A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: allow renaming cells (#484)
Myles Scolnickb2ee63f5c132
diff --git a/frontend/src/components/dependency-graph/custom-node.tsx b/frontend/src/components/dependency-graph/custom-node.tsxindex 831ebd4318..b7535f9be2 100644--- a/frontend/src/components/dependency-graph/custom-node.tsx+++ b/frontend/src/components/dependency-graph/custom-node.tsx@@ -5,6 +5,8 @@ import { useAtomValue } from "jotai";import { memo } from "react";import { Handle, Position, useStore } from "reactflow";import { CustomNodeProps, getNodeHeight } from "./elements";+import { displayCellName } from "@/core/cells/names";+import { CellId } from "@/core/cells/ids";function getWidth(canvasWidth: number) {const minWidth = 100;@@ -47,7 +49,7 @@ export const CustomNode = memo((props: CustomNodeProps) => {}}><div className="text-muted-foreground font-semibold text-xs py-1 px-2 bg-muted border-b">- Cell {id}+ {displayCellName(cell.name, id as CellId)}</div><TinyCode code={cell.code} /></div>diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex e3bf0a747d..34c1c86595 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -41,6 +41,7 @@ import { CellEditor } from "./cell/code/cell-editor";import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";import { outputIsStale } from "@/core/cells/cell";import { RuntimeState } from "@/core/kernel/RuntimeState";+import { isOutputEmpty } from "@/core/cells/outputs";/*** Imperative interface of the cell.@@ -68,7 +69,7 @@ export interface CellProps| "runStartTimestamp"| "runElapsedTimeMs">,- Pick<CellData, "id" | "code" | "edited" | "config">,+ Pick<CellData, "id" | "code" | "edited" | "config" | "name">,Pick<CellActions,| "updateCellCode"@@ -123,6 +124,7 @@ const CellComponent = (moveToNextCell,userConfig,config: cellConfig,+ name,}: CellProps,ref: React.ForwardedRef<CellHandle>) => {@@ -279,13 +281,16 @@ const CellComponent = (}};+ const hasOutput = !isOutputEmpty(output);+return (<CellActionsContextMenucellId={cellId}config={cellConfig}status={status}editorView={editorView.current}- hasOutput={!!output}+ hasOutput={hasOutput}+ name={name}><SortableCelltabIndex={-1}@@ -357,8 +362,9 @@ const CellComponent = (cellId={cellId}status={status}editorView={editorView.current}+ name={name}config={cellConfig}- hasOutput={!!output}+ hasOutput={hasOutput}><CellDragHandle /></CellActionsDropdown>@@ -381,6 +387,8 @@ const CellComponent = (<ConsoleOutputconsoleOutputs={consoleOutputs}stale={consoleOutputStale}+ cellName={name}+ cellId={cellId}/></SortableCell></CellActionsContextMenu>diff --git a/frontend/src/components/editor/actions/name-cell-input.tsx b/frontend/src/components/editor/actions/name-cell-input.tsxnew file mode 100644index 0000000000..2eba2b3f14--- /dev/null+++ b/frontend/src/components/editor/actions/name-cell-input.tsx@@ -0,0 +1,131 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { Input } from "@/components/ui/input";+import { Tooltip } from "@/components/ui/tooltip";+import { getCellNames, useCellActions } from "@/core/cells/cells";+import { CellId } from "@/core/cells/ids";+import {+ DEFAULT_CELL_NAME,+ normalizeName,+ getValidName,+} from "@/core/cells/names";+import { useOnMount } from "@/hooks/useLifecycle";+import { cn } from "@/utils/cn";+import { Events } from "@/utils/events";+import React, { useRef, useState } from "react";++interface Props {+ className?: string;+ value: string;+ onChange: (newName: string) => void;+ placeholder?: string;+}++export const NameCellInput: React.FC<Props> = ({+ value,+ onChange,+ placeholder,+}) => {+ const ref = useRef<HTMLInputElement>(null);+ const inputProps = useCellNameInput(value, onChange);++ // Custom onBlur without React's synthetic events+ // See https://github.com/facebook/react/issues/12363+ useOnMount(() => {+ const onBlur = inputProps.onBlur;+ const input = ref.current;+ if (!input) {+ return;+ }++ input.addEventListener("blur", onBlur);+ return () => {+ input.removeEventListener("blur", onBlur);+ };+ });++ return (+ <Input+ value={inputProps.value}+ onChange={inputProps.onChange}+ ref={ref}+ placeholder={placeholder}+ className="shadow-none! hover:shadow-none focus:shadow-none focus-visible:shadow-none"+ onKeyDown={Events.onEnter(Events.stopPropagation())}+ />+ );+};++export const NameCellContentEditable: React.FC<{+ cellId: CellId;+ value: string;+ className: string;+}> = ({ value, cellId, className }) => {+ const { updateCellName } = useCellActions();+ const inputProps = useCellNameInput(value, (newName) =>+ updateCellName({ cellId, name: newName })+ );++ // If the name is the default, don't render the content editable+ if (value === DEFAULT_CELL_NAME) {+ return null;+ }++ return (+ <Tooltip content="Click to rename">+ <span+ className={cn(+ "outline-none border hover:border-cyan-500/40 focus:border-cyan-500/40",+ className+ )}+ contentEditable={true}+ onChange={inputProps.onChange}+ onBlur={inputProps.onBlur}+ onKeyDown={Events.onEnter((e) => {+ if (e.target instanceof HTMLElement) {+ e.target.blur();+ }+ })}+ >+ {value}+ </span>+ </Tooltip>+ );+};++function useCellNameInput(value: string, onChange: (newName: string) => void) {+ const [internalValue, setInternalValue] = useState(value);++ const commit = (newValue: string) => {+ // No change+ if (newValue === value) {+ return;+ }++ // Empty+ if (!newValue || newValue === DEFAULT_CELL_NAME) {+ return onChange(newValue);+ }++ // Get unique name+ const validName = getValidName(newValue, getCellNames());+ return onChange(validName);+ };++ return {+ value: internalValue === DEFAULT_CELL_NAME ? "" : internalValue,+ onChange: (evt: React.ChangeEvent<HTMLInputElement>) => {+ const newValue = evt.target.value;+ const normalized = normalizeName(newValue);+ return setInternalValue(normalized);+ },+ onBlur: (evt: Pick<Event, "target">) => {+ if (evt.target instanceof HTMLInputElement) {+ const newValue = evt.target.value;+ commit(normalizeName(newValue));+ } else if (evt.target instanceof HTMLSpanElement) {+ const newValue = evt.target.innerText.trim();+ commit(normalizeName(newValue));+ }+ },+ };+}diff --git a/frontend/src/components/editor/actions/types.ts b/frontend/src/components/editor/actions/types.tsindex 595cd19d13..6ee1c6f598 100644--- a/frontend/src/components/editor/actions/types.ts+++ b/frontend/src/components/editor/actions/types.ts@@ -9,8 +9,9 @@ export interface ActionButton {label: string;variant?: "danger";hotkey?: HotkeyAction;+ disableClick?: boolean;icon?: React.ReactNode;hidden?: boolean;rightElement?: React.ReactNode;- handle: () => void;+ handle: (event?: Event) => void;}diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsxindex 3fee1d2b41..659ebce7a5 100644--- a/frontend/src/components/editor/actions/useCellActionButton.tsx+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx@@ -15,19 +15,21 @@ import {Trash2Icon,ZapOffIcon,PlayIcon,+ TextCursorInputIcon,} from "lucide-react";import { ActionButton } from "./types";import { MultiIcon } from "@/components/icons/multi-icon";-import { CellConfig, CellStatus } from "@/core/cells/types";+import { CellData, CellStatus } from "@/core/cells/types";import { CellId } from "@/core/cells/ids";import { saveCellConfig } from "@/core/network/requests";import { EditorView } from "@codemirror/view";import { useRunCell } from "../cell/useRunCells";+import { NameCellInput } from "./name-cell-input";-export interface CellActionButtonProps {+export interface CellActionButtonProps+ extends Pick<CellData, "name" | "config"> {cellId: CellId;status: CellStatus;- config: CellConfig;editorView: EditorView | null;hasOutput: boolean;}@@ -36,6 +38,7 @@ export function useCellActionButtons({cellId,config,editorView,+ name,hasOutput,status,}: CellActionButtonProps) {@@ -43,12 +46,14 @@ export function useCellActionButtons({createNewCell: createCell,updateCellConfig,updateCellCode,+ updateCellName,deleteCell,moveCell,sendToTop,sendToBottom,} = useCellActions();const runCell = useRunCell(cellId);+const toggleDisabled = async () => {if (config.disabled) {await saveCellConfig({ configs: { [cellId]: { disabled: false } } });@@ -62,6 +67,22 @@ export function useCellActionButtons({// Actionsconst actions: ActionButton[][] = [[+ {+ icon: <TextCursorInputIcon size={13} strokeWidth={1.5} />,+ label: "Name",+ disableClick: true,+ handle: (evt) => {+ evt?.stopPropagation();+ evt?.preventDefault();+ },+ rightElement: (+ <NameCellInput+ placeholder={`cell_${cellId}`}+ value={name}+ onChange={(newName) => updateCellName({ cellId, name: newName })}+ />+ ),+ },{icon: <PlayIcon size={13} strokeWidth={1.5} />,label: "Run cell",diff --git a/frontend/src/components/editor/cell/cell-actions.tsx b/frontend/src/components/editor/cell/cell-actions.tsxindex 73652fe025..044cacc262 100644--- a/frontend/src/components/editor/cell/cell-actions.tsx+++ b/frontend/src/components/editor/cell/cell-actions.tsx@@ -78,6 +78,7 @@ export const CellActionsDropdown = ({ children, ...props }: Props) => {action.handle();setOpen(false);}}+ disabled={action.disableClick}variant={action.variant}><div className="flex items-center flex-1">diff --git a/frontend/src/components/editor/cell/cell-context-menu.tsx b/frontend/src/components/editor/cell/cell-context-menu.tsxindex 5381cad562..af61fcf277 100644--- a/frontend/src/components/editor/cell/cell-context-menu.tsx+++ b/frontend/src/components/editor/cell/cell-context-menu.tsx@@ -72,8 +72,8 @@ export const CellActionsContextMenu = ({ children, ...props }: Props) => {return (<ContextMenuItemkey={action.label}- onSelect={() => {- action.handle();+ onSelect={(evt) => {+ action.handle(evt);}}variant={action.variant}>@@ -84,6 +84,7 @@ export const CellActionsContextMenu = ({ children, ...props }: Props) => {<div className="flex-1">{action.label}</div><div className="flex-shrink-0 text-sm">{action.hotkey && renderMinimalShortcut(action.hotkey)}+ {action.rightElement}</div></div></ContextMenuItem>diff --git a/frontend/src/components/editor/links/cell-link.tsx b/frontend/src/components/editor/links/cell-link.tsxindex 94fd74955c..e11cce413c 100644--- a/frontend/src/components/editor/links/cell-link.tsx+++ b/frontend/src/components/editor/links/cell-link.tsx@@ -2,6 +2,8 @@import { CellId, HTMLCellId } from "@/core/cells/ids";import { Logger } from "../../../utils/Logger";import { cn } from "@/utils/cn";+import { displayCellName } from "@/core/cells/names";+import { useCellNames } from "@/core/cells/cells";interface Props {cellId: CellId;@@ -12,7 +14,8 @@ interface Props {/* Component that adds a link to a cell, with styling. */export const CellLink = (props: Props): JSX.Element => {const { className, cellId, variant } = props;- const cellName = HTMLCellId.create(cellId);+ const cellName = useCellNames()[cellId] ?? "";+ const cellHtmlId = HTMLCellId.create(cellId);return (<div@@ -24,10 +27,10 @@ export const CellLink = (props: Props): JSX.Element => {e.stopPropagation();e.preventDefault();- const cell: HTMLElement | null = document.getElementById(cellName);+ const cell: HTMLElement | null = document.getElementById(cellHtmlId);if (cell === null) {- Logger.error(`Cell ${cellName} not found on page.`);+ Logger.error(`Cell ${cellHtmlId} not found on page.`);} else {cell.scrollIntoView({ behavior: "smooth", block: "center" });@@ -46,7 +49,7 @@ export const CellLink = (props: Props): JSX.Element => {}}}>- {cellName}+ {displayCellName(cellName, cellId)}</div>);};@@ -55,8 +58,5 @@ export const CellLink = (props: Props): JSX.Element => {export const CellLinkError = (props: Pick<Props, "className" | "cellId">): JSX.Element => {- const { className, cellId } = props;- return (- <CellLink className={className} cellId={cellId} variant={"destructive"} />- );+ return <CellLink {...props} variant={"destructive"} />;};diff --git a/frontend/src/components/editor/notebook-menu-dropdown.tsx b/frontend/src/components/editor/notebook-menu-dropdown.tsxindex 5d721fc68e..dbcbbc5582 100644--- a/frontend/src/components/editor/notebook-menu-dropdown.tsx+++ b/frontend/src/components/editor/notebook-menu-dropdown.tsx@@ -34,7 +34,7 @@ export const NotebookMenuDropdown: React.FC = () => {{actions.map((action) => (<DropdownMenuItemkey={action.label}- onSelect={() => action.handle()}+ onSelect={(evt) => action.handle(evt)}data-testid={`notebook-menu-dropdown-${action.label}`}>{action.icon && <span className="flex-0 mr-2">{action.icon}</span>}diff --git a/frontend/src/components/editor/output/ConsoleOutput.tsx b/frontend/src/components/editor/output/ConsoleOutput.tsxindex 287e4477d4..89c60e86ff 100644--- a/frontend/src/components/editor/output/ConsoleOutput.tsx+++ b/frontend/src/components/editor/output/ConsoleOutput.tsx@@ -3,24 +3,40 @@ import React from "react";import { OutputMessage } from "@/core/kernel/messages";import { formatOutput } from "../Output";import { cn } from "@/utils/cn";+import { DEFAULT_CELL_NAME } from "@/core/cells/names";+import { NameCellContentEditable } from "../actions/name-cell-input";+import { CellId } from "@/core/cells/ids";interface Props {+ cellId: CellId;+ cellName: string;consoleOutputs: OutputMessage[];stale: boolean;}export const ConsoleOutput = (props: Props): React.ReactNode => {- const { consoleOutputs, stale } = props;- if (consoleOutputs.length === 0) {+ const { consoleOutputs, stale, cellName, cellId } = props;+ const hasOutputs = consoleOutputs.length > 0;++ if (!hasOutputs && cellName === DEFAULT_CELL_NAME) {return null;}return (<divtitle={stale ? "This console output is stale" : undefined}- className={cn("console-output-area", stale && "marimo-output-stale")}+ className={cn(+ "console-output-area overflow-hidden rounded-b-lg",+ stale && "marimo-output-stale",+ hasOutputs ? "p-5" : "p-3"+ )}>{consoleOutputs.map((output) => formatOutput({ message: output }))}+ <NameCellContentEditable+ value={cellName}+ cellId={cellId}+ className="bg-[var(--slate-4)] border-[var(--slate-4)] hover:bg-[var(--slate-5)] dark:bg-[var(--sky-5)] dark:border-[var(--sky-5)] dark:bg-[var(--sky-6)] dark:text-[var(--sky-12)] text-[var(--slate-12)] rounded-tl rounded-br-lg absolute right-0 bottom-0 text-xs px-1.5 py-0.5 font-mono"+ /></div>);};diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 8299baf4dc..c05ae008dd 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -112,6 +112,7 @@ export const CellArray: React.FC<CellArrayProps> = ({ref={notebook.cellHandles[cell.id]}userConfig={userConfig}config={cell.config}+ name={cell.name}/>))}</VerticalLayoutWrapper>diff --git a/frontend/src/core/App.tsx b/frontend/src/core/App.tsxindex 8cea781d15..9e08bfc8f6 100644--- a/frontend/src/core/App.tsx+++ b/frontend/src/core/App.tsx@@ -18,6 +18,7 @@ import { UUID } from "../utils/uuid";import { WebSocketState } from "./websocket/types";import { useMarimoWebSocket } from "./websocket/useMarimoWebSocket";import {+ LastSavedNotebook,notebookCells,notebookIsRunning,notebookNeedsRun,@@ -45,7 +46,6 @@ import { useWindowEventListener } from "../hooks/useEventListener";import { toast } from "../components/ui/use-toast";import { SortableCellsProvider } from "../components/sort/SortableCellsProvider";import { CellId, HTMLCellId } from "./cells/ids";-import { CellConfig } from "./cells/types";import { CellArray } from "../components/editor/renderers/CellArray";import { RuntimeState } from "./kernel/RuntimeState";import { CellsRenderer } from "../components/editor/renderers/cells-renderer";@@ -67,8 +67,8 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {const { setCells, updateCellCode } = useCellActions();const [viewState, setViewState] = useAtom(viewStateAtom);const [filename, setFilename] = useFilename();- const [savedCodes, setSavedCodes] = useState<string[]>([""]);- const [savedConfigs, setSavedConfigs] = useState<CellConfig[]>([]);+ const [lastSavedNotebook, setLastSavedNotebook] =+ useState<LastSavedNotebook>();const { openModal, closeModal, openAlert } = useImperativeModal();const isEditing = viewState.mode === "edit";@@ -91,9 +91,13 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {const { connStatus } = useMarimoWebSocket({autoInstantiate:userConfig.runtime.auto_instantiate || viewState.mode === "read",- setCells,- setInitialCodes: setSavedCodes,- setInitialConfigs: setSavedConfigs,+ setCells: (cells) => {+ setCells(cells);+ const names = cells.map((cell) => cell.name);+ const codes = cells.map((cell) => cell.code);+ const configs = cells.map((cell) => cell.config);+ setLastSavedNotebook({ names, codes, configs });+ },sessionId: UUID,});@@ -120,7 +124,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {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);+ const needsSave = notebookNeedsSave(notebook, lastSavedNotebook);// Save the notebook with the given filenameconst saveNotebook = useEvent((filename: string, userInitiated: boolean) => {@@ -155,8 +159,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {formatAll(updateCellCode);}}- setSavedCodes(codes);- setSavedConfigs(configs);+ setLastSavedNotebook({ names: cellNames, codes, configs });}).catch((error) => {openAlert(error.message);@@ -192,6 +195,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {needsSave: needsSave,codes: codes,cellConfigs: configs,+ cellNames: cellNames,connStatus: connStatus,config: userConfig,});diff --git a/frontend/src/core/cells/__tests__/names.test.ts b/frontend/src/core/cells/__tests__/names.test.tsnew file mode 100644index 0000000000..a7eb07338e--- /dev/null+++ b/frontend/src/core/cells/__tests__/names.test.ts@@ -0,0 +1,48 @@+/* Copyright 2023 Marimo. All rights reserved. */++import { CellId } from "../ids";+import {+ normalizeName,+ DEFAULT_CELL_NAME,+ getValidName,+ displayCellName,+} from "../names";+import { expect, describe, it } from "vitest";++describe("normalizeName", () => {+ it("should return the default cell name for empty input", () => {+ expect(normalizeName("")).toBe(DEFAULT_CELL_NAME);+ expect(normalizeName(" ")).toBe(DEFAULT_CELL_NAME);+ expect(normalizeName(" ")).toBe(DEFAULT_CELL_NAME);+ expect(normalizeName(" ")).toBe(DEFAULT_CELL_NAME);+ });++ it("should remove special characters and make lowercase", () => {+ expect(normalizeName("Test Name!")).toBe("test_name_");+ expect(normalizeName("Another Name")).toBe("another_name");+ expect(normalizeName("Some name 10")).toBe("some_name_10");+ expect(normalizeName("10 names")).toBe("_10_names");+ });+});++describe("getValidName", () => {+ it("should return the same name if it is not in the set", () => {+ expect(getValidName("new_name", ["other"])).toBe("new_name");+ });++ it("should return a non-conflicting name", () => {+ expect(getValidName("name", ["name"])).toBe("name_1");+ expect(getValidName("name", ["name_1", "name"])).toBe("name_2");+ });+});++describe("displayCellName", () => {+ const fallbackCellId = "1" as CellId;+ it("should return the name if it is not the default cell name", () => {+ expect(displayCellName("custom_name", fallbackCellId)).toBe("custom_name");+ });++ it("should return the HTML cell ID if the name is the default cell name", () => {+ expect(displayCellName(DEFAULT_CELL_NAME, fallbackCellId)).toBe("cell-1");+ });+});diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex c01f6484c5..54b12ee2a6 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -72,6 +72,12 @@ export interface NotebookState {cellLogs: CellLog[];}+export interface LastSavedNotebook {+ codes: string[];+ configs: CellConfig[];+ names: string[];+}+/*** Initial state of the notebook.*/@@ -337,6 +343,15 @@ const { reducer, createActions } = createReducer(initialNotebookState, {};});},+ updateCellName: (state, action: { cellId: CellId; name: string }) => {+ const { cellId, name } = action;+ return updateCellData(state, cellId, (cell) => {+ return {+ ...cell,+ name: name,+ };+ });+ },updateCellConfig: (state,action: { cellId: CellId; config: Partial<CellConfig> }@@ -539,10 +554,11 @@ const notebookAtom = atom<NotebookState>(initialNotebookState());const cellIdsAtom = atom((get) => get(notebookAtom).cellIds);const cellErrorsAtom = atom((get) => {- const { cellIds, cellRuntime } = get(notebookAtom);+ const { cellIds, cellRuntime, cellData } = get(notebookAtom);const errors = cellIds.map((cellId) => {const cell = cellRuntime[cellId];+ const { name } = cellData[cellId];if (cell.output?.mimetype === "application/vnd.marimo+error") {// Filter out ancestor-stopped errors// These are errors that are caused by a cell that was stopped,@@ -555,6 +571,7 @@ const cellErrorsAtom = atom((get) => {return {output: { ...cell.output, data: nonAncestorErrors },cellId: cellId,+ cellName: name,};}}@@ -573,6 +590,14 @@ export const notebookOutline = atom((get) => {export const cellErrorCount = atom((get) => get(cellErrorsAtom).length);+export const cellIdToNamesMap = atom((get) => {+ const { cellIds, cellData } = get(notebookAtom);+ const names: Record<CellId, string | undefined> = Objects.fromEntries(+ cellIds.map((cellId) => [cellId, cellData[cellId]?.name])+ );+ return names;+});+/// HOOKS/**@@ -585,6 +610,11 @@ export const useNotebook = () => useAtomValue(notebookAtom);*/export const useCellIds = () => useAtomValue(cellIdsAtom);+/**+ * React-hook for the dictionary of cell names+ */+export const useCellNames = () => useAtomValue(cellIdToNamesMap);+/*** React-hook for the array of cell errors.*/@@ -607,6 +637,14 @@ export const getNotebook = () => store.get(notebookAtom);*/export const getCells = () => store.get(notebookAtom).cellIds;+/**+ * Get the array of cell names+ */+export const getCellNames = () => {+ const { cellIds, cellData } = store.get(notebookAtom);+ return cellIds.map((id) => cellData[id]?.name).filter(Boolean);+};+const cellDataAtoms = splitAtom(selectAtom(notebookAtom, (cells) =>cells.cellIds.map((id) => cells.cellData[id])@@ -639,16 +677,20 @@ export function notebookIsRunning(state: NotebookState) {export function notebookNeedsSave(state: NotebookState,- otherCodes: string[],- otherConfigs: CellConfig[]+ lastSavedNotebook: LastSavedNotebook | undefined) {+ if (!lastSavedNotebook) {+ return false;+ }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);+ const names = data.map((d) => d.name);return (- !arrayShallowEquals(codes, otherCodes) ||- !arrayShallowEquals(configs, otherConfigs)+ !arrayShallowEquals(codes, lastSavedNotebook.codes) ||+ !arrayShallowEquals(configs, lastSavedNotebook.configs) ||+ !arrayShallowEquals(names, lastSavedNotebook.names));}diff --git a/frontend/src/core/cells/names.ts b/frontend/src/core/cells/names.tsnew file mode 100644index 0000000000..102471c80c--- /dev/null+++ b/frontend/src/core/cells/names.ts@@ -0,0 +1,50 @@+/* Copyright 2023 Marimo. All rights reserved. */++import { CellId, HTMLCellId } from "./ids";++export const DEFAULT_CELL_NAME = "__";++/**+ * Make's name pythonic - removes spaces, special characters and makes lowercase+ */+export function normalizeName(name: string) {+ name = name.trim();+ if (!name) {+ return DEFAULT_CELL_NAME;+ }+ // Cannot start with a number+ if (/^\d/.test(name)) {+ name = `_${name}`;+ }+ return name.replaceAll(/\W/g, "_").toLowerCase();+}++/**+ * Get a non-conflicting name+ */+export function getValidName(name: string, existingNames: string[]): string {+ const set = new Set(existingNames);+ let result = name;++ if (!set.has(name)) {+ return name;+ }++ let count = 1;+ while (set.has(result)) {+ result = `${name}_${count}`;+ count++;+ }++ return result;+}++/**+ * Print the cell name if differs from DEFAULT_CELL_NAME+ */+export function displayCellName(name: string, fallbackCellId: CellId): string {+ if (name !== DEFAULT_CELL_NAME) {+ return name;+ }+ return HTMLCellId.create(fallbackCellId);+}diff --git a/frontend/src/core/cells/outputs.ts b/frontend/src/core/cells/outputs.tsindex f381fd81f2..d44f2c6354 100644--- a/frontend/src/core/cells/outputs.ts+++ b/frontend/src/core/cells/outputs.ts@@ -2,6 +2,7 @@import { useState } from "react";import { CellId } from "./ids";+import { OutputMessage } from "../kernel/messages";// This does not need to be overcomplicated. We can just store the expanded// state in a global map instead of Jotai since state is not shared between cells.@@ -17,3 +18,17 @@ export function useExpandedOutput(cellId: CellId) {},] as const;}++export function isOutputEmpty(+ output: OutputMessage | undefined | null+): boolean {+ if (output == null) {+ return true;+ }++ if (output.data == null || output.data === "") {+ return true;+ }++ return false;+}diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.tsindex d0604ff1a8..1c47cb7677 100644--- a/frontend/src/core/cells/types.ts+++ b/frontend/src/core/cells/types.ts@@ -3,8 +3,7 @@ import { OutputMessage } from "../kernel/messages";import { SerializedEditorState } from "../codemirror/types";import { Outline } from "./outline";import { CellId } from "./ids";--const DEFAULT_CELL_NAME = "__";+import { DEFAULT_CELL_NAME } from "./names";/*** The status of a cell.diff --git a/frontend/src/core/saving/useAutoSave.ts b/frontend/src/core/saving/useAutoSave.tsindex cddd992794..18d0bb8e5f 100644--- a/frontend/src/core/saving/useAutoSave.ts+++ b/frontend/src/core/saving/useAutoSave.ts@@ -7,12 +7,21 @@ import { CellConfig } from "../cells/types";export function useAutoSave(opts: {codes: string[];cellConfigs: CellConfig[];+ cellNames: string[];config: UserConfig;connStatus: ConnectionStatus;needsSave: boolean;onSave: () => void;}) {- const { codes, cellConfigs, config, connStatus, needsSave, onSave } = opts;+ const {+ codes,+ cellConfigs,+ config,+ connStatus,+ cellNames,+ needsSave,+ onSave,+ } = opts;const autosaveTimeoutId = useRef<NodeJS.Timeout | null>(null);useEffect(() => {@@ -34,7 +43,15 @@ export function useAutoSave(opts: {clearTimeout(autosaveTimeoutId.current);}};- // codes, cellConfigs needed in deps array to prevent race condition+ // codes, cellConfigs, cellNames needed in deps array to prevent race condition// with needsSave when user changes state rapidly- }, [codes, cellConfigs, config.save, connStatus.state, onSave, needsSave]);+ }, [+ codes,+ cellConfigs,+ cellNames,+ config.save,+ connStatus.state,+ onSave,+ needsSave,+ ]);}diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 5ae223c0b6..2d13a39077 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -11,7 +11,7 @@ import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";import { OperationMessage } from "@/core/kernel/messages";import { sendInstantiate } from "../network/requests";import { CellId } from "../cells/ids";-import { CellConfig, CellData } from "../cells/types";+import { CellData } from "../cells/types";import { createCell } from "../cells/types";import { useErrorBoundary } from "react-error-boundary";import { Logger } from "@/utils/Logger";@@ -34,18 +34,10 @@ export function useMarimoWebSocket(opts: {sessionId: string;autoInstantiate: boolean;setCells: (cells: CellData[]) => void;- setInitialCodes: (codes: string[]) => void;- setInitialConfigs: (cellConfigs: CellConfig[]) => void;}) {// Track whether we want to try reconnecting.const shouldTryReconnecting = useRef<boolean>(true);- const {- autoInstantiate,- sessionId,- setCells,- setInitialCodes,- setInitialConfigs,- } = opts;+ const { autoInstantiate, sessionId, setCells } = opts;const { showBoundary } = useErrorBoundary();const { handleCellMessage } = useCellActions();@@ -79,8 +71,6 @@ export function useMarimoWebSocket(opts: {setLayoutData(deserializeLayout(layout.type, layout.data, cells));}setCells(cells);- setInitialCodes(codes);- setInitialConfigs(configs);// Auto-instantiate, in future this can be configurable// or include initial valuesdiff --git a/frontend/src/css/Cell.css b/frontend/src/css/Cell.cssindex 6b562634f5..dc90f55445 100644--- a/frontend/src/css/Cell.css+++ b/frontend/src/css/Cell.css@@ -382,8 +382,6 @@}.console-output-area {- padding: 20px;- border-radius: 0 0 8px 8px;border-top: 1px solid var(--gray-5);border-bottom: 1px solid var(--gray-3);border-right: 1px solid var(--gray-3);diff --git a/frontend/src/hooks/useLifecycle.ts b/frontend/src/hooks/useLifecycle.tsnew file mode 100644index 0000000000..f95ce581d8--- /dev/null+++ b/frontend/src/hooks/useLifecycle.ts@@ -0,0 +1,10 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { EffectCallback, useEffect } from "react";++/**+ * Wrapper around useEffect that makes it clearer that the effect is run, just on mount.+ */+export function useOnMount(effect: EffectCallback) {+ // eslint-disable-next-line react-hooks/exhaustive-deps+ useEffect(effect, []);+}diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex 2274ddd603..076d444d56 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -32,6 +32,7 @@ const props: CellProps = {runElapsedTimeMs: 10,serializedEditorState: null,mode: "edit",+ name: "cell_1",appClosed: false,showDeleteButton: true,allowFocus: false,