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
refactor notebook state to better support collaboration (#288)
Myles Scolnick9ab23c53c496
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex c2872ba0a4..67e48851f5 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -18,7 +18,14 @@ import { UUID } from "./utils/uuid";import clsx from "clsx";import { WebSocketState } from "./core/websocket/types";import { useMarimoWebSocket } from "./core/websocket/useMarimoWebSocket";-import { useCellActions, useCells } from "./core/state/cells";+import {+ notebookCells,+ notebookIsRunning,+ notebookNeedsRun,+ notebookNeedsSave,+ useCellActions,+ useNotebook,+} from "./core/state/cells";import { Disconnected } from "./editor/Disconnected";import { AppConfig, UserConfig } from "./core/config/config";import { toggleAppMode, viewStateAtom } from "./core/mode";@@ -55,7 +62,7 @@ interface AppProps {}export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {- const cells = useCells();+ const notebook = useNotebook();const { setCells, updateCellCode } = useCellActions();const [viewState, setViewState] = useAtom(viewStateAtom);const [filename, setFilename] = useState(getFilenameFromDOM());@@ -66,7 +73,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {const isEditing = viewState.mode === "edit";const isPresenting = viewState.mode === "present";const isReading = viewState.mode === "read";- const isRunning = cells.present.some((cell) => cell.status === "running");+ const isRunning = notebookIsRunning(notebook);function alertSaveFailed() {openAlert("Failed to save notebook: not connected to a kernel.");@@ -108,14 +115,11 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {});- const codes = cells.present.map((cell) => cell.code);- const cellNames = cells.present.map((cell) => cell.name);- const configs = cells.present.map((cell) => cell.config);- const needsSave =- savedCodes.length !== codes.length ||- savedCodes.some((code, index) => codes[index] !== code) ||- savedConfigs.length !== configs.length ||- savedConfigs.some((config, index) => configs[index] !== config);+ const cells = notebookCells(notebook);+ const codes = cells.map((cell) => cell.code);+ const cellNames = cells.map((cell) => cell.name);+ const configs = cells.map((cell) => cell.config);+ const needsSave = notebookNeedsSave(notebook, savedCodes, savedConfigs);// Save the notebook with the given filenameconst saveNotebook = useEvent((filename: string, userInitiated: boolean) => {@@ -273,7 +277,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {return JSON.stringify({filename: filename,- cells: cells.present.map((cell) => {+ cells: cells.map((cell) => {return { name: cell.name, code: cell.code };}),},@@ -286,7 +290,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {const editableCellsArray = (<CellArray- cells={cells}+ notebook={notebook}connStatus={connStatus}mode={viewState.mode}userConfig={userConfig}@@ -334,7 +338,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {</div>{/* Don't render until we have a single cell */}- {cells.present.length > 0 && (+ {cells.length > 0 && (<CellsRenderer appConfig={appConfig} mode={viewState.mode}><SortableCellsProvider disabled={!isEditing}>{editableCellsArray}@@ -356,10 +360,8 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {onRun={runStaleCells}closed={connStatus.state === WebSocketState.CLOSED}running={isRunning}- needsRun={cells.present.some(- (cell) => cell.edited || cell.interrupted- )}- undoAvailable={cells.history.length > 0}+ needsRun={notebookNeedsRun(notebook)}+ undoAvailable={notebook.history.length > 0}appWidth={appConfig.width}/>)}diff --git a/frontend/src/components/sort/SortableCellsProvider.tsx b/frontend/src/components/sort/SortableCellsProvider.tsxindex 9ca7af5018..b6f4186f93 100644--- a/frontend/src/components/sort/SortableCellsProvider.tsx+++ b/frontend/src/components/sort/SortableCellsProvider.tsx@@ -15,7 +15,7 @@ import {sortableKeyboardCoordinates,verticalListSortingStrategy,} from "@dnd-kit/sortable";-import { useCellActions, useCells } from "../../core/state/cells";+import { useCellActions, useNotebook } from "../../core/state/cells";import { useEvent } from "../../hooks/useEvent";import { CellId } from "@/core/model/ids";@@ -28,7 +28,7 @@ const SortableCellsProviderInternal = ({children,disabled,}: SortableCellsProviderProps) => {- const cells = useCells();+ const notebook = useNotebook();const { dropCellOver } = useCellActions();const sensors = useSensors(@@ -43,7 +43,7 @@ const SortableCellsProviderInternal = ({}));- const ids = cells.present.map((item) => item.key.toString());+ const ids = notebook.cellIds;const handleDragEnd = useEvent((event: DragEndEvent) => {const { active, over } = event;diff --git a/frontend/src/core/codemirror/completion/completer.ts b/frontend/src/core/codemirror/completion/completer.tsindex 24ab2ec2e2..d1ca2359ba 100644--- a/frontend/src/core/codemirror/completion/completer.ts+++ b/frontend/src/core/codemirror/completion/completer.ts@@ -4,7 +4,7 @@ import { CompletionContext, CompletionResult } from "@codemirror/autocomplete";import { AUTOCOMPLETER, Autocompleter } from "./Autocompleter";import { Logger } from "../../../utils/Logger";import { CellId, HTMLCellId } from "@/core/model/ids";-import { getCells } from "@/core/state/cells";+import { getCellEditorView } from "@/core/state/cells";import { dispatchShowTooltip } from "./hints";export async function completer(@@ -38,8 +38,7 @@ export async function completer(});if (tooltip) {// Find EditorView for the cell- const editorView = getCells().find((cell) => cell.key === cellId)?.ref- .current?.editorView;+ const editorView = getCellEditorView(cellId);if (editorView) {dispatchShowTooltip(editorView, tooltip);}diff --git a/frontend/src/core/codemirror/copilot/getCodes.ts b/frontend/src/core/codemirror/copilot/getCodes.tsindex 538ae61cee..2d7afacbec 100644--- a/frontend/src/core/codemirror/copilot/getCodes.ts+++ b/frontend/src/core/codemirror/copilot/getCodes.ts@@ -1,16 +1,16 @@/* Copyright 2023 Marimo. All rights reserved. */-import { getCells } from "@/core/state/cells";+import { getAllEditorViews } from "@/core/state/cells";export function getCodes(otherCode: string) {// Get all other cells' code// Put `import` statements at the top, as it can help copilot give better suggestions// TODO: we should sort this topologically- const codes = getCells()- .map((cell) => {- if (cell.ref.current?.editorView.state.doc.toString() === otherCode) {+ const codes = getAllEditorViews()+ .map((editorView) => {+ if (editorView.state.doc.toString() === otherCode) {return null;}- return cell.ref.current?.editorView.state.doc.toString();+ return editorView.state.doc.toString();}).filter(Boolean).sort((a, b) => {diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.tsindex f56ce1a3fd..40789bbf9e 100644--- a/frontend/src/core/codemirror/format.ts+++ b/frontend/src/core/codemirror/format.ts@@ -3,7 +3,11 @@ import { EditorView } from "@codemirror/view";import { CellId } from "../model/ids";import { Objects } from "../../utils/objects";import { sendFormat } from "../network/requests";-import { CellActions, getCells } from "../state/cells";+import {+ CellActions,+ getNotebook,+ notebookCellEditorViews,+} from "../state/cells";/*** Format the code in the editor views via the marimo server,@@ -48,13 +52,6 @@ export async function formatEditorViews(* Format all cells in the notebook.*/export function formatAll(updateCellCode: CellActions["updateCellCode"]) {- const cells = getCells();- const views: Record<CellId, EditorView> = {};- cells.forEach((cell) => {- const editorView = cell.ref.current?.editorView;- if (editorView) {- views[cell.key] = editorView;- }- });+ const views = notebookCellEditorViews(getNotebook());return formatEditorViews(views, updateCellCode);}diff --git a/frontend/src/core/model/cells.ts b/frontend/src/core/model/cells.tsindex d01fc3acb9..d0604ff1a8 100644--- a/frontend/src/core/model/cells.ts+++ b/frontend/src/core/model/cells.ts@@ -1,13 +1,10 @@/* Copyright 2023 Marimo. All rights reserved. */-import { createRef } from "react";import { OutputMessage } from "../kernel/messages";import { SerializedEditorState } from "../codemirror/types";-import { CellHandle } from "../../editor/Cell";-import { CellId } from "./ids";import { Outline } from "./outline";-import { parseOutline } from "../dom/outline";+import { CellId } from "./ids";-export const DEFAULT_CELL_NAME = "__";+const DEFAULT_CELL_NAME = "__";/*** The status of a cell.@@ -29,51 +26,59 @@ export type CellStatus =* Create a new cell with default state.*/export function createCell({- key,- ref = createRef(),+ id,name = DEFAULT_CELL_NAME,code = "",- output = null,- consoleOutputs = [],- status = "idle",- edited = false,- interrupted = false,- errored = false,- stopped = false,- runElapsedTimeMs = null,- runStartTimestamp = null,lastCodeRun = null,- serializedEditorState = null,+ edited = false,config = {},-}: Partial<CellState> & Pick<CellState, "key">): CellState {+ serializedEditorState = null,+}: Partial<CellData> & { id: CellId }): CellData {return {- key: key,- ref: ref,+ id: id,config: config,name: name,- output: output,- outline: parseOutline(output),code: code,- status: status,edited: edited,- interrupted: interrupted,- errored: errored,- stopped: stopped,- runElapsedTimeMs: runElapsedTimeMs,- runStartTimestamp: runStartTimestamp,lastCodeRun: lastCodeRun,- consoleOutputs: consoleOutputs,serializedEditorState: serializedEditorState,};}-export interface CellState {- /** unique key */- key: CellId;+export function createCellRuntimeState(): CellRuntimeState {+ return {+ outline: null,+ output: null,+ consoleOutputs: [],+ status: "idle",+ interrupted: false,+ errored: false,+ stopped: false,+ runElapsedTimeMs: null,+ runStartTimestamp: null,+ };+}++/**+ * Data of the cell+ */+export interface CellData {+ id: CellId;/** user-given name, or default */name: string;/** current contents of the editor */code: string;+ /** whether this cell has been modified since its last run */+ edited: boolean;+ /** snapshot of code that was last run */+ lastCodeRun: string | null;+ /** cell configuration */+ config: CellConfig;+ /** serialized state of the underlying editor */+ serializedEditorState: SerializedEditorState | null;+}++export interface CellRuntimeState {/** a message encoding the cell's output */output: OutputMessage | null;/** TOC outline */@@ -82,14 +87,10 @@ export interface CellState {consoleOutputs: OutputMessage[];/** current status of the cell */status: CellStatus;- /** whether this cell has been modified since its last run */- edited: boolean;/** whether this cell has been interrupted since its last run */interrupted: boolean;/** whether this cell was stopped with mo.stop */stopped: boolean;- /** snapshot of code that was last run */- lastCodeRun: string | null;/*** whether marimo encountered an error when trying to register or run* this cell (such as a multiple definition error)@@ -99,14 +100,6 @@ export interface CellState {runStartTimestamp: number | null;/** run elapsed time, in milliseconds */runElapsedTimeMs: number | null;- /** serialized state of the underyling editor */- serializedEditorState: SerializedEditorState | null;-- /** handle to access the underlying cell */- ref: React.RefObject<CellHandle>;-- /** cell configuration */- config: CellConfig;}export interface CellConfig {diff --git a/frontend/src/core/model/scrollCellIntoView.ts b/frontend/src/core/model/scrollCellIntoView.tsindex fa7989fd86..04bf6c4d9b 100644--- a/frontend/src/core/model/scrollCellIntoView.ts+++ b/frontend/src/core/model/scrollCellIntoView.ts@@ -1,15 +1,19 @@/* Copyright 2023 Marimo. All rights reserved. */+import { RefObject } from "react";import { Logger } from "../../utils/Logger";-import { CellState } from "./cells";-import { HTMLCellId } from "./ids";+import { CellId, HTMLCellId } from "./ids";+import { CellHandle } from "@/editor/Cell";-export function focusAndScrollCellIntoView(cell: CellState) {+export function focusAndScrollCellIntoView(+ cellId: CellId,+ cell: RefObject<CellHandle>+) {if (!cell) {return;}- cell.ref.current?.editorView.focus();- const element = document.getElementById(HTMLCellId.create(cell.key));+ cell.current?.editorView.focus();+ const element = document.getElementById(HTMLCellId.create(cellId));if (element) {element.scrollIntoView({behavior: "smooth",diff --git a/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snapindex ecb24f97fe..c59d3e75d0 100644--- a/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap+++ b/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap@@ -7,15 +7,12 @@ exports[`cell reducer > can run a stale cell 1`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "1","interrupted": false,- "key": "1","lastCodeRun": "mo.slider()","name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,@@ -31,15 +28,12 @@ exports[`cell reducer > can run a stale cell 2`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "1","interrupted": false,- "key": "1","lastCodeRun": "mo.slider()","name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,@@ -55,15 +49,12 @@ exports[`cell reducer > can run a stopped cell 1`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "mo.md('This has an ancestor that was stopped')","name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,@@ -79,15 +70,12 @@ exports[`cell reducer > can run a stopped cell 2`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "mo.md('This has an ancestor that was stopped')","name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,@@ -103,8 +91,8 @@ exports[`cell reducer > can run a stopped cell 3`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "mo.md('This has an ancestor that was stopped')","name": "__","outline": null,@@ -120,9 +108,6 @@ exports[`cell reducer > can run a stopped cell 3`] = `"mimetype": "application/vnd.marimo+error","timestamp": 20,},- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,@@ -138,8 +123,8 @@ exports[`cell reducer > can run a stopped cell 4`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "mo.md('This has an ancestor that was stopped')","name": "__","outline": null,@@ -155,9 +140,6 @@ exports[`cell reducer > can run a stopped cell 4`] = `"mimetype": "application/vnd.marimo+error","timestamp": 20,},- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,@@ -173,15 +155,12 @@ exports[`cell reducer > can run a stopped cell 5`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "mo.md('This has an ancestor that was stopped')","name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": 40,"serializedEditorState": null,@@ -197,15 +176,12 @@ exports[`cell reducer > can run cell and receive cell messages 1`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": null,"name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,@@ -221,15 +197,12 @@ exports[`cell reducer > can run cell and receive cell messages 2`] = `"consoleOutputs": [],"edited": true,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": null,"name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,@@ -245,15 +218,12 @@ exports[`cell reducer > can run cell and receive cell messages 3`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "import marimo as mo","name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,@@ -269,15 +239,12 @@ exports[`cell reducer > can run cell and receive cell messages 4`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "import marimo as mo","name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": null,"serializedEditorState": null,@@ -293,15 +260,12 @@ exports[`cell reducer > can run cell and receive cell messages 5`] = `"consoleOutputs": [],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "import marimo as mo","name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,@@ -324,15 +288,12 @@ exports[`cell reducer > can run cell and receive cell messages 6`] = `],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "import marimo as mo","name": "__","outline": null,"output": null,- "ref": {- "current": null,- },"runElapsedTimeMs": null,"runStartTimestamp": 20,"serializedEditorState": null,@@ -355,8 +316,8 @@ exports[`cell reducer > can run cell and receive cell messages 7`] = `],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "import marimo as mo","name": "__","outline": null,@@ -366,9 +327,6 @@ exports[`cell reducer > can run cell and receive cell messages 7`] = `"mimetype": "text/plain","timestamp": 0,},- "ref": {- "current": null,- },"runElapsedTimeMs": 13000,"runStartTimestamp": null,"serializedEditorState": null,@@ -392,8 +350,8 @@ import numpy",],"edited": true,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "import marimo as mo","name": "__","outline": null,@@ -403,9 +361,6 @@ import numpy","mimetype": "text/plain","timestamp": 0,},- "ref": {- "current": null,- },"runElapsedTimeMs": 13000,"runStartTimestamp": null,"serializedEditorState": null,@@ -428,8 +383,8 @@ exports[`cell reducer > can run cell and receive cell messages 9`] = `],"edited": false,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "import marimo as mo","name": "__","outline": null,@@ -439,9 +394,6 @@ exports[`cell reducer > can run cell and receive cell messages 9`] = `"mimetype": "text/plain","timestamp": 0,},- "ref": {- "current": null,- },"runElapsedTimeMs": 13000,"runStartTimestamp": null,"serializedEditorState": null,@@ -465,8 +417,8 @@ import numpy",],"edited": true,"errored": false,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "import marimo as mo","name": "__","outline": null,@@ -476,9 +428,6 @@ import numpy","mimetype": "text/plain","timestamp": 0,},- "ref": {- "current": null,- },"runElapsedTimeMs": 13000,"runStartTimestamp": null,"serializedEditorState": null,@@ -502,8 +451,8 @@ import numpy",],"edited": false,"errored": true,+ "id": "0","interrupted": false,- "key": "0","lastCodeRun": "import marimo as moimport numpy","name": "__",@@ -520,9 +469,6 @@ import numpy","mimetype": "application/vnd.marimo+error","timestamp": 0,},- "ref": {- "current": null,- },"runElapsedTimeMs": 11000,"runStartTimestamp": null,"serializedEditorState": null,@@ -546,9 +492,10 @@ import numpy",],"edited": false,"errored": false,+ "id": "0","interrupted": true,- "key": "0",- "lastCodeRun": null,+ "lastCodeRun": "import marimo as mo+import numpy","name": "__","outline": null,"output": {@@ -561,9 +508,6 @@ import numpy","mimetype": "application/vnd.marimo+error","timestamp": 0,},- "ref": {- "current": null,- },"runElapsedTimeMs": 11000,"runStartTimestamp": null,"serializedEditorState": null,diff --git a/frontend/src/core/state/__tests__/cells.test.ts b/frontend/src/core/state/__tests__/cells.test.tsindex 7ea1538946..4c43e42ac1 100644--- a/frontend/src/core/state/__tests__/cells.test.ts+++ b/frontend/src/core/state/__tests__/cells.test.ts@@ -1,31 +1,38 @@/* Copyright 2023 Marimo. All rights reserved. */import { beforeEach, describe, expect, it } from "vitest";-import { CellState, createCell } from "../../model/cells";-import { CellsAndHistory, exportedForTesting } from "../cells";+import {+ NotebookState,+ exportedForTesting,+ flattenNotebookCells,+ notebookCells,+} from "../cells";import { CellId } from "@/core/model/ids";const { initialCellState, reducer, createActions } = exportedForTesting;-function formatCells(cells: CellState[]) {+function formatCells(notebook: NotebookState) {+ const cells = notebookCells(notebook);return `\n${cells- .map((cell) => [`key: ${cell.key}`, `code: '${cell.code}'`].join("\n"))+ .map((cell) => [`key: ${cell.id}`, `code: '${cell.code}'`].join("\n")).join("\n\n")}`;}describe("cell reducer", () => {- let state: CellsAndHistory;+ let state: NotebookState;+ let cells: ReturnType<typeof flattenNotebookCells>;let firstCellId: CellId;const actions = createActions((action) => {state = reducer(state, action);+ cells = flattenNotebookCells(state);});beforeEach(() => {CellId.reset();state = initialCellState();- state.present = [createCell({ key: CellId.create() })];- firstCellId = state.present[0].key;+ actions.createNewCell({ cellId: undefined!, before: false });+ firstCellId = state.cellIds[0];});it("can add a cell after another cell", () => {@@ -33,7 +40,7 @@ describe("cell reducer", () => {cellId: firstCellId,before: false,});- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 0code: ''@@ -48,7 +55,7 @@ describe("cell reducer", () => {cellId: firstCellId,before: true,});- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 1code: ''@@ -66,7 +73,7 @@ describe("cell reducer", () => {actions.deleteCell({cellId: firstCellId,});- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 1code: ''"@@ -74,7 +81,7 @@ describe("cell reducer", () => {// undoactions.undoDeleteCell();- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 2code: ''@@ -90,7 +97,7 @@ describe("cell reducer", () => {code: "import numpy as np",formattingChange: false,});- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 0code: 'import numpy as np'"@@ -102,7 +109,7 @@ describe("cell reducer", () => {cellId: firstCellId,before: false,});- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 0code: ''@@ -116,7 +123,7 @@ describe("cell reducer", () => {cellId: firstCellId,before: false,});- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 1code: ''@@ -130,7 +137,7 @@ describe("cell reducer", () => {cellId: firstCellId,before: true,});- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 0code: ''@@ -149,7 +156,7 @@ describe("cell reducer", () => {cellId: "1" as CellId,before: false,});- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 0code: ''@@ -166,7 +173,7 @@ describe("cell reducer", () => {cellId: firstCellId,overCellId: "2" as CellId,});- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 1code: ''@@ -183,7 +190,7 @@ describe("cell reducer", () => {cellId: firstCellId,overCellId: "2" as CellId,});- expect(formatCells(state.present)).toMatchInlineSnapshot(`+ expect(formatCells(state)).toMatchInlineSnapshot(`"key: 1code: ''@@ -200,7 +207,7 @@ describe("cell reducer", () => {// HAPPY PATH/////////////////// Initial state- let cell = state.present[0];+ let cell = cells[0];expect(cell.status).toBe("idle");expect(cell.lastCodeRun).toBe(null);expect(cell.edited).toBe(false);@@ -212,7 +219,7 @@ describe("cell reducer", () => {code: "import marimo as mo",formattingChange: false,});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("idle");expect(cell.lastCodeRun).toBe(null);expect(cell.edited).toBe(true);@@ -222,7 +229,7 @@ describe("cell reducer", () => {actions.prepareForRun({cellId: firstCellId,});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("idle");expect(cell.lastCodeRun).toBe("import marimo as mo");expect(cell.edited).toBe(false);@@ -239,7 +246,7 @@ describe("cell reducer", () => {timestamp: new Date(10).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("queued");expect(cell.lastCodeRun).toBe("import marimo as mo");expect(cell.edited).toBe(false);@@ -258,7 +265,7 @@ describe("cell reducer", () => {timestamp: new Date(20).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("running");expect(cell.lastCodeRun).toBe("import marimo as mo");expect(cell.edited).toBe(false);@@ -282,7 +289,7 @@ describe("cell reducer", () => {timestamp: new Date(22).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("running");expect(cell.edited).toBe(false);expect(cell.runElapsedTimeMs).toBe(null);@@ -310,7 +317,7 @@ describe("cell reducer", () => {timestamp: new Date(33).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("idle");expect(cell.edited).toBe(false);expect(cell.runElapsedTimeMs).toBe(13_000);@@ -325,7 +332,7 @@ describe("cell reducer", () => {code: "import marimo as mo\nimport numpy",formattingChange: false,});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("idle");expect(cell.edited).toBe(true);expect(cell).toMatchSnapshot(); // snapshot everything as a catch all@@ -336,7 +343,7 @@ describe("cell reducer", () => {code: "import marimo as mo",formattingChange: false,});- cell = state.present[0];+ cell = cells[0];expect(cell.edited).toBe(false);expect(cell).toMatchSnapshot(); // snapshot everything as a catch all@@ -346,7 +353,7 @@ describe("cell reducer", () => {code: "import marimo as mo\nimport numpy",formattingChange: false,});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("idle");expect(cell.lastCodeRun).toBe("import marimo as mo");expect(cell.edited).toBe(true);@@ -358,7 +365,7 @@ describe("cell reducer", () => {actions.prepareForRun({cellId: firstCellId,});- cell = state.present[0];+ cell = cells[0];expect(cell.output).not.toBe(null); // keep old output// Queueactions.handleCellMessage({@@ -371,7 +378,7 @@ describe("cell reducer", () => {timestamp: new Date(40).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.output).not.toBe(null); // keep old output// Runningactions.handleCellMessage({@@ -384,7 +391,7 @@ describe("cell reducer", () => {timestamp: new Date(50).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.output).not.toBe(null); // keep old output// Receive erroractions.handleCellMessage({@@ -404,7 +411,7 @@ describe("cell reducer", () => {timestamp: new Date(61).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.output).not.toBe(null); // keep old outputexpect(cell.status).toBe("idle");expect(cell.lastCodeRun).toBe("import marimo as mo\nimport numpy");@@ -419,7 +426,7 @@ describe("cell reducer", () => {actions.prepareForRun({cellId: firstCellId,});- cell = state.present[0];+ cell = cells[0];expect(cell.output).not.toBe(null); // keep old output// Queueactions.handleCellMessage({@@ -432,7 +439,7 @@ describe("cell reducer", () => {timestamp: new Date(40).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.output).not.toBe(null); // keep old output// Runningactions.handleCellMessage({@@ -445,7 +452,7 @@ describe("cell reducer", () => {timestamp: new Date(50).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.output).not.toBe(null); // keep old output// Receive erroractions.handleCellMessage({@@ -463,9 +470,9 @@ describe("cell reducer", () => {timestamp: new Date(61).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("idle");- expect(cell.lastCodeRun).toBe(null);+ expect(cell.lastCodeRun).toBe(cell.code);expect(cell.edited).toBe(false);expect(cell.runElapsedTimeMs).toBe(11_000);expect(cell.runStartTimestamp).toBe(null);@@ -484,7 +491,7 @@ describe("cell reducer", () => {cellId: firstCellId,before: false,});- const secondCell = state.present[1].key;+ const secondCell = cells[1].id;// Update codeactions.updateCellCode({code: "mo.slider()",@@ -508,7 +515,7 @@ describe("cell reducer", () => {timestamp: new Date(10).getTime(),},});- let cell = state.present[1];+ let cell = cells[1];expect(cell.status).toBe("queued");expect(cell.lastCodeRun).toBe("mo.slider()");expect(cell.edited).toBe(false);@@ -527,7 +534,7 @@ describe("cell reducer", () => {timestamp: new Date(20).getTime(),},});- cell = state.present[1];+ cell = cells[1];expect(cell.status).toBe("stale");expect(cell.lastCodeRun).toBe("mo.slider()");expect(cell.edited).toBe(false);@@ -537,13 +544,13 @@ describe("cell reducer", () => {});it("can format code and update cell", () => {- const firstCellId = state.present[0].key;+ const firstCellId = cells[0].id;actions.updateCellCode({cellId: firstCellId,code: "import marimo as mo",formattingChange: false,});- let cell = state.present[0];+ let cell = cells[0];expect(cell.status).toBe("idle");expect(cell.lastCodeRun).toBe(null);expect(cell.edited).toBe(true);@@ -574,7 +581,7 @@ describe("cell reducer", () => {});// Check steady state- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("idle");expect(cell.edited).toBe(false);expect(cell.lastCodeRun).toBe("import marimo as mo");@@ -585,15 +592,15 @@ describe("cell reducer", () => {code: "import marimo as mo",formattingChange: true,});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("idle");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];+ const firstCellId = cells[0].id;+ let cell = cells[0];// Starts emptyexpect(cell.config).toEqual({});@@ -601,7 +608,7 @@ describe("cell reducer", () => {cellId: firstCellId,config: { disabled: true },});- cell = state.present[0];+ cell = cells[0];expect(cell.config.disabled).toBe(true);// Revert@@ -609,7 +616,7 @@ describe("cell reducer", () => {cellId: firstCellId,config: { disabled: false },});- cell = state.present[0];+ cell = cells[0];expect(cell.config.disabled).toBe(false);});@@ -637,7 +644,7 @@ describe("cell reducer", () => {timestamp: new Date(10).getTime(),},});- let cell = state.present[0];+ let cell = cells[0];expect(cell.status).toBe("queued");expect(cell.lastCodeRun).toBe("mo.md('This has an ancestor that was stopped')"@@ -658,7 +665,7 @@ describe("cell reducer", () => {timestamp: new Date(20).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell).toMatchSnapshot(); // snapshot everything as a catch all// Receive stop output@@ -683,7 +690,7 @@ describe("cell reducer", () => {timestamp: new Date(20).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("idle");// eslint-disable-next-line @typescript-eslint/no-explicit-anyexpect((cell.output?.data as any)[0].msg).toBe(@@ -703,7 +710,7 @@ describe("cell reducer", () => {timestamp: new Date(30).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("queued");expect(cell.stopped).toBe(true);expect(cell).toMatchSnapshot(); // snapshot everything as a catch all@@ -719,7 +726,7 @@ describe("cell reducer", () => {timestamp: new Date(40).getTime(),},});- cell = state.present[0];+ cell = cells[0];expect(cell.status).toBe("running");expect(cell.stopped).toBe(false);expect(cell.output).toBe(null);diff --git a/frontend/src/core/state/cell.ts b/frontend/src/core/state/cell.tsindex 6fff1f191c..87b7f21849 100644--- a/frontend/src/core/state/cell.ts+++ b/frontend/src/core/state/cell.ts@@ -1,14 +1,14 @@/* Copyright 2023 Marimo. All rights reserved. */import { logNever } from "@/utils/assertNever";import { CellMessage } from "../kernel/messages";-import { CellState } from "../model/cells";+import { CellRuntimeState } from "../model/cells";import { collapseConsoleOutputs } from "../model/collapseConsoleOutputs";import { parseOutline } from "../dom/outline";export function transitionCell(- cell: CellState,+ cell: CellRuntimeState,message: CellMessage-): CellState {+): CellRuntimeState {const nextCell = { ...cell };// Handle status transition and update output; message.status !== null@@ -57,10 +57,7 @@ export function transitionCell(message.output.mimetype === "application/vnd.marimo+error") {if (message.output.data.some((error) => error["type"] === "interruption")) {- // This cell needs to be re-run, even if its code contents haven't- // changed since it was last run. Force the re-run state by clearing- // its lastCodeRun- nextCell.lastCodeRun = null;+ // Interrupted helps distinguish that the cell is stalenextCell.interrupted = true;} else if (message.output.data.some((error) => error["type"] === "ancestor-stopped")@@ -101,14 +98,14 @@ export function transitionCell(// Should be called when a cell's code is registered with the kernel for// execution.-export function prepareCellForExecution(cell: CellState): CellState {+export function prepareCellForExecution(+ cell: CellRuntimeState+): CellRuntimeState {const nextCell = { ...cell };nextCell.interrupted = false;nextCell.errored = false;- nextCell.edited = false;nextCell.runElapsedTimeMs = null;- nextCell.lastCodeRun = cell.code.trim();return nextCell;}diff --git a/frontend/src/core/state/cells.ts b/frontend/src/core/state/cells.tsindex eabeb6e3a2..ea2c09a418 100644--- a/frontend/src/core/state/cells.ts+++ b/frontend/src/core/state/cells.ts@@ -1,8 +1,14 @@/* Copyright 2023 Marimo. All rights reserved. */import { atom, useAtomValue, useSetAtom } from "jotai";-import { ReducerWithoutAction, useMemo } from "react";+import { ReducerWithoutAction, createRef, useMemo } from "react";import { CellMessage } from "../kernel/messages";-import { CellConfig, CellState, createCell } from "../model/cells";+import {+ CellConfig,+ CellRuntimeState,+ CellData,+ createCell,+ createCellRuntimeState,+} from "../model/cells";import {scrollToBottom,scrollToTop,@@ -13,27 +19,41 @@ 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 { arrayInsert, arrayDelete, arrayShallowEquals } from "@/utils/arrays";import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";import { mergeOutlines } from "../dom/outline";+import { CellHandle } from "@/editor/Cell";+import { Logger } from "@/utils/Logger";+import { Objects } from "@/utils/objects";+import { EditorView } from "@codemirror/view";-/* The array of cells on the page, together with a history of- * deleted cells to implement an "undo delete" action+/**+ * The state of the notebook.*/-export interface CellsAndHistory {+export interface NotebookState {+ /**+ * Order of cells on the page.+ */+ cellIds: CellId[];+ /**+ * Map of cells to their view state+ */+ cellData: Record<CellId, CellData>;/**- * The array of cells on the page+ * Map of cells to their runtime state*/- present: CellState[];+ cellRuntime: Record<CellId, CellRuntimeState>;/**- * Tuples of deleted cells, represented by (cell name, serialized editor- * config, and insertion index), so that cell deletion can be undone+ * Cell handlers+ */+ cellHandles: Record<CellId, React.RefObject<CellHandle>>;+ /**+ * Array of deleted cells (with their data and index) so that cell deletion can be undone** (CodeMirror types the serialized config as any.)*/// eslint-disable-next-line @typescript-eslint/no-explicit-any- history: Array<[string, any, number]>;-+ history: Array<{ name: string; serializedEditorState: any; index: number }>;/*** Key of cell to scroll to; typically set by actions that re-order the cell* array. Call the SCROLL_TO_TARGET action to scroll to the specified cell@@ -42,41 +62,62 @@ export interface CellsAndHistory {scrollKey: CellId | null;}-function initialCellState(): CellsAndHistory {+/**+ * Initial state of the notebook.+ */+function initialNotebookState(): NotebookState {return {- present: [],+ cellIds: [],+ cellData: {},+ cellRuntime: {},+ cellHandles: {},history: [],scrollKey: null,};}-const { reducer, createActions } = createReducer(initialCellState, {+/**+ * Actions and reducer for the notebook state.+ */+const { reducer, createActions } = createReducer(initialNotebookState, {createNewCell: (state, action: { cellId: CellId; before: boolean }) => {const { cellId, before } = action;- const index = state.present.findIndex((cell) => cell.key === cellId);+ const index = state.cellIds.indexOf(cellId);const insertionIndex = before ? index : index + 1;- const cell = createCell({ key: CellId.create() });+ const newCellId = CellId.create();return {...state,- present: arrayInsert(state.present, insertionIndex, cell),- scrollKey: cell.key,+ cellIds: arrayInsert(state.cellIds, insertionIndex, newCellId),+ cellData: {+ ...state.cellData,+ [newCellId]: createCell({ id: newCellId }),+ },+ cellRuntime: {+ ...state.cellRuntime,+ [newCellId]: createCellRuntimeState(),+ },+ cellHandles: {+ ...state.cellHandles,+ [newCellId]: createRef(),+ },+ scrollKey: newCellId,};},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];+ const index = state.cellIds.indexOf(cellId);+ const cell = state.cellIds[index];if (before && index === 0) {return {...state,- present: [cell, ...state.present.slice(1)],+ cellIds: [cell, ...state.cellIds.slice(1)],scrollKey: cellId,};- } else if (!before && index === state.present.length - 1) {+ } else if (!before && index === state.cellIds.length - 1) {return {...state,- present: [...state.present.slice(0, -1), cell],+ cellIds: [...state.cellIds.slice(0, -1), cell],scrollKey: cellId,};}@@ -84,103 +125,109 @@ const { reducer, createActions } = createReducer(initialCellState, {return before? {...state,- present: arrayMove(state.present, index, index - 1),+ cellIds: arrayMove(state.cellIds, index, index - 1),scrollKey: cellId,}: {...state,- present: arrayMove(state.present, index, index + 1),+ cellIds: arrayMove(state.cellIds, index, index + 1),scrollKey: cellId,};},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);+ const fromIndex = state.cellIds.indexOf(cellId);+ const toIndex = state.cellIds.indexOf(overCellId);return {...state,- present: arrayMove(state.present, fromIndex, toIndex),+ cellIds: arrayMove(state.cellIds, fromIndex, toIndex),scrollKey: null,};},focusCell: (state, action: { cellId: CellId; before: boolean }) => {- if (state.present.length === 0) {+ if (state.cellIds.length === 0) {return state;}const { cellId, before } = action;- const index = state.present.findIndex((cell) => cell.key === cellId);+ const index = state.cellIds.indexOf(cellId);let focusIndex = before ? index - 1 : index + 1;// clamp- focusIndex = Math.max(0, Math.min(focusIndex, state.present.length - 1));+ focusIndex = Math.max(0, Math.min(focusIndex, state.cellIds.length - 1));+ const focusCellId = state.cellIds[focusIndex];// can scroll immediately, without setting scrollKey in state, because// CellArray won't need to re-render- focusAndScrollCellIntoView(state.present[focusIndex]);+ focusAndScrollCellIntoView(focusCellId, state.cellHandles[focusCellId]);return state;},focusTopCell: (state) => {- if (state.present.length === 0) {+ if (state.cellIds.length === 0) {return state;}- state.present[0].ref.current?.editorView.focus();+ const cellKey = state.cellIds[0];+ state.cellHandles[cellKey].current?.editorView.focus();scrollToTop();return state;},focusBottomCell: (state) => {- if (state.present.length === 0) {+ if (state.cellIds.length === 0) {return state;}- state.present[state.present.length - 1].ref.current?.editorView.focus();+ const cellKey = state.cellIds[state.cellIds.length - 1];+ state.cellHandles[cellKey].current?.editorView.focus();scrollToBottom();return state;},sendToTop: (state, action: { cellId: CellId }) => {- if (state.present.length === 0) {+ if (state.cellIds.length === 0) {return state;}const { cellId } = action;- const index = state.present.findIndex((cell) => cell.key === cellId);+ const index = state.cellIds.indexOf(cellId);return {...state,- present: arrayMove(state.present, index, 0),+ cellIds: arrayMove(state.cellIds, index, 0),scrollKey: cellId,};},sendToBottom: (state, action: { cellId: CellId }) => {- if (state.present.length === 0) {+ if (state.cellIds.length === 0) {return state;}const { cellId } = action;- const index = state.present.findIndex((cell) => cell.key === cellId);+ const index = state.cellIds.indexOf(cellId);return {...state,- present: arrayMove(state.present, index, state.present.length - 1),+ cellIds: arrayMove(state.cellIds, index, state.cellIds.length - 1),scrollKey: cellId,};},deleteCell: (state, action: { cellId: CellId }) => {const cellId = action.cellId;- if (state.present.length === 1) {+ if (state.cellIds.length === 1) {return state;}- const index = state.present.findIndex((cell) => cell.key === cellId);+ const index = state.cellIds.indexOf(cellId);+ const cellKey = state.cellIds[index];const focusIndex = index === 0 ? 1 : index - 1;- const scrollKey = state.present[focusIndex].key;+ const scrollKey = state.cellIds[focusIndex];return {- present: arrayDelete(state.present, index),+ ...state,+ cellIds: arrayDelete(state.cellIds, index),history: [...state.history,- [- state.present[index].name,- state.present[index].ref.current?.editorStateJSON(),- index,- ],+ {+ name: state.cellData[cellKey].name,+ serializedEditorState:+ state.cellHandles[cellKey].current?.editorStateJSON(),+ index: index,+ },],scrollKey: scrollKey,};@@ -191,13 +238,14 @@ const { reducer, createActions } = createReducer(initialCellState, {} else {const mostRecentlyDeleted = state.history[state.history.length - 1];- const name = mostRecentlyDeleted[0];- const serializedEditorState = mostRecentlyDeleted[1] || {- doc: "",- };- const index = mostRecentlyDeleted[2];+ const {+ name,+ serializedEditorState = { doc: "" },+ index,+ } = mostRecentlyDeleted;+ const cellId = CellId.create();const undoCell = createCell({- key: CellId.create(),+ id: cellId,name,code: serializedEditorState.doc,edited: serializedEditorState.doc.trim().length > 0,@@ -205,7 +253,19 @@ const { reducer, createActions } = createReducer(initialCellState, {});return {...state,- present: arrayInsert(state.present, index, undoCell),+ cellIds: arrayInsert(state.cellIds, index, cellId),+ cellData: {+ ...state.cellData,+ [cellId]: undoCell,+ },+ cellRuntime: {+ ...state.cellRuntime,+ [cellId]: createCellRuntimeState(),+ },+ cellHandles: {+ ...state.cellHandles,+ [cellId]: createRef(),+ },history: state.history.slice(0, -1),};}@@ -223,13 +283,13 @@ const { reducer, createActions } = createReducer(initialCellState, {}) => {const { cellId, code, formattingChange } = action;- const cellToUpdate = state.present.find((cell) => cell.key === cellId);+ const cellIndex = state.cellIds.indexOf(cellId);- if (!cellToUpdate || cellToUpdate.code === code) {+ if (cellIndex === -1) {return state;}- return updateCell(state, cellId, (cell) => {+ return updateCellData(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@@ -250,7 +310,7 @@ const { reducer, createActions } = createReducer(initialCellState, {action: { cellId: CellId; config: Partial<CellConfig> }) => {const { cellId, config } = action;- return updateCell(state, cellId, (cell) => {+ return updateCellData(state, cellId, (cell) => {return {...cell,config: { ...cell.config, ...config },@@ -258,29 +318,37 @@ const { reducer, createActions } = createReducer(initialCellState, {});},prepareForRun: (state, action: { cellId: CellId }) => {- const cellToUpdate = state.present.find(- (cell) => cell.key === action.cellId- );- if (!cellToUpdate) {- return state;- }- return updateCell(state, action.cellId, (cell) => {+ const newState = updateCellRuntimeState(state, action.cellId, (cell) => {return prepareCellForExecution(cell);});+ return updateCellData(newState, action.cellId, (cell) => {+ return {+ ...cell,+ edited: false,+ lastCodeRun: cell.code.trim(),+ };+ });},handleCellMessage: (state,action: { cellId: CellId; message: CellMessage }) => {const { cellId, message } = action;- return updateCell(state, cellId, (cell) => {+ return updateCellRuntimeState(state, cellId, (cell) => {return transitionCell(cell, message);});},- setCells: (state, cells: CellState[]) => {+ setCells: (state, cells: CellData[]) => {return {...state,- present: cells,+ cellIds: cells.map((cell) => cell.id),+ cellData: Object.fromEntries(cells.map((cell) => [cell.id, cell])),+ cellHandles: Object.fromEntries(+ cells.map((cell) => [cell.id, createRef()])+ ),+ cellRuntime: Object.fromEntries(+ cells.map((cell) => [cell.id, createCellRuntimeState()])+ ),};},/**@@ -294,31 +362,52 @@ const { reducer, createActions } = createReducer(initialCellState, {*/moveToNextCell: (state, action: { cellId: CellId; before: boolean }) => {const { cellId, before } = action;- const index = state.present.findIndex((cell) => cell.key === cellId);+ const index = state.cellIds.indexOf(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(),- });+ if (nextCellIndex === state.cellIds.length) {+ const newCellId = CellId.create();return {...state,- present: [...state.present, newCell],+ cellIds: [...state.cellIds, newCellId],+ cellData: {+ ...state.cellData,+ [newCellId]: createCell({ id: newCellId }),+ },+ cellRuntime: {+ ...state.cellRuntime,+ [newCellId]: createCellRuntimeState(),+ },+ cellHandles: {+ ...state.cellHandles,+ [newCellId]: createRef(),+ },};// Create a new cell at the beginning; again, no need to update// scrollKey} else if (nextCellIndex === -1) {- const newCell = createCell({- key: CellId.create(),- });+ const newCellId = CellId.create();return {...state,- present: [newCell, ...state.present],+ cellIds: [newCellId, ...state.cellIds],+ cellData: {+ ...state.cellData,+ [newCellId]: createCell({ id: newCellId }),+ },+ cellRuntime: {+ ...state.cellRuntime,+ [newCellId]: createCellRuntimeState(),+ },+ cellHandles: {+ ...state.cellHandles,+ [newCellId]: createRef(),+ },};} else {+ const nextCellId = state.cellIds[nextCellIndex];// Just focus, no state change- focusAndScrollCellIntoView(state.present[nextCellIndex]);+ focusAndScrollCellIntoView(nextCellId, state.cellHandles[nextCellId]);return state;}},@@ -328,15 +417,17 @@ const { reducer, createActions } = createReducer(initialCellState, {if (scrollKey === null) {return state;} else {- const index = state.present.findIndex((cell) => cell.key === scrollKey);+ const index = state.cellIds.indexOf(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();+ if (index === state.cellIds.length - 1) {+ const cellId = state.cellIds[state.cellIds.length - 1];+ state.cellHandles[cellId].current?.editorView.focus();scrollToBottom();} else {- focusAndScrollCellIntoView(state.present[index]);+ const nextCellId = state.cellIds[index];+ focusAndScrollCellIntoView(nextCellId, state.cellHandles[nextCellId]);}return {@@ -346,98 +437,210 @@ const { reducer, createActions } = createReducer(initialCellState, {}},foldAll: (state) => {- const targets = state.present.map((cell) => cell.ref.current?.editorView);+ const targets = Object.values(state.cellHandles).map(+ (handle) => handle.current?.editorView+ );foldAllBulk(targets);return state;},unfoldAll: (state) => {- const targets = state.present.map((cell) => cell.ref.current?.editorView);+ const targets = Object.values(state.cellHandles).map(+ (handle) => handle.current?.editorView+ );unfoldAllBulk(targets);return state;},});// Helper function to update a cell in the array-function updateCell(- state: CellsAndHistory,+function updateCellRuntimeState(+ state: NotebookState,+ cellId: CellId,+ cellReducer: ReducerWithoutAction<CellRuntimeState>+) {+ if (!(cellId in state.cellRuntime)) {+ Logger.warn(`Cell ${cellId} not found in state`);+ return state;+ }++ return {+ ...state,+ cellRuntime: {+ ...state.cellRuntime,+ [cellId]: cellReducer(state.cellRuntime[cellId]),+ },+ };+}+function updateCellData(+ state: NotebookState,cellId: CellId,- cellReducer: ReducerWithoutAction<CellState>+ cellReducer: ReducerWithoutAction<CellData>) {+ if (!(cellId in state.cellData)) {+ Logger.warn(`Cell ${cellId} not found in state`);+ return state;+ }+return {...state,- present: state.present.map((cell) =>- cell.key === cellId ? cellReducer(cell) : cell- ),+ cellData: {+ ...state.cellData,+ [cellId]: cellReducer(state.cellData[cellId]),+ },};}-const cellsAtom = atom<CellsAndHistory>(initialCellState());-const cellIdsAtom = atom((get) =>- get(cellsAtom).present.map((cell) => cell.key)-);+/// ATOMS++const notebookAtom = atom<NotebookState>(initialNotebookState());++const cellIdsAtom = atom((get) => get(notebookAtom).cellIds);const cellErrorsAtom = atom((get) => {- const errors = get(cellsAtom)- .present.map((cell) =>- cell.output?.mimetype === "application/vnd.marimo+error"+ const { cellIds, cellRuntime } = get(notebookAtom);+ const errors = cellIds+ .map((cellId) => {+ const cell = cellRuntime[cellId];+ return cell.output?.mimetype === "application/vnd.marimo+error"? {output: cell.output,- cellId: cell.key,+ cellId: cellId,}- : null- )+ : null;+ }).filter(Boolean);return errors;});+export const notebookOutline = atom((get) => {+ const { cellIds, cellRuntime } = get(notebookAtom);+ const outlines = cellIds.map((cellId) => cellRuntime[cellId].outline);+ return mergeOutlines(outlines);+});++export const cellErrorCount = atom((get) => get(cellErrorsAtom).length);++/// HOOKS+/**- * Get the array of cells.+ * React-hook for the array of cells.*/-export const useCells = () => useAtomValue(cellsAtom);+export const useNotebook = () => useAtomValue(notebookAtom);+/**+ * React-hook for the array of cell IDs.+ */export const useCellIds = () => useAtomValue(cellIdsAtom);+/**+ * React-hook for the array of cell errors.+ */export const useCellErrors = () => useAtomValue(cellErrorsAtom);-export const getCells = () => store.get(cellsAtom).present;+/// IMPERATIVE GETTERS++/**+ * Get the array of cell IDs.+ */+export const getNotebook = () => store.get(notebookAtom);++/**+ * Get the array of cell IDs.+ */+export const getCells = () => store.get(notebookAtom).cellIds;/*** Get the editor views for all cells.*/export const getAllEditorViews = () => {- const cells = store.get(cellsAtom).present;- return cells- .map((cell) => cell.ref.current?.editorView)- .flatMap((x) => (x ? [x] : []));+ const { cellIds, cellHandles } = store.get(notebookAtom);+ return cellIds+ .map((cellId) => cellHandles[cellId].current?.editorView)+ .filter(Boolean);};-export const cellErrors = atom((get) => {- const errors = get(cellsAtom)- .present.map((cell) =>- cell.output?.mimetype === "application/vnd.marimo+error"- ? {- output: cell.output,- cellId: cell.key,- }- : null- )- .filter(Boolean);- return errors;-});+export const getCellEditorView = (cellId: CellId) => {+ const { cellHandles } = store.get(notebookAtom);+ return cellHandles[cellId].current?.editorView;+};-export const notebookOutline = atom((get) => {- const outlines = get(cellsAtom).present.map((cell) => cell.outline);- return mergeOutlines(outlines);-});+/// HELPERS-export const cellErrorCount = atom((get) => get(cellErrors).length);+export function notebookIsRunning(state: NotebookState) {+ return Object.values(state.cellRuntime).some(+ (cell) => cell.status === "running"+ );+}++export function notebookNeedsSave(+ state: NotebookState,+ otherCodes: string[],+ otherConfigs: CellConfig[]+) {+ const { cellIds, cellData } = state;+ const data = cellIds.map((cellId) => cellData[cellId]);+ const codes = data.map((d) => d.code);+ const configs = data.map((d) => d.config);+ return (+ !arrayShallowEquals(codes, otherCodes) ||+ !arrayShallowEquals(configs, otherConfigs)+ );+}++export function notebookNeedsRun(state: NotebookState) {+ return staleCellIds(state).length > 0;+}++export function notebookCells(state: NotebookState) {+ return state.cellIds.map((cellId) => state.cellData[cellId]);+}++export function notebookCellEditorViews({ cellHandles }: NotebookState) {+ const views: Record<CellId, EditorView> = {};+ for (const [cell, ref] of Objects.entries(cellHandles)) {+ if (!ref.current) {+ continue;+ }+ views[cell] = ref.current.editorView;+ }+ return views;+}++export function disabledCellIds(state: NotebookState) {+ const { cellIds, cellData } = state;+ return cellIds+ .map((cellId) => cellData[cellId])+ .filter((cell) => cell.config.disabled);+}++export function enabledCellIds(state: NotebookState) {+ const { cellIds, cellData } = state;+ return cellIds+ .map((cellId) => cellData[cellId])+ .filter((cell) => !cell.config.disabled);+}++export function staleCellIds(state: NotebookState) {+ const { cellIds, cellData, cellRuntime } = state;+ return cellIds.filter(+ (cellId) => cellData[cellId].edited || cellRuntime[cellId].interrupted+ );+}++export function flattenNotebookCells(state: NotebookState) {+ const { cellIds, cellData, cellRuntime } = state;+ return cellIds.map((cellId) => ({+ ...cellData[cellId],+ ...cellRuntime[cellId],+ }));+}/*** Use this hook to dispatch cell actions. This hook will not cause a re-render* when cells change.*/export function useCellActions() {- const setState = useSetAtom(cellsAtom);+ const setState = useSetAtom(notebookAtom);return useMemo(() => {const actions = createActions((action) => {@@ -447,6 +650,9 @@ export function useCellActions() {}, [setState]);}+/**+ * Map of cell actions+ */export type CellActions = ReturnType<typeof createActions>;/**@@ -455,5 +661,5 @@ export type CellActions = ReturnType<typeof createActions>;export const exportedForTesting = {reducer,createActions,- initialCellState,+ initialCellState: initialNotebookState,};diff --git a/frontend/src/core/state/layout.ts b/frontend/src/core/state/layout.tsindex ae7bd80406..61e9a5fd3e 100644--- a/frontend/src/core/state/layout.ts+++ b/frontend/src/core/state/layout.ts@@ -4,7 +4,7 @@ import { LayoutType } from "@/editor/renderers/types";import { cellRendererPlugins } from "@/editor/renderers/plugins";import { Logger } from "@/utils/Logger";import { atom } from "jotai";-import { getCells } from "./cells";+import { getNotebook, notebookCells } from "./cells";import { store } from "./jotai";/**@@ -21,7 +21,7 @@ export const layoutDataAtom = atom<GridLayout | undefined>(undefined);* Get the serialized layout data, to be used when saving.*/export function getSerializedLayout() {- const cells = getCells();+ const notebook = getNotebook();const layoutData = store.get(layoutDataAtom);const layoutViewType = store.get(layoutViewAtom);@@ -41,6 +41,6 @@ export function getSerializedLayout() {}return {type: layoutViewType,- data: plugin.serializeLayout(layoutData, cells),+ data: plugin.serializeLayout(layoutData, notebookCells(notebook)),};}diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex e72ed6b5b0..9fd8c9a338 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -11,8 +11,8 @@ import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";import { OperationMessage } from "@/core/kernel/messages";import { saveCellConfig, sendInstantiate } from "../network/requests";import { CellId } from "../model/ids";-import { CellConfig } from "../model/cells";-import { CellState, createCell } from "../model/cells";+import { CellConfig, CellData } from "../model/cells";+import { createCell } from "../model/cells";import { useErrorBoundary } from "react-error-boundary";import { Logger } from "@/utils/Logger";import { layoutDataAtom, layoutViewAtom } from "../state/layout";@@ -30,7 +30,7 @@ import { prettyError } from "@/utils/errors";export function useMarimoWebSocket(opts: {sessionId: string;autoInstantiate: boolean;- setCells: (cells: CellState[]) => void;+ setCells: (cells: CellData[]) => void;setInitialCodes: (codes: string[]) => void;setInitialConfigs: (cellConfigs: CellConfig[]) => void;}) {@@ -62,7 +62,7 @@ export function useMarimoWebSocket(opts: {// Set the layout, initial codes, cellsconst cells = codes.map((code, i) =>createCell({- key: CellId.create(),+ id: CellId.create(),code,edited: !autoInstantiate,name: names[i],@@ -91,7 +91,7 @@ export function useMarimoWebSocket(opts: {// Register the configssaveCellConfig({configs: Object.fromEntries(- cells.map((cell) => [cell.key, cell.config])+ cells.map((cell) => [cell.id, cell.config])),}).catch((error) => {showBoundary(diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsxindex 14c73551aa..eb88ed735a 100644--- a/frontend/src/editor/Cell.tsx+++ b/frontend/src/editor/Cell.tsx@@ -19,7 +19,7 @@ import { sendRun } from "@/core/network/requests";import { autocompletionKeymap, setupCodeMirror } from "@/core/codemirror/cm";import { UserConfig } from "../core/config/config";-import { CellState } from "../core/model/cells";+import { CellData, CellRuntimeState } from "../core/model/cells";import { CellActions, useCellActions } from "../core/state/cells";import { derefNotNull } from "../utils/dereference";import { OutputArea } from "./Output";@@ -35,7 +35,7 @@ import { Functions } from "../utils/functions";import { Logger } from "../utils/Logger";import { SerializedEditorState } from "../core/codemirror/types";import { CellDragHandle, SortableCell } from "./SortableCell";-import { CellId, HTMLCellId } from "../core/model/ids";+import { HTMLCellId } from "../core/model/ids";import { Theme } from "../theme/useTheme";import { CellActionsDropdown } from "./cell/cell-actions";import { CellActionsContextMenu } from "./cell/cell-context-menu";@@ -62,19 +62,17 @@ export interface CellHandle {export interface CellPropsextends Pick<- CellState,+ CellRuntimeState,| "consoleOutputs"| "status"| "output"- | "code"- | "edited"| "errored"| "interrupted"- | "config"| "stopped"| "runStartTimestamp"| "runElapsedTimeMs">,+ Pick<CellData, "id" | "code" | "edited" | "config">,Pick<CellActions,| "updateCellCode"@@ -87,7 +85,6 @@ export interface CellProps> {theme: Theme;showPlaceholder: boolean;- cellId: CellId;registerRunStart: () => void;serializedEditorState: SerializedEditorState | null;mode: AppMode;@@ -107,7 +104,7 @@ const CellComponent = (theme,showPlaceholder,allowFocus,- cellId,+ id: cellId,code,output,consoleOutputs,diff --git a/frontend/src/editor/actions/useNotebookActions.tsx b/frontend/src/editor/actions/useNotebookActions.tsxindex e2d2eb5c27..96fddf14e7 100644--- a/frontend/src/editor/actions/useNotebookActions.tsx+++ b/frontend/src/editor/actions/useNotebookActions.tsx@@ -10,7 +10,12 @@ import {BookMarkedIcon,} from "lucide-react";import { commandPalletteAtom } from "../CommandPallette";-import { useCellActions, useCells } from "@/core/state/cells";+import {+ disabledCellIds,+ enabledCellIds,+ useCellActions,+ useNotebook,+} from "@/core/state/cells";import { saveCellConfig } from "@/core/network/requests";import { Objects } from "@/utils/objects";import { ActionButton } from "./types";@@ -18,12 +23,12 @@ import { ActionButton } from "./types";export function useNotebookActions(opts: { filename?: string | null }) {const { filename } = opts;- const cells = useCells();+ const notebook = useNotebook();const { updateCellConfig } = useCellActions();const setCommandPalletteOpen = useSetAtom(commandPalletteAtom);- const disabledCells = cells.present.filter((cell) => cell.config.disabled);- const enabledCells = cells.present.filter((cell) => !cell.config.disabled);+ const disabledCells = disabledCellIds(notebook);+ const enabledCells = enabledCellIds(notebook);const actions: ActionButton[] = [{@@ -44,7 +49,7 @@ export function useNotebookActions(opts: { filename?: string | null }) {label: "Enable all cells",hidden: disabledCells.length === 0,handle: async () => {- const ids = disabledCells.map((cell) => cell.key);+ const ids = disabledCells.map((cell) => cell.id);const newConfigs = Objects.fromEntries(ids.map((cellId) => [cellId, { disabled: false }]));@@ -61,7 +66,7 @@ export function useNotebookActions(opts: { filename?: string | null }) {label: "Disable all cells",hidden: enabledCells.length === 0,handle: async () => {- const ids = enabledCells.map((cell) => cell.key);+ const ids = enabledCells.map((cell) => cell.id);const newConfigs = Objects.fromEntries(ids.map((cellId) => [cellId, { disabled: true }]));diff --git a/frontend/src/editor/cell/useRunCells.ts b/frontend/src/editor/cell/useRunCells.tsindex fdd8e3ca73..56a7ae2da0 100644--- a/frontend/src/editor/cell/useRunCells.ts+++ b/frontend/src/editor/cell/useRunCells.ts@@ -1,9 +1,8 @@/* Copyright 2023 Marimo. All rights reserved. */import { RuntimeState } from "@/core/RuntimeState";-import { CellState } from "@/core/model/cells";import { CellId } from "@/core/model/ids";import { sendRunMultiple } from "@/core/network/requests";-import { useCells } from "@/core/state/cells";+import { staleCellIds, useNotebook } from "@/core/state/cells";import { derefNotNull } from "@/utils/dereference";import useEvent from "react-use-event-hook";@@ -11,16 +10,9 @@ import useEvent from "react-use-event-hook";* Creates a function that runs all cells that have been edited or interrupted.*/export function useRunStaleCells() {- const cells = useCells();+ const notebook = useNotebook();const runCells = useRunCells();-- const runStaleCells = useEvent(async () => {- const staleCells = cells.present.filter((cell) => {- return cell.edited || cell.interrupted;- });- await runCells(staleCells);- });-+ const runStaleCells = useEvent(() => runCells(staleCellIds(notebook)));return runStaleCells;}@@ -28,36 +20,28 @@ export function useRunStaleCells() {* Creates a function that runs the cell with the given id.*/export function useRunCell(cellId: CellId) {- const cells = useCells();const runCells = useRunCells();-- const runCell = useEvent(async () => {- const cell = cells.present.find((cell) => cell.key === cellId);- if (cell) {- await runCells([cell]);- }- });-+ const runCell = useEvent(() => runCells([cellId]));return runCell;}/*** Creates a function that runs the given cells.*/-export function useRunCells() {- const runCells = useEvent(async (cells: CellState[]) => {- if (cells.length === 0) {+function useRunCells() {+ const notebook = useNotebook();++ const runCells = useEvent(async (cellIds: CellId[]) => {+ if (cellIds.length === 0) {return;}- const cellIds: CellId[] = [];- const codes: string[] = [];- for (const cell of cells) {- const ref = derefNotNull(cell.ref);+ const { cellHandles } = notebook;- cellIds.push(cell.key);+ const codes: string[] = [];+ for (const cellId of cellIds) {+ const ref = derefNotNull(cellHandles[cellId]);codes.push(ref.editorView.state.doc.toString());-ref.registerRun();}diff --git a/frontend/src/editor/chrome/panels/error-panel.tsx b/frontend/src/editor/chrome/panels/error-panel.tsxindex 0f1141cf99..28564b0b99 100644--- a/frontend/src/editor/chrome/panels/error-panel.tsx+++ b/frontend/src/editor/chrome/panels/error-panel.tsx@@ -1,13 +1,12 @@/* Copyright 2023 Marimo. All rights reserved. */import React from "react";-import { cellErrors } from "../../../core/state/cells";+import { useCellErrors } from "../../../core/state/cells";import { MarimoErrorOutput } from "../../output/MarimoErrorOutput";import { CellLinkError } from "@/editor/links/cell-link";-import { useAtomValue } from "jotai";import { PartyPopperIcon } from "lucide-react";export const ErrorsPanel: React.FC = () => {- const errors = useAtomValue(cellErrors);+ const errors = useCellErrors();if (errors.length === 0) {return (diff --git a/frontend/src/editor/renderers/CellArray.tsx b/frontend/src/editor/renderers/CellArray.tsxindex b0331c8e01..1fa2acac70 100644--- a/frontend/src/editor/renderers/CellArray.tsx+++ b/frontend/src/editor/renderers/CellArray.tsx@@ -4,7 +4,11 @@ import { sendDeleteCell } from "@/core/network/requests";import { Cell } from "editor/Cell";import { RuntimeState } from "../../core/RuntimeState";import { ConnectionStatus, WebSocketState } from "../../core/websocket/types";-import { CellsAndHistory, useCellActions } from "../../core/state/cells";+import {+ NotebookState,+ flattenNotebookCells,+ useCellActions,+} from "../../core/state/cells";import { AppConfig, UserConfig } from "../../core/config/config";import { AppMode } from "../../core/mode";import { useHotkey } from "../../hooks/useHotkey";@@ -16,7 +20,7 @@ import { useDelayVisibility } from "./vertical-layout/useDelayVisiblity";import { useChromeActions } from "../chrome/state";interface CellArrayProps {- cells: CellsAndHistory;+ notebook: NotebookState;mode: AppMode;userConfig: UserConfig;appConfig: AppConfig;@@ -29,7 +33,7 @@ function registerRunStart() {}export const CellArray: React.FC<CellArrayProps> = ({- cells,+ notebook,mode,userConfig,appConfig,@@ -52,7 +56,7 @@ export const CellArray: React.FC<CellArrayProps> = ({const { theme } = useTheme();const { togglePanel } = useChromeActions();- const { invisible } = useDelayVisibility(cells.present, mode);+ const { invisible } = useDelayVisibility(notebook.cellIds.length, mode);// HOTKEYSuseHotkey("global.focusTop", focusTopCell);@@ -71,20 +75,22 @@ export const CellArray: React.FC<CellArrayProps> = ({// Scroll to a cell targeted by a previous actionuseEffect(() => {- if (cells.scrollKey !== null) {+ if (notebook.scrollKey !== null) {scrollToTarget();}- }, [cells.present, cells.scrollKey, scrollToTarget]);+ }, [notebook.cellIds, notebook.scrollKey, scrollToTarget]);++ const cells = flattenNotebookCells(notebook);return (<VerticalLayoutWrapper invisible={invisible} appConfig={appConfig}>- {cells.present.map((cell) => (+ {cells.map((cell) => (<Cell- key={cell.key.toString()}+ key={cell.id.toString()}theme={theme}- showPlaceholder={cells.present.length === 1}+ showPlaceholder={cells.length === 1}allowFocus={!invisible}- cellId={cell.key}+ id={cell.id}code={cell.code}output={cell.output}consoleOutputs={cell.consoleOutputs}@@ -99,7 +105,7 @@ export const CellArray: React.FC<CellArrayProps> = ({runElapsedTimeMs={cell.runElapsedTimeMs}registerRunStart={registerRunStart}serializedEditorState={cell.serializedEditorState}- showDeleteButton={cells.present.length > 1}+ showDeleteButton={cells.length > 1}createNewCell={createNewCell}deleteCell={onDeleteCell}focusCell={focusCell}@@ -107,7 +113,7 @@ export const CellArray: React.FC<CellArrayProps> = ({moveCell={moveCell}mode={mode}appClosed={connStatus.state !== WebSocketState.OPEN}- ref={cell.ref}+ ref={notebook.cellHandles[cell.id]}userConfig={userConfig}config={cell.config}/>diff --git a/frontend/src/editor/renderers/cells-renderer.tsx b/frontend/src/editor/renderers/cells-renderer.tsxindex c526cc1fcb..5388d3c56f 100644--- a/frontend/src/editor/renderers/cells-renderer.tsx+++ b/frontend/src/editor/renderers/cells-renderer.tsx@@ -1,5 +1,5 @@/* Copyright 2023 Marimo. All rights reserved. */-import { useCells } from "@/core/state/cells";+import { flattenNotebookCells, useNotebook } from "@/core/state/cells";import React, { PropsWithChildren, memo } from "react";import { cellRendererPlugins } from "./plugins";import { AppConfig } from "@/core/config/config";@@ -14,7 +14,7 @@ interface Props {export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(({ appConfig, mode, children }) => {- const cells = useCells();+ const notebook = useNotebook();const [layoutData, setLayoutData] = useAtom(layoutDataAtom);const [layoutType] = useAtom(layoutViewAtom);@@ -30,13 +30,15 @@ export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(return children;}+ const cells = flattenNotebookCells(notebook);+const Renderer = plugin.Component;const body = (<RendererappConfig={appConfig}mode={mode}- cells={cells.present}- layout={layoutData || plugin.getInitialLayout(cells.present)}+ cells={cells}+ layout={layoutData || plugin.getInitialLayout(cells)}setLayout={setLayoutData}/>);diff --git a/frontend/src/editor/renderers/grid-layout/grid-layout.tsx b/frontend/src/editor/renderers/grid-layout/grid-layout.tsxindex 4721ef0d13..d1631e87ba 100644--- a/frontend/src/editor/renderers/grid-layout/grid-layout.tsx+++ b/frontend/src/editor/renderers/grid-layout/grid-layout.tsx@@ -8,7 +8,7 @@ import {SerializedGridLayoutCell,} from "./types";import { OutputArea } from "@/editor/Output";-import { CellState } from "@/core/model/cells";+import { CellRuntimeState } from "@/core/model/cells";import "react-grid-layout/css/styles.css";import "./styles.css";@@ -118,10 +118,10 @@ const GridLayoutRenderer: React.FC<Props> = ({draggableHandle={enableInteractions ? undefined : "noop"}>{cells- .filter((cell) => inGridIds.has(cell.key))+ .filter((cell) => inGridIds.has(cell.id)).map((cell) => (<div- key={cell.key}+ key={cell.id}className={cn("relative transparent-when-disconnected z-10",enableInteractions &&@@ -132,7 +132,7 @@ const GridLayoutRenderer: React.FC<Props> = ({<GridCellcode={cell.code}mode={mode}- cellId={cell.key}+ cellId={cell.id}output={cell.output}status={cell.status}hidden={cell.errored || cell.interrupted || cell.stopped}@@ -144,7 +144,7 @@ const GridLayoutRenderer: React.FC<Props> = ({onClick={() => {setLayout({...layout,- cells: layout.cells.filter((c) => c.i !== cell.key),+ cells: layout.cells.filter((c) => c.i !== cell.id),});}}/>@@ -159,7 +159,7 @@ const GridLayoutRenderer: React.FC<Props> = ({return grid;}- const notInGrid = cells.filter((cell) => !inGridIds.has(cell.key));+ const notInGrid = cells.filter((cell) => !inGridIds.has(cell.id));return (<>@@ -237,10 +237,10 @@ const GridLayoutRenderer: React.FC<Props> = ({</div>{notInGrid.map((cell) => (<div- key={cell.key}+ key={cell.id}draggable={true}unselectable="on"- data-cell-id={cell.key}+ data-cell-id={cell.id}// Firefox requires some kind of initialization which we can do by adding this attribute// @see https://bugzilla.mozilla.org/show_bug.cgi?id=568313onDragStart={(e) => {@@ -248,7 +248,7 @@ const GridLayoutRenderer: React.FC<Props> = ({const height = e.currentTarget.offsetHeight;setDroppingItem({- i: cell.key,+ i: cell.id,w: layout.columns / 4,h: Math.ceil(height / layout.rowHeight) || 1,});@@ -259,7 +259,7 @@ const GridLayoutRenderer: React.FC<Props> = ({<GridCellcode={cell.code}mode={mode}- cellId={cell.key}+ cellId={cell.id}output={cell.output}status={cell.status}hidden={false}@@ -272,7 +272,8 @@ const GridLayoutRenderer: React.FC<Props> = ({);};-interface GridCellProps extends Pick<CellState, "output" | "status" | "code"> {+interface GridCellProps extends Pick<CellRuntimeState, "output" | "status"> {+ code: string;cellId: CellId;mode: AppMode;hidden: boolean;@@ -349,7 +350,7 @@ export const GridLayoutPlugin: ICellRendererPlugin<return [];}return {- i: cell.key,+ i: cell.id,x: position[0],y: position[1],w: position[2],@@ -362,7 +363,7 @@ export const GridLayoutPlugin: ICellRendererPlugin<serializeLayout: (layout, cells): SerializedGridLayout => {const layoutsByKey = Maps.keyBy(layout.cells, (cell) => cell.i);const serializedCells: SerializedGridLayoutCell[] = cells.map((cell) => {- const layout = layoutsByKey.get(cell.key);+ const layout = layoutsByKey.get(cell.id);if (!layout) {return {position: null,diff --git a/frontend/src/editor/renderers/plugins.ts b/frontend/src/editor/renderers/plugins.tsindex 194c6cf392..03cfe3ca45 100644--- a/frontend/src/editor/renderers/plugins.ts+++ b/frontend/src/editor/renderers/plugins.ts@@ -1,7 +1,7 @@/* Copyright 2023 Marimo. All rights reserved. */import { GridLayoutPlugin } from "./grid-layout/grid-layout";import { ICellRendererPlugin, LayoutType } from "./types";-import { CellState } from "@/core/model/cells";+import { CellData } from "@/core/model/cells";// If more renderers are added, we may want to consider lazy loading them.// eslint-disable-next-line @typescript-eslint/no-explicit-any@@ -12,7 +12,7 @@ export const cellRendererPlugins: Array<ICellRendererPlugin<any, any>> = [export function deserializeLayout(type: LayoutType,data: unknown,- cells: CellState[]+ cells: CellData[]) {const plugin = cellRendererPlugins.find((plugin) => plugin.type === type);if (plugin === undefined) {diff --git a/frontend/src/editor/renderers/types.ts b/frontend/src/editor/renderers/types.tsindex 72ccd165f7..4cf96d95e0 100644--- a/frontend/src/editor/renderers/types.ts+++ b/frontend/src/editor/renderers/types.ts@@ -1,6 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */import { AppConfig } from "@/core/config/config";-import { CellState } from "@/core/model/cells";+import { CellData, CellRuntimeState } from "@/core/model/cells";import { ZodType, ZodTypeDef } from "zod";import { AppMode } from "@/core/mode";@@ -16,7 +16,7 @@ export interface ICellRendererProps<L> {/*** The cells to render.*/- cells: CellState[];+ cells: Array<CellRuntimeState & CellData>;/*** The layout configuration.@@ -56,10 +56,10 @@ export interface ICellRendererPlugin<S, L> {*/validator: ZodType<S, ZodTypeDef, unknown>;- deserializeLayout: (layout: S, cells: CellState[]) => L;- serializeLayout: (layout: L, cells: CellState[]) => S;+ deserializeLayout: (layout: S, cells: CellData[]) => L;+ serializeLayout: (layout: L, cells: CellData[]) => S;Component: React.FC<ICellRendererProps<L>>;- getInitialLayout: (cells: CellState[]) => L;+ getInitialLayout: (cells: CellData[]) => L;}diff --git a/frontend/src/editor/renderers/vertical-layout/useDelayVisiblity.ts b/frontend/src/editor/renderers/vertical-layout/useDelayVisiblity.tsindex a29c4311a0..5de7eda094 100644--- a/frontend/src/editor/renderers/vertical-layout/useDelayVisiblity.ts+++ b/frontend/src/editor/renderers/vertical-layout/useDelayVisiblity.ts@@ -1,21 +1,21 @@/* Copyright 2023 Marimo. All rights reserved. */import { AppMode } from "@/core/mode";-import { CellState } from "@/core/model/cells";+import { getAllEditorViews } from "@/core/state/cells";import { useState, useEffect } from "react";-export function useDelayVisibility(cells: CellState[], mode: AppMode) {+export function useDelayVisibility(numCells: number, mode: AppMode) {// Start the app as invisible and delay proportional to the number of cells,// to avoid most of the flickering when the app is loaded (b/c it is// streamed). Delaying also helps prevent cell editors from stealing focus.const [invisible, setInvisible] = useState(true);useEffect(() => {- const delay = Math.max(Math.min((cells.length - 1) * 15, 100), 0);+ const delay = Math.max(Math.min((numCells - 1) * 15, 100), 0);const timeout = setTimeout(() => {setInvisible(false);// After 1 frame, focus on the first cell if it's been mountedif (mode !== "read") {requestAnimationFrame(() => {- cells[0]?.ref.current?.editorView.focus();+ focusFirstEditor();});}}, delay);@@ -26,3 +26,10 @@ export function useDelayVisibility(cells: CellState[], mode: AppMode) {return { invisible };}++function focusFirstEditor() {+ const editors = getAllEditorViews();+ if (editors.length > 0) {+ editors[0].focus();+ }+}diff --git a/frontend/src/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/editor/renderers/vertical-layout/vertical-layout.tsxindex a398f7622a..27daa6b949 100644--- a/frontend/src/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/editor/renderers/vertical-layout/vertical-layout.tsx@@ -1,6 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */import { memo, useRef } from "react";-import { CellState } from "@/core/model/cells";+import { CellRuntimeState } from "@/core/model/cells";import { CellId, HTMLCellId } from "@/core/model/ids";import { OutputArea } from "@/editor/Output";import clsx from "clsx";@@ -17,13 +17,13 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({appConfig,mode,}) => {- const { invisible } = useDelayVisibility(cells, mode);+ const { invisible } = useDelayVisibility(cells.length, mode);return (<VerticalLayoutWrapper invisible={invisible} appConfig={appConfig}>{cells.map((cell) => (<VerticalCell- key={cell.key}- cellId={cell.key}+ key={cell.id}+ cellId={cell.id}output={cell.output}status={cell.status}stopped={cell.stopped}@@ -37,8 +37,8 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({interface VerticalCellPropsextends Pick<- CellState,- "output" | "key" | "status" | "stopped" | "errored" | "interrupted"+ CellRuntimeState,+ "output" | "status" | "stopped" | "errored" | "interrupted"> {cellId: CellId;}diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 19f9dd8200..343f2bf692 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -16,7 +16,7 @@ type Story = StoryObj<typeof Cell>;const props: CellProps = {theme: "light",showPlaceholder: false,- cellId: "1" as CellId,+ id: "1" as CellId,code: "import marimo as mo",output: null,consoleOutputs: [],diff --git a/frontend/src/utils/arrays.ts b/frontend/src/utils/arrays.tsindex 5aa436cf04..c04cc82655 100644--- a/frontend/src/utils/arrays.ts+++ b/frontend/src/utils/arrays.ts@@ -4,9 +4,25 @@ export function arrayDelete<T>(array: T[], index: number): T[] {}export function arrayInsert<T>(array: T[], index: number, value: T): T[] {+ if (array.length === 0) {+ return [value];+ }+return [...array.slice(0, index), value, ...array.slice(index)];}+export function arrayShallowEquals<T>(a: T[], b: T[]): boolean {+ if (a.length !== b.length) {+ return false;+ }+ for (let i = 0, l = a.length; i < l; i++) {+ if (a[i] !== b[i]) {+ return false;+ }+ }+ return true;+}+export const Arrays = {// eslint-disable-next-line @typescript-eslint/no-explicit-anyEMPTY: [] as any[],