Skip to content

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

improvement: refactors for perf (#3079)

Myles Scolnickbe4ab4c13a5d
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsx
index a78cdc2ab4..20b3dfd061 100644
--- a/frontend/src/components/editor/Cell.tsx
+++ b/frontend/src/components/editor/Cell.tsx
@@ -16,7 +16,8 @@ import { saveCellConfig, sendRun, sendStdin } from "@/core/network/requests";
import { autocompletionKeymap } from "@/core/codemirror/cm";
import type { UserConfig } from "../../core/config/config-schema";
import type { CellData, CellRuntimeState } from "../../core/cells/types";
-import { type CellActions, isUninstantiated } from "../../core/cells/cells";
+import type { CellActions } from "../../core/cells/cells";
+import { isUninstantiated } from "../../core/cells/utils";
import { derefNotNull } from "../../utils/dereference";
import { OutputArea } from "./Output";
import { ConsoleOutput } from "./output/ConsoleOutput";
@@ -191,14 +192,14 @@ const CellComponent = (
const disabledOrAncestorDisabled =
cellConfig.disabled || status === "disabled-transitively";
- const uninstantiated = isUninstantiated(
- userConfig.runtime.auto_instantiate,
- runElapsedTimeMs,
+ const uninstantiated = isUninstantiated({
+ autoInstantiate: userConfig.runtime.auto_instantiate,
+ executionTime: runElapsedTimeMs,
status,
errored,
interrupted,
stopped,
- );
+ });
const needsRun =
uninstantiated ||
diff --git a/frontend/src/components/editor/RecoveryButton.tsx b/frontend/src/components/editor/RecoveryButton.tsx
index a8f5dc0b8e..e0404877c0 100644
--- a/frontend/src/components/editor/RecoveryButton.tsx
+++ b/frontend/src/components/editor/RecoveryButton.tsx
@@ -13,19 +13,41 @@ import {
DialogTitle,
} from "../ui/dialog";
import { downloadBlob } from "@/utils/download";
+import { useEvent } from "@/hooks/useEvent";
+import { getNotebook } from "@/core/cells/cells";
+import { notebookCells } from "@/core/cells/utils";
+import { useFilename } from "@/core/saving/filename";
const RecoveryModal = (props: {
proposedName: string;
- getCellsAsJSON: () => string;
closeModal: () => void;
}): JSX.Element => {
+ const filename = useFilename();
+
const downloadRecoveryFile = () => {
downloadBlob(
- new Blob([props.getCellsAsJSON()], { type: "text/plain" }),
+ new Blob([getCellsAsJSON()], { type: "text/plain" }),
`${props.proposedName}.json`,
);
};
+ const getCellsAsJSON = useEvent(() => {
+ const notebook = getNotebook();
+ const cells = notebookCells(notebook);
+ return JSON.stringify(
+ {
+ filename: filename,
+ cells: cells.map((cell) => {
+ return { name: cell.name, code: cell.code };
+ }),
+ },
+ // no replacer
+ null,
+ // whitespace for indentation
+ 2,
+ );
+ });
+
// NB: we use markdown class to have sane styling for list, paragraph
return (
<DialogContent className="w-fit">
@@ -41,33 +63,35 @@ const RecoveryModal = (props: {
}
}}
>
- <DialogTitle className="text-accent mb-6">
+ <DialogTitle className="text-accent-foreground mb-6">
Download unsaved changes?
</DialogTitle>
<DialogDescription
className="markdown break-words"
style={{ wordBreak: "break-word" }}
>
- <p>This app has unsaved changes. To recover:</p>
+ <div className="prose dark:prose-invert">
+ <p>This app has unsaved changes. To recover:</p>
- <ol>
- <li style={{ paddingBottom: "10px" }}>
- Click the "Download" button. This will download a file
- called&nbsp;
- <code>{props.proposedName}.json</code>. This file contains your
- code.
- </li>
+ <ol>
+ <li style={{ paddingBottom: "10px" }}>
+ Click the "Download" button. This will download a file
+ called&nbsp;
+ <code>{props.proposedName}.json</code>. This file contains your
+ code.
+ </li>
- <li style={{ paddingBottom: "10px" }}>
- In your terminal, type
- <code style={{ display: "block", padding: "10px" }}>
- marimo recover {props.proposedName}.json {">"}{" "}
- {props.proposedName}.py
- </code>
- to overwrite <code>{props.proposedName}.py</code> with the
- recovered changes.
- </li>
- </ol>
+ <li style={{ paddingBottom: "10px" }}>
+ In your terminal, type
+ <code style={{ display: "block", padding: "10px" }}>
+ marimo recover {props.proposedName}.json {">"}{" "}
+ {props.proposedName}.py
+ </code>
+ to overwrite <code>{props.proposedName}.py</code> with the
+ recovered changes.
+ </li>
+ </ol>
+ </div>
</DialogDescription>
<DialogFooter>
<Button
@@ -95,9 +119,8 @@ const RecoveryModal = (props: {
export const RecoveryButton = (props: {
filename: string | null;
needsSave: boolean;
- getCellsAsJSON: () => string;
}): JSX.Element => {
- const { filename, needsSave, getCellsAsJSON } = props;
+ const { filename, needsSave } = props;
const { openModal, closeModal } = useImperativeModal();
const proposedName = filename === null ? "app" : filename.slice(0, -3);
@@ -105,11 +128,7 @@ export const RecoveryButton = (props: {
const openRecoveryModal = () => {
if (needsSave) {
openModal(
- <RecoveryModal
- getCellsAsJSON={getCellsAsJSON}
- proposedName={proposedName}
- closeModal={closeModal}
- />,
+ <RecoveryModal proposedName={proposedName} closeModal={closeModal} />,
);
}
};
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index af1786fc21..aeaf79572d 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -31,12 +31,14 @@ import {
FilePlus2Icon,
} from "lucide-react";
import { commandPaletteAtom } from "../controls/command-palette";
-import { useCellActions, useNotebook } from "@/core/cells/cells";
import {
- canUndoDeletes,
- disabledCellIds,
- enabledCellIds,
-} from "@/core/cells/utils";
+ canUndoDeletesAtom,
+ getNotebook,
+ hasDisabledCellsAtom,
+ hasEnabledCellsAtom,
+ useCellActions,
+} from "@/core/cells/cells";
+import { disabledCellIds, enabledCellIds } from "@/core/cells/utils";
import {
exportAsMarkdown,
readCode,
@@ -74,14 +76,13 @@ const NOOP_HANDLER = (event?: Event) => {
};
export function useNotebookActions() {
- const [filename] = useFilename();
+ const filename = useFilename();
const { openModal, closeModal } = useImperativeModal();
const { openApplication } = useChromeActions();
const { selectedPanel } = useChromeState();
const [viewState] = useAtom(viewStateAtom);
const kioskMode = useAtomValue(kioskModeAtom);
- const notebook = useNotebook();
const { updateCellConfig, undoDeleteCell, clearAllCellOutputs } =
useCellActions();
const restartKernel = useRestartKernel();
@@ -90,8 +91,9 @@ export function useNotebookActions() {
const setSettingsDialogOpen = useSetAtom(settingDialogAtom);
const setKeyboardShortcutsOpen = useSetAtom(keyboardShortcutsAtom);
- const disabledCells = disabledCellIds(notebook);
- const enabledCells = enabledCellIds(notebook);
+ const hasDisabledCells = useAtomValue(hasDisabledCellsAtom);
+ const hasEnabledCells = useAtomValue(hasEnabledCellsAtom);
+ const canUndoDeletes = useAtomValue(canUndoDeletesAtom);
const { selectedLayout } = useLayoutState();
const { setLayoutView } = useLayoutActions();
const togglePresenting = useTogglePresenting();
@@ -315,9 +317,10 @@ export function useNotebookActions() {
{
icon: <ZapIcon size={14} strokeWidth={1.5} />,
label: "Enable all cells",
- hidden: disabledCells.length === 0 || kioskMode,
+ hidden: !hasDisabledCells || kioskMode,
handle: async () => {
- const ids = disabledCells.map((cell) => cell.id);
+ const notebook = getNotebook();
+ const ids = disabledCellIds(notebook);
const newConfigs = Objects.fromEntries(
ids.map((cellId) => [cellId, { disabled: false }]),
);
@@ -332,9 +335,10 @@ export function useNotebookActions() {
{
icon: <ZapOffIcon size={14} strokeWidth={1.5} />,
label: "Disable all cells",
- hidden: enabledCells.length === 0 || kioskMode,
+ hidden: !hasEnabledCells || kioskMode,
handle: async () => {
- const ids = enabledCells.map((cell) => cell.id);
+ const notebook = getNotebook();
+ const ids = enabledCellIds(notebook);
const newConfigs = Objects.fromEntries(
ids.map((cellId) => [cellId, { disabled: true }]),
);
@@ -356,7 +360,7 @@ export function useNotebookActions() {
{
icon: <Undo2Icon size={14} strokeWidth={1.5} />,
label: "Undo cell deletion",
- hidden: !canUndoDeletes(notebook) || kioskMode,
+ hidden: !canUndoDeletes || kioskMode,
handle: () => {
undoDeleteCell();
},
diff --git a/frontend/src/components/editor/cell/useRunCells.ts b/frontend/src/components/editor/cell/useRunCells.ts
index 2b4e5eca4a..545bc0eca9 100644
--- a/frontend/src/components/editor/cell/useRunCells.ts
+++ b/frontend/src/components/editor/cell/useRunCells.ts
@@ -1,18 +1,23 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type { CellId } from "@/core/cells/ids";
import { sendRun } from "@/core/network/requests";
-import { staleCellIds, useCellActions, useNotebook } from "@/core/cells/cells";
+import { getNotebook, useCellActions } from "@/core/cells/cells";
import useEvent from "react-use-event-hook";
import { getEditorCodeAsPython } from "@/core/codemirror/language/utils";
import { Logger } from "@/utils/Logger";
+import { staleCellIds } from "@/core/cells/utils";
+import { useAtomValue } from "jotai";
+import { autoInstantiateAtom } from "@/core/config/config";
/**
* Creates a function that runs all cells that have been edited or interrupted.
*/
export function useRunStaleCells() {
- const notebook = useNotebook();
+ const autoInstantiate = useAtomValue(autoInstantiateAtom);
const runCells = useRunCells();
- const runStaleCells = useEvent(() => runCells(staleCellIds(notebook)));
+ const runStaleCells = useEvent(() =>
+ runCells(staleCellIds(getNotebook(), autoInstantiate)),
+ );
return runStaleCells;
}
@@ -34,7 +39,6 @@ export function useRunCell(cellId: CellId | undefined) {
* Creates a function that runs the given cells.
*/
function useRunCells() {
- const notebook = useNotebook();
const { prepareForRun } = useCellActions();
const runCells = useEvent(async (cellIds: CellId[]) => {
@@ -42,7 +46,7 @@ function useRunCells() {
return;
}
- const { cellHandles, cellData } = notebook;
+ const { cellHandles, cellData } = getNotebook();
const codes: string[] = [];
for (const cellId of cellIds) {
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index b5b34bfa79..b931b14867 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -29,6 +29,7 @@ import { ScratchpadPanel } from "../panels/scratchpad-panel";
import { IfCapability } from "@/core/config/if-capability";
import { PackagesPanel } from "../panels/packages-panel";
import { ChatPanel } from "@/components/chat/chat-panel";
+import { TooltipProvider } from "@radix-ui/react-tooltip";
const LazyTerminal = React.lazy(() => import("@/components/terminal/terminal"));
@@ -139,18 +140,20 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
<XIcon className="w-4 h-4" />
</Button>
</div>
- {selectedPanel === "files" && <FileExplorerPanel />}
- {selectedPanel === "errors" && <ErrorsPanel />}
- {selectedPanel === "variables" && <VariablePanel />}
- {selectedPanel === "dependencies" && <DependencyGraphPanel />}
- {selectedPanel === "packages" && <PackagesPanel />}
- {selectedPanel === "outline" && <OutlinePanel />}
- {selectedPanel === "datasources" && <DataSourcesPanel />}
- {selectedPanel === "documentation" && <DocumentationPanel />}
- {selectedPanel === "snippets" && <SnippetsPanel />}
- {selectedPanel === "scratchpad" && <ScratchpadPanel />}
- {selectedPanel === "chat" && <ChatPanel />}
- {selectedPanel === "logs" && <LogsPanel />}
+ <TooltipProvider>
+ {selectedPanel === "files" && <FileExplorerPanel />}
+ {selectedPanel === "errors" && <ErrorsPanel />}
+ {selectedPanel === "variables" && <VariablePanel />}
+ {selectedPanel === "dependencies" && <DependencyGraphPanel />}
+ {selectedPanel === "packages" && <PackagesPanel />}
+ {selectedPanel === "outline" && <OutlinePanel />}
+ {selectedPanel === "datasources" && <DataSourcesPanel />}
+ {selectedPanel === "documentation" && <DocumentationPanel />}
+ {selectedPanel === "snippets" && <SnippetsPanel />}
+ {selectedPanel === "scratchpad" && <ScratchpadPanel />}
+ {selectedPanel === "chat" && <ChatPanel />}
+ {selectedPanel === "logs" && <LogsPanel />}
+ </TooltipProvider>
</div>
</Suspense>
</ErrorBoundary>
@@ -227,7 +230,9 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
direction={"horizontal"}
storage={createStorage("left")}
>
- <Sidebar />
+ <TooltipProvider>
+ <Sidebar />
+ </TooltipProvider>
{helperPanel}
<Panel>
<PanelGroup autoSaveId="marimo:chrome:v1:l1" direction="vertical">
@@ -237,7 +242,9 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
</Panel>
</PanelGroup>
<ErrorBoundary>
- <Footer />
+ <TooltipProvider>
+ <Footer />
+ </TooltipProvider>
</ErrorBoundary>
</div>
);
diff --git a/frontend/src/components/editor/controls/Controls.tsx b/frontend/src/components/editor/controls/Controls.tsx
index b9bbcf3ea9..e9ef674273 100644
--- a/frontend/src/components/editor/controls/Controls.tsx
+++ b/frontend/src/components/editor/controls/Controls.tsx
@@ -1,7 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import {
LayoutTemplateIcon,
- SaveIcon,
EditIcon,
PlayIcon,
SquareIcon,
@@ -11,11 +10,14 @@ import {
import { Button } from "@/components/editor/inputs/Inputs";
import { KeyboardShortcuts } from "@/components/editor/controls/keyboard-shortcuts";
import { ShutdownButton } from "@/components/editor/controls/shutdown-button";
-import { RecoveryButton } from "@/components/editor/RecoveryButton";
import { Tooltip } from "../../ui/tooltip";
import { renderShortcut } from "../../shortcuts/renderShortcut";
-import { useCellActions } from "../../../core/cells/cells";
+import {
+ canUndoDeletesAtom,
+ needsRunAtom,
+ useCellActions,
+} from "../../../core/cells/cells";
import { ConfigButton } from "../../app-config/app-config-button";
import { LayoutSelect } from "../renderers/layout-select";
import { NotebookMenuDropdown } from "@/components/editor/controls/notebook-menu-dropdown";
@@ -26,46 +28,33 @@ import { CommandPaletteButton } from "./command-palette-button";
import { cn } from "@/utils/cn";
import { HideInKioskMode } from "../kiosk-mode";
import { Functions } from "@/utils/functions";
+import { SaveComponent } from "@/core/saving/save-component";
+import { useAtomValue } from "jotai";
interface ControlsProps {
- filename: string | null;
- needsSave: boolean;
- onSaveNotebook: () => void;
- getCellsAsJSON: () => string;
presenting: boolean;
onTogglePresenting: () => void;
onInterrupt: () => void;
onRun: () => void;
closed: boolean;
running: boolean;
- needsRun: boolean;
- undoAvailable: boolean;
- appWidth: AppConfig["width"];
+ appConfig: AppConfig;
}
export const Controls = ({
- filename,
- needsSave,
- onSaveNotebook,
- getCellsAsJSON,
presenting,
onTogglePresenting,
onInterrupt,
onRun,
closed,
running,
- needsRun,
- undoAvailable,
- appWidth,
+ appConfig,
}: ControlsProps): JSX.Element => {
+ const appWidth = appConfig.width;
+ const undoAvailable = useAtomValue(canUndoDeletesAtom);
+ const needsRun = useAtomValue(needsRunAtom);
const { undoDeleteCell } = useCellActions();
- const handleSaveClick = (e: React.MouseEvent<HTMLButtonElement>) => {
- e.preventDefault();
- e.stopPropagation();
- onSaveNotebook();
- };
-
let undoControl: JSX.Element | null = null;
if (!closed && undoAvailable) {
undoControl = (
@@ -103,25 +92,7 @@ export const Controls = ({
)}
>
<HideInKioskMode>
- {closed ? (
- <RecoveryButton
- filename={filename}
- getCellsAsJSON={getCellsAsJSON}
- needsSave={needsSave}
- />
- ) : (
- <Tooltip content={renderShortcut("global.save")}>
- <Button
- data-testid="save-button"
- id="save-button"
- shape="rectangle"
- color={needsSave ? "yellow" : "hint-green"}
- onClick={handleSaveClick}
- >
- <SaveIcon strokeWidth={1.5} size={18} />
- </Button>
- </Tooltip>
- )}
+ <SaveComponent kioskMode={false} appConfig={appConfig} />
</HideInKioskMode>
<Tooltip content={renderShortcut("global.hideCode")}>
diff --git a/frontend/src/components/editor/header/filename-form.tsx b/frontend/src/components/editor/header/filename-form.tsx
index 9134f87e5f..486a3adcc2 100644
--- a/frontend/src/components/editor/header/filename-form.tsx
+++ b/frontend/src/components/editor/header/filename-form.tsx
@@ -1,14 +1,14 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { FilenameInput } from "@/components/editor/header/filename-input";
+import { useUpdateFilename } from "@/core/saving/filename";
import { Paths } from "@/utils/paths";
export const FilenameForm = ({
filename,
- setFilename,
}: {
filename: string | null;
- setFilename: (filename: string) => void;
}): JSX.Element => {
+ const setFilename = useUpdateFilename();
return (
<FilenameInput
placeholderText={
diff --git a/frontend/src/components/editor/links/cell-link.tsx b/frontend/src/components/editor/links/cell-link.tsx
index e05c4d4042..60b914d9c2 100644
--- a/frontend/src/components/editor/links/cell-link.tsx
+++ b/frontend/src/components/editor/links/cell-link.tsx
@@ -69,7 +69,7 @@ export const CellLinkTraceback = ({
cellId,
lineNumber,
}: { cellId: CellId; lineNumber: number }): JSX.Element => {
- const [filename] = useFilename();
+ const filename = useFilename();
return (
<CellLink
cellId={cellId}
diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsx
index 398b5fe9ba..38b002c3aa 100644
--- a/frontend/src/components/editor/renderers/CellArray.tsx
+++ b/frontend/src/components/editor/renderers/CellArray.tsx
@@ -5,12 +5,18 @@ import {
type ConnectionStatus,
WebSocketState,
} from "../../../core/websocket/types";
-import { type NotebookState, useCellActions } from "../../../core/cells/cells";
+import {
+ useNotebook,
+ type CellActions,
+ columnIdsAtom,
+ type NotebookState,
+ useCellActions,
+} from "../../../core/cells/cells";
import type { AppConfig, UserConfig } from "../../../core/config/config-schema";
import type { AppMode } from "../../../core/mode";
import { useHotkey } from "../../../hooks/useHotkey";
import { formatAll } from "../../../core/codemirror/format";
-import { useTheme } from "../../../theme/useTheme";
+import { type Theme, useTheme } from "../../../theme/useTheme";
import { VerticalLayoutWrapper } from "./vertical-layout/vertical-layout-wrapper";
import { useDelayVisibility } from "./vertical-layout/useDelayVisibility";
import { useChromeActions } from "../chrome/state";
@@ -45,27 +51,41 @@ import {
} from "@dnd-kit/sortable";
import { SortableCellsProvider } from "@/components/sort/SortableCellsProvider";
import { Column } from "../columns/cell-column";
-import type { CellColumnId } from "@/utils/id-tree";
+import type { CellColumnId, CollapsibleTree } from "@/utils/id-tree";
+import type { CellId } from "@/core/cells/ids";
interface CellArrayProps {
- notebook: NotebookState;
mode: AppMode;
userConfig: UserConfig;
appConfig: AppConfig;
connStatus: ConnectionStatus;
}
-export const CellArray: React.FC<CellArrayProps> = ({
- notebook,
+export const CellArray: React.FC<CellArrayProps> = (props) => {
+ const columnIds = useAtomValue(columnIdsAtom);
+ return (
+ <SortableCellsProvider multiColumn={props.appConfig.width === "columns"}>
+ <SortableContext
+ id="column-container"
+ items={columnIds}
+ strategy={horizontalListSortingStrategy}
+ >
+ <CellArrayInternal {...props} />
+ </SortableContext>
+ </SortableCellsProvider>
+ );
+};
+
+const CellArrayInternal: React.FC<CellArrayProps> = ({
mode,
userConfig,
appConfig,
connStatus,
}) => {
+ const notebook = useNotebook();
const actions = useCellActions();
const { theme } = useTheme();
const { toggleSidebarPanel } = useChromeActions();
-
const { invisible } = useDelayVisibility(notebook.cellIds.idLength, mode);
// HOTKEYS
@@ -105,99 +125,135 @@ export const CellArray: React.FC<CellArrayProps> = ({
>
<PackageAlert />
<NotebookBanner width={appConfig.width} />
- <SortableCellsProvider multiColumn={appConfig.width === "columns"}>
- <SortableContext
- id="column-container"
- items={columns.map((column) => column.id)}
- strategy={horizontalListSortingStrategy}
- >
- <div
- className={cn(
- appConfig.width === "columns" &&
- "grid grid-flow-col auto-cols-min gap-6",
- )}
- >
- {columns.map((column, index) => {
- return (
- <Column
- key={column.id}
- columnId={column.id}
- canMoveLeft={index > 0}
- canMoveRight={index < columns.length - 1}
- width={appConfig.width}
- canDelete={columns.length > 1}
- footer={
- <AddCellButtons
- columnId={column.id}
- className={cn(
- appConfig.width === "columns" &&
- "opacity-0 group-hover/column:opacity-100",
- )}
- />
- }
- >
- <SortableContext
- id={`column-${index + 1}`}
- items={column.topLevelIds}
- strategy={verticalListSortingStrategy}
- >
- {column.topLevelIds.map((cellId) => {
- const cellData = notebook.cellData[cellId];
- const cellRuntime = notebook.cellRuntime[cellId];
- return (
- <Cell
- key={cellData.id.toString()}
- theme={theme}
- showPlaceholder={hasOnlyOneCell}
- allowFocus={!invisible && !notebook.scrollKey}
- id={cellData.id}
- code={cellData.code}
- outline={cellRuntime.outline}
- output={cellRuntime.output}
- consoleOutputs={cellRuntime.consoleOutputs}
- status={cellRuntime.status}
- edited={cellData.edited}
- interrupted={cellRuntime.interrupted}
- errored={cellRuntime.errored}
- stopped={cellRuntime.stopped}
- staleInputs={cellRuntime.staleInputs}
- runStartTimestamp={cellRuntime.runStartTimestamp}
- lastRunStartTimestamp={
- cellRuntime.lastRunStartTimestamp
- }
- runElapsedTimeMs={
- cellRuntime.runElapsedTimeMs ??
- (cellData.lastExecutionTime as Milliseconds)
- }
- serializedEditorState={cellData.serializedEditorState}
- canDelete={!hasOnlyOneCell}
- mode={mode}
- appClosed={connStatus.state !== WebSocketState.OPEN}
- ref={notebook.cellHandles[cellId]}
- userConfig={userConfig}
- debuggerActive={cellRuntime.debuggerActive}
- config={cellData.config}
- name={cellData.name}
- isCollapsed={column.isCollapsed(cellId)}
- collapseCount={column.getCount(cellId)}
- canMoveX={appConfig.width === "columns"}
- {...actions}
- deleteCell={onDeleteCell}
- />
- );
- })}
- </SortableContext>
- </Column>
- );
- })}
- </div>
- </SortableContext>
- </SortableCellsProvider>
+ <div
+ className={cn(
+ appConfig.width === "columns" &&
+ "grid grid-flow-col auto-cols-min gap-6",
+ )}
+ >
+ {columns.map((column, index) => (
+ <SortableColumn
+ key={column.id}
+ column={column}
+ index={index}
+ columnsLength={columns.length}
+ appConfig={appConfig}
+ notebook={notebook}
+ mode={mode}
+ userConfig={userConfig}
+ connStatus={connStatus}
+ actions={actions}
+ theme={theme}
+ hasOnlyOneCell={hasOnlyOneCell}
+ invisible={invisible}
+ onDeleteCell={onDeleteCell}
+ />
+ ))}
+ </div>
<FloatingOutline />
</VerticalLayoutWrapper>
);
};
+const SortableColumn: React.FC<{
+ column: CollapsibleTree<CellId>;
+ index: number;
+ columnsLength: number;
+ appConfig: AppConfig;
+ notebook: NotebookState;
+ mode: AppMode;
+ userConfig: UserConfig;
+ connStatus: ConnectionStatus;
+ actions: CellActions;
+ theme: Theme;
+ hasOnlyOneCell: boolean;
+ invisible: boolean;
+ onDeleteCell: (payload: { cellId: CellId }) => void;
+}> = ({
+ column,
+ index,
+ columnsLength,
+ appConfig,
+ notebook,
+ mode,
+ userConfig,
+ connStatus,
+ actions,
+ theme,
+ hasOnlyOneCell,
+ invisible,
+ onDeleteCell,
+}) => {
+ return (
+ <Column
+ columnId={column.id}
+ canMoveLeft={index > 0}
+ canMoveRight={index < columnsLength - 1}
+ width={appConfig.width}
+ canDelete={columnsLength > 1}
+ footer={
+ <AddCellButtons
+ columnId={column.id}
+ className={cn(
+ appConfig.width === "columns" &&
+ "opacity-0 group-hover/column:opacity-100",
+ )}
+ />
+ }
+ >
+ <SortableContext
+ id={`column-${index + 1}`}
+ items={column.topLevelIds}
+ strategy={verticalListSortingStrategy}
+ >
+ {column.topLevelIds.map((cellId) => {
+ const cellData = notebook.cellData[cellId];
+ const cellRuntime = notebook.cellRuntime[cellId];
+ return (
+ <Cell
+ key={cellData.id.toString()}
+ theme={theme}
+ showPlaceholder={hasOnlyOneCell}
+ allowFocus={!invisible && !notebook.scrollKey}
+ id={cellData.id}
+ code={cellData.code}
+ outline={cellRuntime.outline}
+ output={cellRuntime.output}
+ consoleOutputs={cellRuntime.consoleOutputs}
+ status={cellRuntime.status}
+ edited={cellData.edited}
+ interrupted={cellRuntime.interrupted}
+ errored={cellRuntime.errored}
+ stopped={cellRuntime.stopped}
+ staleInputs={cellRuntime.staleInputs}
+ runStartTimestamp={cellRuntime.runStartTimestamp}
+ lastRunStartTimestamp={cellRuntime.lastRunStartTimestamp}
+ runElapsedTimeMs={
+ cellRuntime.runElapsedTimeMs ??
+ (cellData.lastExecutionTime as Milliseconds)
+ }
+ serializedEditorState={cellData.serializedEditorState}
+ canDelete={!hasOnlyOneCell}
+ mode={mode}
+ appClosed={connStatus.state !== WebSocketState.OPEN}
+ ref={notebook.cellHandles[cellId]}
+ userConfig={userConfig}
+ debuggerActive={cellRuntime.debuggerActive}
+ config={cellData.config}
+ name={cellData.name}
+ isCollapsed={column.isCollapsed(cellId)}
+ collapseCount={column.getCount(cellId)}
+ canMoveX={appConfig.width === "columns"}
+ {...actions}
+ deleteCell={onDeleteCell}
+ />
+ );
+ })}
+ </SortableContext>
+ </Column>
+ );
+};
+
const AddCellButtons: React.FC<{
columnId: CellColumnId;
className?: string;
diff --git a/frontend/src/components/editor/renderers/cells-renderer.tsx b/frontend/src/components/editor/renderers/cells-renderer.tsx
index 72ebe28ae0..629ac20e4e 100644
--- a/frontend/src/components/editor/renderers/cells-renderer.tsx
+++ b/frontend/src/components/editor/renderers/cells-renderer.tsx
@@ -5,10 +5,18 @@ import { type PropsWithChildren, memo } from "react";
import { cellRendererPlugins } from "./plugins";
import type { AppConfig } from "@/core/config/config-schema";
import { type AppMode, kioskModeAtom } from "@/core/mode";
-import { useLayoutActions, useLayoutState } from "@/core/layout/layout";
+import {
+ type LayoutData,
+ useLayoutActions,
+ useLayoutState,
+} from "@/core/layout/layout";
import { useAtomValue } from "jotai";
import { KnownQueryParams } from "@/core/constants";
-import { type LayoutType, OVERRIDABLE_LAYOUT_TYPES } from "./types";
+import {
+ type ICellRendererPlugin,
+ type LayoutType,
+ OVERRIDABLE_LAYOUT_TYPES,
+} from "./types";
interface Props {
appConfig: AppConfig;
@@ -17,9 +25,7 @@ interface Props {
export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(
({ appConfig, mode, children }) => {
- const notebook = useNotebook();
const { selectedLayout, layoutData } = useLayoutState();
- const { setCurrentLayoutData } = useLayoutActions();
const kioskMode = useAtomValue(kioskModeAtom);
// Just render children if we are in edit mode
@@ -46,20 +52,44 @@ export const CellsRenderer: React.FC<PropsWithChildren<Props>> = memo(
return children;
}
- const cells = flattenTopLevelNotebookCells(notebook);
-
- const Renderer = plugin.Component;
- const body = (
- <Renderer
+ return (
+ <PluginCellRenderer
appConfig={appConfig}
mode={mode}
- cells={cells}
- layout={layoutData[finalLayout] || plugin.getInitialLayout(cells)}
- setLayout={setCurrentLayoutData}
+ plugin={plugin}
+ layoutData={layoutData}
+ finalLayout={finalLayout}
/>
);
-
- return body;
},
);
CellsRenderer.displayName = "CellsRenderer";
+
+interface PluginCellRendererProps extends PropsWithChildren<Props> {
+ appConfig: AppConfig;
+ mode: AppMode;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ plugin: ICellRendererPlugin<any, any>;
+ layoutData: Partial<Record<LayoutType, LayoutData>>;
+ finalLayout: LayoutType;
+}
+
+export const PluginCellRenderer = (props: PluginCellRendererProps) => {
+ const { appConfig, mode, plugin, layoutData, finalLayout } = props;
+ const notebook = useNotebook();
+ const { setCurrentLayoutData } = useLayoutActions();
+ const cells = flattenTopLevelNotebookCells(notebook);
+
+ const Renderer = plugin.Component;
+ const body = (
+ <Renderer
+ appConfig={appConfig}
+ mode={mode}
+ cells={cells}
+ layout={layoutData[finalLayout] || plugin.getInitialLayout(cells)}
+ setLayout={setCurrentLayoutData}
+ />
+ );
+
+ return body;
+};
diff --git a/frontend/src/components/sort/SortableCellsProvider.tsx b/frontend/src/components/sort/SortableCellsProvider.tsx
index 5ba4d2b9ba..701b075c35 100644
--- a/frontend/src/components/sort/SortableCellsProvider.tsx
+++ b/frontend/src/components/sort/SortableCellsProvider.tsx
@@ -18,7 +18,7 @@ import {
} from "@dnd-kit/core";
import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
import { sortableKeyboardCoordinates } from "@dnd-kit/sortable";
-import { useCellActions, useNotebook } from "../../core/cells/cells";
+import { getNotebook, useCellActions } from "../../core/cells/cells";
import { useEvent } from "../../hooks/useEvent";
import type { CellId } from "@/core/cells/ids";
import { useAppConfig } from "@/core/config/config";
@@ -42,7 +42,6 @@ const SortableCellsProviderInternal = ({
children,
multiColumn,
}: SortableCellsProviderProps) => {
- const { cellIds } = useNotebook();
const { dropCellOverCell, dropCellOverColumn, moveColumn, compactColumns } =
useCellActions();
@@ -73,7 +72,8 @@ const SortableCellsProviderInternal = ({
const handleDragStart = useEvent((event: DragStartEvent) => {
setActiveId(event.active.id);
- setClonedItems(cellIds);
+ const notebook = getNotebook();
+ setClonedItems(notebook.cellIds);
});
const handleDragCancel = useEvent(() => {
@@ -134,7 +134,8 @@ const SortableCellsProviderInternal = ({
invariant(isColumnId(overId), `Expected column id. Got: ${overId}`);
// If column is empty, we can drop on it
- const column = cellIds.get(overId);
+ const notebook = getNotebook();
+ const column = notebook.cellIds.get(overId);
invariant(column, `Expected column. Got: ${overId}`);
if (column && column.topLevelIds.length === 0) {
// Return the column
@@ -160,7 +161,7 @@ const SortableCellsProviderInternal = ({
return [];
},
- [activeId, cellIds],
+ [activeId],
);
const handleDragOver = useEvent(({ active, over }) => {
diff --git a/frontend/src/components/ui/tooltip.tsx b/frontend/src/components/ui/tooltip.tsx
index 9aa56c4791..7ceff88270 100644
--- a/frontend/src/components/ui/tooltip.tsx
+++ b/frontend/src/components/ui/tooltip.tsx
@@ -5,7 +5,12 @@ import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "@/utils/cn";
import { StyleNamespace } from "@/theme/namespace";
-const TooltipProvider = TooltipPrimitive.Provider;
+const TooltipProvider = ({
+ delayDuration = 400,
+ ...props
+}: TooltipPrimitive.TooltipProviderProps) => (
+ <TooltipPrimitive.Provider delayDuration={delayDuration} {...props} />
+);
const TooltipRoot = TooltipPrimitive.Root;
diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsx
index 31920c2405..5b4d5eab57 100644
--- a/frontend/src/core/MarimoApp.tsx
+++ b/frontend/src/core/MarimoApp.tsx
@@ -83,7 +83,7 @@ const Providers = memo(({ children }: PropsWithChildren) => {
return (
<ErrorBoundary>
<Suspense>
- <TooltipProvider delayDuration={400}>
+ <TooltipProvider>
<SlotzProvider controller={slotsController}>
<ModalProvider>
{children}
diff --git a/frontend/src/core/cells/__tests__/utils.test.ts b/frontend/src/core/cells/__tests__/utils.test.ts
index cadbaacbc8..0db44b1db2 100644
--- a/frontend/src/core/cells/__tests__/utils.test.ts
+++ b/frontend/src/core/cells/__tests__/utils.test.ts
@@ -1,9 +1,16 @@
/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
import { describe, it, expect } from "vitest";
import { getCellConfigs, type NotebookState } from "@/core/cells/cells";
import { CellId } from "@/core/cells/ids";
import { MultiColumn } from "@/utils/id-tree";
import type { CellData, CellRuntimeState } from "@/core/cells/types";
+import {
+ disabledCellIds,
+ enabledCellIds,
+ isUninstantiated,
+ staleCellIds,
+} from "../utils";
describe("getCellConfigs", () => {
it("should return correct cell configs with column indices", () => {
@@ -59,7 +66,6 @@ describe("getCellConfigs", () => {
expect(mockState.cellData[cellId1].config).toEqual({
hide_code: false,
disabled: false,
- column: 0,
});
expect(mockState.cellData[cellId2].config).toEqual({
hide_code: true,
@@ -68,7 +74,6 @@ describe("getCellConfigs", () => {
expect(mockState.cellData[cellId3].config).toEqual({
hide_code: false,
disabled: true,
- column: 1,
});
expect(mockState.cellData[cellId4].config).toEqual({
hide_code: true,
@@ -115,3 +120,347 @@ describe("getCellConfigs", () => {
expect(result).toEqual([]);
});
});
+
+describe("staleCellIds", () => {
+ it("should return cell IDs that have not been instantiated when auto-instantiate is false", () => {
+ const state: NotebookState = {
+ cellIds: MultiColumn.from([["cell1", "cell2"]]),
+ cellData: {
+ cell1: {
+ lastExecutionTime: null,
+ edited: false,
+ config: { disabled: false },
+ },
+ cell2: {
+ lastExecutionTime: 123,
+ edited: false,
+ config: { disabled: false },
+ },
+ },
+ cellRuntime: {
+ cell1: {
+ runElapsedTimeMs: null,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ staleInputs: false,
+ },
+ cell2: {
+ runElapsedTimeMs: 456,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ staleInputs: false,
+ },
+ },
+ } as any;
+
+ const result = staleCellIds(state, false);
+
+ expect(result).toEqual(["cell1"]);
+ });
+
+ it("should use lastExecutionTime when runElapsedTimeMs is null", () => {
+ const state: NotebookState = {
+ cellIds: MultiColumn.from([["cell1", "cell2"]]),
+ cellData: {
+ cell1: {
+ lastExecutionTime: null,
+ edited: false,
+ config: { disabled: false },
+ },
+ cell2: {
+ lastExecutionTime: 123,
+ edited: false,
+ config: { disabled: false },
+ },
+ },
+ cellRuntime: {
+ cell1: {
+ runElapsedTimeMs: null,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ staleInputs: false,
+ },
+ cell2: {
+ runElapsedTimeMs: null,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ staleInputs: false,
+ },
+ },
+ } as any;
+
+ const result = staleCellIds(state, false);
+
+ expect(result).toEqual(["cell1"]);
+ });
+
+ it("should return cell IDs that are edited", () => {
+ const state: NotebookState = {
+ cellIds: MultiColumn.from([["cell1", "cell2"]]),
+ cellData: {
+ cell1: {
+ lastExecutionTime: 123,
+ edited: true,
+ config: { disabled: false },
+ },
+ cell2: {
+ lastExecutionTime: 123,
+ edited: false,
+ config: { disabled: false },
+ },
+ },
+ cellRuntime: {
+ cell1: {
+ runElapsedTimeMs: 456,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ staleInputs: false,
+ },
+ cell2: {
+ runElapsedTimeMs: 456,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ staleInputs: false,
+ },
+ },
+ } as any;
+
+ const result = staleCellIds(state, true);
+
+ expect(result).toEqual(["cell1"]);
+ });
+
+ it("should return cell IDs that are interrupted", () => {
+ const state: NotebookState = {
+ cellIds: MultiColumn.from([["cell1", "cell2"]]),
+ cellData: {
+ cell1: {
+ lastExecutionTime: 123,
+ edited: false,
+ config: { disabled: false },
+ },
+ cell2: {
+ lastExecutionTime: 123,
+ edited: false,
+ config: { disabled: false },
+ },
+ },
+ cellRuntime: {
+ cell1: {
+ runElapsedTimeMs: 456,
+ status: "idle",
+ errored: false,
+ interrupted: true,
+ stopped: false,
+ staleInputs: false,
+ },
+ cell2: {
+ runElapsedTimeMs: 456,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ staleInputs: false,
+ },
+ },
+ } as any;
+
+ const result = staleCellIds(state, true);
+
+ expect(result).toEqual(["cell1"]);
+ });
+
+ it("should not return cell IDs that are disabled", () => {
+ const state: NotebookState = {
+ cellIds: MultiColumn.from([["cell1", "cell2"]]),
+ cellData: {
+ cell1: {
+ lastExecutionTime: 123,
+ edited: false,
+ config: { disabled: true },
+ },
+ cell2: {
+ lastExecutionTime: 123,
+ edited: false,
+ config: { disabled: false },
+ },
+ },
+ cellRuntime: {
+ cell1: {
+ runElapsedTimeMs: 456,
+ status: "disabled-transitively",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ staleInputs: true,
+ },
+ cell2: {
+ runElapsedTimeMs: 456,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ staleInputs: false,
+ },
+ },
+ } as any;
+
+ const result = staleCellIds(state, true);
+
+ expect(result).toEqual([]);
+ });
+});
+
+describe("isUninstantiated", () => {
+ it("should return true if autoInstantiate is false and cell has not run", () => {
+ const result = isUninstantiated({
+ autoInstantiate: false,
+ executionTime: null,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ });
+ expect(result).toBe(true);
+ });
+
+ it("should return false if autoInstantiate is true", () => {
+ const result = isUninstantiated({
+ autoInstantiate: true,
+ executionTime: null,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ });
+ expect(result).toBe(false);
+ });
+
+ it("should return false if cell has run", () => {
+ const result = isUninstantiated({
+ autoInstantiate: false,
+ executionTime: 123,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ });
+ expect(result).toBe(false);
+ });
+
+ it("should return false if cell is currently queued or running", () => {
+ let result = isUninstantiated({
+ autoInstantiate: false,
+ executionTime: null,
+ status: "queued",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ });
+ expect(result).toBe(false);
+
+ result = isUninstantiated({
+ autoInstantiate: false,
+ executionTime: null,
+ status: "running",
+ errored: false,
+ interrupted: false,
+ stopped: false,
+ });
+ expect(result).toBe(false);
+ });
+
+ it("should return false if cell is in an error state", () => {
+ let result = isUninstantiated({
+ autoInstantiate: false,
+ executionTime: null,
+ status: "idle",
+ errored: true,
+ interrupted: false,
+ stopped: false,
+ });
+ expect(result).toBe(false);
+
+ result = isUninstantiated({
+ autoInstantiate: false,
+ executionTime: null,
+ status: "idle",
+ errored: false,
+ interrupted: true,
+ stopped: false,
+ });
+ expect(result).toBe(false);
+
+ result = isUninstantiated({
+ autoInstantiate: false,
+ executionTime: null,
+ status: "idle",
+ errored: false,
+ interrupted: false,
+ stopped: true,
+ });
+ expect(result).toBe(false);
+ });
+});
+
+describe("disabledCellIds", () => {
+ it("should return only disabled cell IDs", () => {
+ const cellId1 = CellId.create();
+ const cellId2 = CellId.create();
+ const cellId3 = CellId.create();
+
+ const state: NotebookState = {
+ cellIds: MultiColumn.from([[cellId1, cellId2, cellId3]]),
+ cellData: {
+ [cellId1]: { id: cellId1, config: { disabled: true } } as CellData,
+ [cellId2]: { id: cellId2, config: { disabled: false } } as CellData,
+ [cellId3]: { id: cellId3, config: { disabled: true } } as CellData,
+ },
+ cellRuntime: {} as Record<CellId, CellRuntimeState>,
+ cellHandles: {},
+ history: [],
+ scrollKey: null,
+ cellLogs: [],
+ };
+
+ const result = disabledCellIds(state);
+ expect(result).toEqual([cellId1, cellId3]);
+ });
+});
+
+describe("enabledCellIds", () => {
+ it("should return only enabled cell IDs", () => {
+ const cellId1 = CellId.create();
+ const cellId2 = CellId.create();
+ const cellId3 = CellId.create();
+
+ const state: NotebookState = {
+ cellIds: MultiColumn.from([[cellId1, cellId2, cellId3]]),
+ cellData: {
+ [cellId1]: { id: cellId1, config: { disabled: true } } as CellData,
+ [cellId2]: { id: cellId2, config: { disabled: false } } as CellData,
+ [cellId3]: { id: cellId3, config: { disabled: false } } as CellData,
+ },
+ cellRuntime: {} as Record<CellId, CellRuntimeState>,
+ cellHandles: {},
+ history: [],
+ scrollKey: null,
+ cellLogs: [],
+ };
+
+ const result = enabledCellIds(state);
+ expect(result).toEqual([cellId2, cellId3]);
+ });
+});
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 9b01ecd7eb..77381dd2ce 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -15,7 +15,7 @@ import {
} from "./scrollCellIntoView";
import { CellId } from "./ids";
import { prepareCellForExecution, transitionCell } from "./cell";
-import { store } from "../state/jotai";
+import { createDeepEqualAtom, store } from "../state/jotai";
import { createReducerAndAtoms } from "../../utils/createReducer";
import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";
import { findCollapseRange, mergeOutlines, parseOutline } from "../dom/outline";
@@ -28,19 +28,20 @@ import { type CellLog, getCellLogsForMessage } from "./logs";
import { deserializeBase64, deserializeJson } from "@/utils/json/base64";
import { historyField } from "@codemirror/commands";
import { clamp } from "@/utils/math";
-import type { LayoutState } from "../layout/layout";
-import { notebookIsRunning, notebookQueueOrRunningCount } from "./utils";
+import {
+ canUndoDeletes,
+ disabledCellIds,
+ enabledCellIds,
+ notebookIsRunning,
+ notebookNeedsRun,
+ notebookQueueOrRunningCount,
+} from "./utils";
import {
splitEditor,
updateEditorCodeFromPython,
} from "../codemirror/language/utils";
import { invariant } from "@/utils/invariant";
-import type {
- CellConfig,
- RuntimeState,
- UpdateCellIdsRequest,
-} from "../network/types";
-import { getUserConfig } from "@/core/config/config";
+import type { CellConfig, UpdateCellIdsRequest } from "../network/types";
import { syncCellIds } from "../network/requests";
import { kioskModeAtom } from "../mode";
import {
@@ -50,6 +51,7 @@ import {
} from "@/utils/id-tree";
import { isEqual } from "lodash-es";
import { isErrorMime } from "../mime";
+import { userConfigAtom } from "../config/config";
export const SCRATCH_CELL_ID = "__scratch__" as CellId;
@@ -97,13 +99,6 @@ export interface NotebookState {
cellLogs: CellLog[];
}
-export interface LastSavedNotebook {
- codes: string[];
- configs: CellConfig[];
- names: string[];
- layout: LayoutState;
-}
-
function withScratchCell(notebookState: NotebookState): NotebookState {
const config = { column: 0, hide_code: false, disabled: false };
return {
@@ -1146,12 +1141,12 @@ export function getCellConfigs(state: NotebookState): CellConfig[] {
config.column = columnIndex;
}
- cells[cellId].config = {
+ const newConfig = {
...cells[cellId].config,
...config,
};
- return cells[cellId].config;
+ return newConfig;
});
});
}
@@ -1170,6 +1165,23 @@ export const hasOnlyOneCellAtom = atom((get) =>
get(cellIdsAtom).hasOnlyOneId(),
);
+export const hasDisabledCellsAtom = atom(
+ (get) => disabledCellIds(get(notebookAtom)).length > 0,
+);
+export const hasEnabledCellsAtom = atom(
+ (get) => enabledCellIds(get(notebookAtom)).length > 0,
+);
+export const canUndoDeletesAtom = atom((get) =>
+ canUndoDeletes(get(notebookAtom)),
+);
+
+export const needsRunAtom = atom((get) =>
+ notebookNeedsRun(
+ get(notebookAtom),
+ get(userConfigAtom).runtime.auto_instantiate,
+ ),
+);
+
const cellErrorsAtom = atom((get) => {
const { cellIds, cellRuntime, cellData } = get(notebookAtom);
const errors = cellIds.inOrderIds
@@ -1210,13 +1222,15 @@ 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.inOrderIds.map((cellId) => [cellId, cellData[cellId]?.name]),
- );
- return names;
-});
+export const cellIdToNamesMap = createDeepEqualAtom(
+ atom((get) => {
+ const { cellIds, cellData } = get(notebookAtom);
+ const names: Record<CellId, string | undefined> = Objects.fromEntries(
+ cellIds.inOrderIds.map((cellId) => [cellId, cellData[cellId]?.name]),
+ );
+ return names;
+ }),
+);
/// HOOKS
@@ -1279,6 +1293,16 @@ export const notebookQueuedOrRunningCountAtom = atom((get) =>
notebookQueueOrRunningCount(get(notebookAtom)),
);
+export const numColumnsAtom = atom(
+ (get) => get(notebookAtom).cellIds.colLength,
+);
+export const hasCellsAtom = atom(
+ (get) => get(notebookAtom).cellIds.idLength > 0,
+);
+export const columnIdsAtom = atom((get) =>
+ get(notebookAtom).cellIds.getColumnIds(),
+);
+
/**
* Get the editor views for all cells.
*/
@@ -1294,58 +1318,6 @@ export const getCellEditorView = (cellId: CellId) => {
return cellHandles[cellId].current?.editorView;
};
-export function isUninstantiated(
- autoInstantiate: boolean,
- executionTime: number | null,
- status: RuntimeState,
- errored: boolean,
- interrupted: boolean,
- stopped: boolean,
-) {
- return (
- // autorun on startup is off ...
- !autoInstantiate &&
- // hasn't run ...
- executionTime === null &&
- // isn't currently queued/running &&
- status !== "queued" &&
- status !== "running" &&
- // and isn't in an error state.
- !(errored || interrupted || stopped)
- );
-}
-
-/**
- * Cells that are stale and can be run.
- */
-export function staleCellIds(state: NotebookState) {
- const autoInstantiate = getUserConfig().runtime.auto_instantiate;
-
- const { cellIds, cellData, cellRuntime } = state;
- return cellIds.inOrderIds.filter(
- (cellId) =>
- isUninstantiated(
- autoInstantiate,
- // runElapstedTimeMs is what we've seen in this session
- cellRuntime[cellId].runElapsedTimeMs ??
- // lastExecutionTime is what was seen on session start/resume
- cellData[cellId].lastExecutionTime,
- cellRuntime[cellId].status,
- cellRuntime[cellId].errored,
- cellRuntime[cellId].interrupted,
- cellRuntime[cellId].stopped,
- ) ||
- cellData[cellId].edited ||
- cellRuntime[cellId].interrupted ||
- (cellRuntime[cellId].staleInputs &&
- // if a cell is disabled, it can't be run ...
- !(
- cellRuntime[cellId].status === "disabled-transitively" ||
- cellData[cellId].config.disabled
- )),
- );
-}
-
export function flattenTopLevelNotebookCells(
state: NotebookState,
): Array<CellData & CellRuntimeState> {
diff --git a/frontend/src/core/cells/utils.ts b/frontend/src/core/cells/utils.ts
index c542b4508e..6a32f95cc7 100644
--- a/frontend/src/core/cells/utils.ts
+++ b/frontend/src/core/cells/utils.ts
@@ -1,15 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type { CellId } from "./ids";
-import { arrayShallowEquals } from "@/utils/arrays";
import { Objects } from "@/utils/objects";
import type { EditorView } from "@codemirror/view";
-import type { LayoutState } from "../layout/layout";
-import { isEqual } from "lodash-es";
-import {
- type NotebookState,
- type LastSavedNotebook,
- staleCellIds,
-} from "./cells";
+import type { NotebookState } from "./cells";
+import type { RuntimeState } from "../network/types";
export function notebookIsRunning(state: NotebookState) {
return Object.values(state.cellRuntime).some(
@@ -22,30 +16,11 @@ export function notebookQueueOrRunningCount(state: NotebookState) {
).length;
}
-export function notebookNeedsSave(
+export function notebookNeedsRun(
state: NotebookState,
- layout: LayoutState,
- lastSavedNotebook: LastSavedNotebook | undefined,
+ autoInstantiate: boolean,
) {
- if (!lastSavedNotebook) {
- return false;
- }
- const { cellIds, cellData } = state;
- const data = cellIds.inOrderIds.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, lastSavedNotebook.codes) ||
- !arrayShallowEquals(names, lastSavedNotebook.names) ||
- !isEqual(configs, lastSavedNotebook.configs) ||
- !isEqual(layout.selectedLayout, lastSavedNotebook.layout.selectedLayout) ||
- !isEqual(layout.layoutData, lastSavedNotebook.layout.layoutData)
- );
-}
-
-export function notebookNeedsRun(state: NotebookState) {
- return staleCellIds(state).length > 0;
+ return staleCellIds(state, autoInstantiate).length > 0;
}
export function notebookCells(state: NotebookState) {
@@ -65,16 +40,26 @@ export function notebookCellEditorViews({ cellHandles }: NotebookState) {
export function disabledCellIds(state: NotebookState) {
const { cellIds, cellData } = state;
- return cellIds.inOrderIds
- .map((cellId) => cellData[cellId])
- .filter((cell) => cell.config.disabled);
+ const disabledCells: CellId[] = [];
+ for (const cellId of cellIds.inOrderIds) {
+ const cell = cellData[cellId];
+ if (cell.config.disabled) {
+ disabledCells.push(cellId);
+ }
+ }
+ return disabledCells;
}
export function enabledCellIds(state: NotebookState) {
const { cellIds, cellData } = state;
- return cellIds.inOrderIds
- .map((cellId) => cellData[cellId])
- .filter((cell) => !cell.config.disabled);
+ const enabledCells: CellId[] = [];
+ for (const cellId of cellIds.inOrderIds) {
+ const cell = cellData[cellId];
+ if (!cell.config.disabled) {
+ enabledCells.push(cellId);
+ }
+ }
+ return enabledCells;
}
export function canUndoDeletes(state: NotebookState) {
@@ -103,3 +88,61 @@ export function getDescendantsStatus(state: NotebookState, cellId: CellId) {
runningOrQueued,
};
}
+
+/**
+ * Cells that are stale and can be run.
+ */
+export function staleCellIds(state: NotebookState, autoInstantiate: boolean) {
+ const { cellIds, cellData, cellRuntime } = state;
+ return cellIds.inOrderIds.filter(
+ (cellId) =>
+ isUninstantiated({
+ autoInstantiate,
+ // runElapstedTimeMs is what we've seen in this session
+ executionTime:
+ cellRuntime[cellId].runElapsedTimeMs ??
+ // lastExecutionTime is what was seen on session start/resume
+ cellData[cellId].lastExecutionTime,
+ status: cellRuntime[cellId].status,
+ errored: cellRuntime[cellId].errored,
+ interrupted: cellRuntime[cellId].interrupted,
+ stopped: cellRuntime[cellId].stopped,
+ }) ||
+ cellData[cellId].edited ||
+ cellRuntime[cellId].interrupted ||
+ (cellRuntime[cellId].staleInputs &&
+ // if a cell is disabled, it can't be run ...
+ !(
+ cellRuntime[cellId].status === "disabled-transitively" ||
+ cellData[cellId].config.disabled
+ )),
+ );
+}
+
+export function isUninstantiated({
+ autoInstantiate,
+ executionTime,
+ status,
+ errored,
+ interrupted,
+ stopped,
+}: {
+ autoInstantiate: boolean;
+ executionTime: number | null;
+ status: RuntimeState;
+ errored: boolean;
+ interrupted: boolean;
+ stopped: boolean;
+}) {
+ return (
+ // autorun on startup is off ...
+ !autoInstantiate &&
+ // hasn't run ...
+ executionTime === null &&
+ // isn't currently queued/running &&
+ status !== "queued" &&
+ status !== "running" &&
+ // and isn't in an error state.
+ !(errored || interrupted || stopped)
+ );
+}
diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.ts
index 7043bf9cda..a67e0aef86 100644
--- a/frontend/src/core/config/config.ts
+++ b/frontend/src/core/config/config.ts
@@ -27,6 +27,10 @@ export const hotkeysAtom = atom((get) => {
return new OverridingHotkeyProvider(overrides);
});
+export const autoSaveConfigAtom = atom((get) => {
+ return get(userConfigAtom).save;
+});
+
/**
* Returns the user config.
*/
diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsx
index 10e6cb3716..d16fcda75c 100644
--- a/frontend/src/core/edit-app.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -1,69 +1,39 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { useEffect, useState } from "react";
+import { useEffect } from "react";
-import {
- sendComponentValues,
- sendInterrupt,
- sendRename,
- sendSave,
-} from "@/core/network/requests";
+import { sendComponentValues, sendInterrupt } from "@/core/network/requests";
import { Controls } from "@/components/editor/controls/Controls";
-import { FilenameInput } from "@/components/editor/header/filename-input";
import { FilenameForm } from "@/components/editor/header/filename-form";
import { WebSocketState } from "./websocket/types";
import { useMarimoWebSocket } from "./websocket/useMarimoWebSocket";
import {
- type LastSavedNotebook,
notebookIsRunningAtom,
useCellActions,
- useNotebook,
CellEffects,
cellIdsAtom,
- getCellConfigs,
+ numColumnsAtom,
+ hasCellsAtom,
} from "./cells/cells";
-import {
- canUndoDeletes,
- notebookCells,
- notebookNeedsRun,
- notebookNeedsSave,
-} from "./cells/utils";
import type { AppConfig, UserConfig } from "./config/config-schema";
-import { kioskModeAtom, viewStateAtom } from "./mode";
+import { viewStateAtom } from "./mode";
import { useHotkey } from "../hooks/useHotkey";
-import { useImperativeModal } from "../components/modal/ImperativeModal";
-import {
- DialogContent,
- DialogFooter,
- DialogTitle,
-} from "../components/ui/dialog";
-import { Label } from "../components/ui/label";
-import { Button } from "../components/ui/button";
-import { useEvent } from "../hooks/useEvent";
-import { Logger } from "../utils/Logger";
-import { useAutoSave } from "./saving/useAutoSave";
-import { useEventListener } from "../hooks/useEventListener";
-import { toast } from "../components/ui/use-toast";
import { CellArray } from "../components/editor/renderers/CellArray";
import { RuntimeState } from "./kernel/RuntimeState";
import { CellsRenderer } from "../components/editor/renderers/cells-renderer";
-import { getSerializedLayout, useLayoutState } from "./layout/layout";
-import { useAtomValue } from "jotai";
+import { useAtomValue, useSetAtom } from "jotai";
import { useRunStaleCells } from "../components/editor/cell/useRunCells";
-import { formatAll } from "./codemirror/format";
import { cn } from "@/utils/cn";
-import { isStaticNotebook } from "./static/static-state";
import { useFilename } from "./saving/filename";
import { getSessionId } from "./kernel/session";
-import { updateQueryParams } from "@/utils/urls";
import { AppHeader } from "@/components/editor/header/app-header";
import { AppContainer } from "../components/editor/app-container";
import { useJotaiEffect } from "./state/jotai";
import { Paths } from "@/utils/paths";
-import { KnownQueryParams } from "./constants";
import { useTogglePresenting } from "./layout/useTogglePresenting";
-import { useAutoExport } from "./export/hooks";
import { usePrevious } from "@dnd-kit/utilities";
+import { TooltipProvider } from "@radix-ui/react-tooltip";
+import { lastSavedNotebookAtom } from "./saving/state";
interface AppProps {
userConfig: UserConfig;
@@ -71,26 +41,18 @@ interface AppProps {
}
export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
- const notebook = useNotebook();
-
useJotaiEffect(cellIdsAtom, CellEffects.onCellIdsChange);
- const { setCells, updateCellCode, mergeAllColumns } = useCellActions();
+ const { setCells, mergeAllColumns } = useCellActions();
const viewState = useAtomValue(viewStateAtom);
- const [filename, setFilename] = useFilename();
- const [lastSavedNotebook, setLastSavedNotebook] =
- useState<LastSavedNotebook>();
- const layout = useLayoutState();
- const { openModal, closeModal, openAlert } = useImperativeModal();
+ const numColumns = useAtomValue(numColumnsAtom);
+ const hasCells = useAtomValue(hasCellsAtom);
+ const filename = useFilename();
+ const setLastSavedNotebook = useSetAtom(lastSavedNotebookAtom);
const isEditing = viewState.mode === "edit";
const isPresenting = viewState.mode === "present";
const isRunning = useAtomValue(notebookIsRunningAtom);
- const kioskMode = useAtomValue(kioskModeAtom);
-
- function alertSaveFailed() {
- openAlert("Failed to save notebook: not connected to a kernel.");
- }
// Initialize RuntimeState event-listeners
useEffect(() => {
@@ -112,34 +74,6 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
sessionId: getSessionId(),
});
- const handleFilenameChange = useEvent(async (name: string) => {
- if (connection.state !== WebSocketState.OPEN) {
- alertSaveFailed();
- return null;
- }
-
- updateQueryParams((params) => {
- if (name === null) {
- params.delete(KnownQueryParams.filePath);
- } else {
- params.set(KnownQueryParams.filePath, name);
- }
- });
-
- return sendRename({ filename: name })
- .then(() => {
- setFilename(name);
- // Set document title: app_title takes precedence, then filename, then default
- document.title =
- appConfig.app_title || Paths.basename(name) || "Untitled Notebook";
- return name;
- })
- .catch((error) => {
- openAlert(error.message);
- return null;
- });
- });
-
// Update document title whenever filename or app_title changes
useEffect(() => {
// Set document title: app_title takes precedence, then filename, then default
@@ -150,7 +84,6 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
}, [appConfig.app_title, filename]);
// Delete column breakpoints if app width changes from "columns"
- const numColumns = notebook.cellIds.colLength;
const previousWidth = usePrevious(appConfig.width);
useEffect(() => {
if (previousWidth === "columns" && appConfig.width !== "columns") {
@@ -158,106 +91,6 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
}
}, [appConfig.width, previousWidth, mergeAllColumns, numColumns]);
- const cells = notebookCells(notebook);
- const cellIds = cells.map((cell) => cell.id);
- const codes = cells.map((cell) => cell.code);
- const cellNames = cells.map((cell) => cell.name);
- const configs = getCellConfigs(notebook);
- const needsSave = notebookNeedsSave(notebook, layout, lastSavedNotebook);
-
- // Save the notebook with the given filename
- const saveNotebook = useEvent((filename: string, userInitiated: boolean) => {
- if (kioskMode) {
- return;
- }
-
- // Don't save if there are no cells
- if (codes.length === 0) {
- return;
- }
-
- // Don't save if we are not connected to a kernel
- if (connection.state !== WebSocketState.OPEN) {
- alertSaveFailed();
- return;
- }
-
- Logger.log("saving to ", filename);
- sendSave({
- cellIds: cellIds,
- codes,
- names: cellNames,
- filename,
- configs,
- layout: getSerializedLayout(),
- persist: true,
- }).then(() => {
- if (userInitiated) {
- toast({ title: "Notebook saved" });
- if (userConfig.save.format_on_save) {
- formatAll(updateCellCode);
- }
- }
- setLastSavedNotebook({
- names: cellNames,
- codes,
- configs,
- layout,
- });
- });
- });
-
- // Save the notebook with the current filename, only if the filename exists
- const saveIfNotebookIsNamed = useEvent((userInitiated = false) => {
- if (filename !== null && connection.state === WebSocketState.OPEN) {
- saveNotebook(filename, userInitiated);
- }
- });
-
- // Save the notebook with the current filename, or prompt the user to name
- const saveOrNameNotebook = useEvent(() => {
- saveIfNotebookIsNamed(true);
-
- // Filename does not exist and we are connected to a kernel
- if (filename === null && connection.state !== WebSocketState.CLOSED) {
- openModal(<SaveDialog onClose={closeModal} onSave={handleSaveDialog} />);
- }
- });
-
- useAutoSave({
- // Only run autosave if the file is named
- onSave: saveIfNotebookIsNamed,
- // Reset autosave when needsSave, or codes/configs have changed
- needsSave: needsSave,
- codes: codes,
- cellConfigs: configs,
- cellNames: cellNames,
- connStatus: connection,
- config: userConfig,
- kioskMode: kioskMode,
- });
- useAutoExport();
-
- useEventListener(window, "beforeunload", (e: BeforeUnloadEvent) => {
- if (isStaticNotebook()) {
- return;
- }
-
- if (needsSave) {
- e.preventDefault();
- return (e.returnValue =
- "You have unsaved changes. Are you sure you want to quit?");
- }
- });
-
- const handleSaveDialog = (pythonFilename: string) => {
- handleFilenameChange(pythonFilename).then((name) => {
- if (name !== null) {
- saveNotebook(name, true);
- }
- });
- };
-
const runStaleCells = useRunStaleCells();
const togglePresenting = useTogglePresenting();
@@ -265,7 +98,6 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
useHotkey("global.runStale", () => {
runStaleCells();
});
- useHotkey("global.save", saveOrNameNotebook);
useHotkey("global.interrupt", () => {
sendInterrupt();
});
@@ -273,24 +105,8 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
togglePresenting();
});
- const getCellsAsJSON = useEvent(() => {
- return JSON.stringify(
- {
- filename: filename,
- cells: cells.map((cell) => {
- return { name: cell.name, code: cell.code };
- }),
- },
- // no replacer
- null,
- // whitespace for indentation
- 2,
- );
- });
-
const editableCellsArray = (
<CellArray
- notebook={notebook}
connStatus={connection}
mode={viewState.mode}
userConfig={userConfig}
@@ -315,85 +131,29 @@ export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
>
{isEditing && (
<div className="flex items-center justify-center container">
- <FilenameForm
- filename={filename}
- setFilename={handleFilenameChange}
- />
+ <FilenameForm filename={filename} />
</div>
)}
</AppHeader>
{/* Don't render until we have a single cell */}
- {cells.length > 0 && (
+ {hasCells && (
<CellsRenderer appConfig={appConfig} mode={viewState.mode}>
{editableCellsArray}
</CellsRenderer>
)}
</AppContainer>
- <Controls
- filename={filename}
- needsSave={needsSave}
- onSaveNotebook={saveOrNameNotebook}
- getCellsAsJSON={getCellsAsJSON}
- presenting={isPresenting}
- onTogglePresenting={togglePresenting}
- onInterrupt={sendInterrupt}
- onRun={runStaleCells}
- closed={connection.state === WebSocketState.CLOSED}
- running={isRunning}
- needsRun={notebookNeedsRun(notebook)}
- undoAvailable={canUndoDeletes(notebook)}
- appWidth={appConfig.width}
- />
- </>
- );
-};
-
-const SaveDialog = (props: {
- onClose: () => void;
- onSave: (filename: string) => void;
-}) => {
- const { onClose, onSave } = props;
- const cancelButtonLabel = "Cancel";
- const [filename, setFilename] = useState<string>();
- const handleFilenameChange = (name: string) => {
- setFilename(name);
- if (name.trim()) {
- onSave(name);
- onClose();
- }
- };
-
- return (
- <DialogContent>
- <DialogTitle>Save notebook</DialogTitle>
- <div className="flex flex-col">
- <Label className="text-md pt-6 px-1">Save as</Label>
- <FilenameInput
- onNameChange={handleFilenameChange}
- placeholderText="filename"
- className="missing-filename"
+ <TooltipProvider>
+ <Controls
+ presenting={isPresenting}
+ onTogglePresenting={togglePresenting}
+ onInterrupt={sendInterrupt}
+ onRun={runStaleCells}
+ closed={connection.state === WebSocketState.CLOSED}
+ running={isRunning}
+ appConfig={appConfig}
/>
- </div>
- <DialogFooter>
- <Button
- data-testid="cancel-save-dialog-button"
- aria-label={cancelButtonLabel}
- variant="secondary"
- onClick={onClose}
- >
- Cancel
- </Button>
- <Button
- data-testid="submit-save-dialog-button"
- aria-label="Save"
- variant="default"
- disabled={!filename}
- type="submit"
- >
- Save
- </Button>
- </DialogFooter>
- </DialogContent>
+ </TooltipProvider>
+ </>
);
};
diff --git a/frontend/src/core/layout/layout.ts b/frontend/src/core/layout/layout.ts
index 8366b43d5a..3d558e9a60 100644
--- a/frontend/src/core/layout/layout.ts
+++ b/frontend/src/core/layout/layout.ts
@@ -57,6 +57,8 @@ const { valueAtom: layoutStateAtom, useActions } = createReducerAndAtoms(
},
);
+export { layoutStateAtom };
+
export const useLayoutState = () => {
return useAtomValue(layoutStateAtom);
};
diff --git a/frontend/src/core/saving/filename.ts b/frontend/src/core/saving/filename.ts
index 335c669f27..b0e7d85765 100644
--- a/frontend/src/core/saving/filename.ts
+++ b/frontend/src/core/saving/filename.ts
@@ -1,10 +1,56 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { atom, useAtom } from "jotai";
+import { atom, useAtom, useAtomValue, useSetAtom } from "jotai";
import { getFilenameFromDOM } from "../dom/htmlUtils";
+import { sendRename } from "../network/requests";
+import { Paths } from "@/utils/paths";
+import { updateQueryParams } from "@/utils/urls";
+import useEvent from "react-use-event-hook";
+import { KnownQueryParams } from "../constants";
+import { WebSocketState } from "../websocket/types";
+import { useImperativeModal } from "@/components/modal/ImperativeModal";
+import { connectionAtom } from "../network/connection";
+import { getAppConfig } from "../config/config";
const filenameAtom = atom<string | null>(getFilenameFromDOM());
export function useFilename() {
- return useAtom(filenameAtom);
+ return useAtomValue(filenameAtom);
+}
+
+export function useUpdateFilename() {
+ const [connection] = useAtom(connectionAtom);
+ const setFilename = useSetAtom(filenameAtom);
+ const { openAlert } = useImperativeModal();
+
+ const handleFilenameChange = useEvent(async (name: string) => {
+ const appConfig = getAppConfig();
+ if (connection.state !== WebSocketState.OPEN) {
+ openAlert("Failed to save notebook: not connected to a kernel.");
+ return null;
+ }
+
+ updateQueryParams((params) => {
+ if (name === null) {
+ params.delete(KnownQueryParams.filePath);
+ } else {
+ params.set(KnownQueryParams.filePath, name);
+ }
+ });
+
+ return sendRename({ filename: name })
+ .then(() => {
+ setFilename(name);
+ // Set document title: app_title takes precedence, then filename, then default
+ document.title =
+ appConfig.app_title || Paths.basename(name) || "Untitled Notebook";
+ return name;
+ })
+ .catch((error) => {
+ openAlert(error.message);
+ return null;
+ });
+ });
+
+ return handleFilenameChange;
}
diff --git a/frontend/src/core/saving/save-component.tsx b/frontend/src/core/saving/save-component.tsx
new file mode 100644
index 0000000000..8e98d619af
--- /dev/null
+++ b/frontend/src/core/saving/save-component.tsx
@@ -0,0 +1,231 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { useState } from "react";
+
+import { sendSave } from "@/core/network/requests";
+
+import { FilenameInput } from "@/components/editor/header/filename-input";
+import { WebSocketState } from "../websocket/types";
+import { useCellActions, useNotebook, getCellConfigs } from "../cells/cells";
+import { notebookCells } from "../cells/utils";
+import type { AppConfig } from "../config/config-schema";
+import { useImperativeModal } from "../../components/modal/ImperativeModal";
+import {
+ DialogContent,
+ DialogFooter,
+ DialogTitle,
+} from "../../components/ui/dialog";
+import { Label } from "../../components/ui/label";
+import { Button } from "../../components/ui/button";
+import { useEvent } from "../../hooks/useEvent";
+import { Logger } from "../../utils/Logger";
+import { useAutoSave } from "./useAutoSave";
+import { toast } from "../../components/ui/use-toast";
+import { getSerializedLayout, useLayoutState } from "../layout/layout";
+import { useAtom, useAtomValue, useSetAtom } from "jotai";
+import { formatAll } from "../codemirror/format";
+import { useFilename, useUpdateFilename } from "./filename";
+import { connectionAtom } from "../network/connection";
+import { autoSaveConfigAtom } from "../config/config";
+import { lastSavedNotebookAtom, needsSaveAtom } from "./state";
+import { Tooltip } from "@/components/ui/tooltip";
+import { RecoveryButton } from "@/components/editor/RecoveryButton";
+import { renderShortcut } from "@/components/shortcuts/renderShortcut";
+import { SaveIcon } from "lucide-react";
+import { useHotkey } from "@/hooks/useHotkey";
+import { Button as ControlButton } from "@/components/editor/inputs/Inputs";
+
+interface SaveNotebookProps {
+ kioskMode: boolean;
+ appConfig: AppConfig;
+}
+
+export const SaveComponent = ({ kioskMode, appConfig }: SaveNotebookProps) => {
+ const filename = useFilename();
+ const { saveOrNameNotebook, needsSave, closed } = useSaveNotebook({
+ appConfig,
+ kioskMode,
+ });
+
+ const handleSaveClick = (e: React.MouseEvent<HTMLButtonElement>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ saveOrNameNotebook();
+ };
+
+ useHotkey("global.save", saveOrNameNotebook);
+
+ if (closed) {
+ return <RecoveryButton filename={filename} needsSave={needsSave} />;
+ }
+
+ return (
+ <Tooltip content={renderShortcut("global.save")}>
+ <ControlButton
+ data-testid="save-button"
+ id="save-button"
+ shape="rectangle"
+ color={needsSave ? "yellow" : "hint-green"}
+ onClick={handleSaveClick}
+ >
+ <SaveIcon strokeWidth={1.5} size={18} />
+ </ControlButton>
+ </Tooltip>
+ );
+};
+
+export function useSaveNotebook({ kioskMode, appConfig }: SaveNotebookProps) {
+ const autoSaveConfig = useAtomValue(autoSaveConfigAtom);
+ const { updateCellCode } = useCellActions();
+ const notebook = useNotebook();
+ const [connection] = useAtom(connectionAtom);
+ const filename = useFilename();
+ const { openModal, closeModal, openAlert } = useImperativeModal();
+ const setLastSavedNotebook = useSetAtom(lastSavedNotebookAtom);
+ const updateFilename = useUpdateFilename();
+ const needsSave = useAtomValue(needsSaveAtom);
+ const layout = useLayoutState();
+
+ // Save the notebook with the given filename
+ const saveNotebook = useEvent((filename: string, userInitiated: boolean) => {
+ const cells = notebookCells(notebook);
+ const cellIds = cells.map((cell) => cell.id);
+ const codes = cells.map((cell) => cell.code);
+ const cellNames = cells.map((cell) => cell.name);
+ const configs = getCellConfigs(notebook);
+
+ if (kioskMode) {
+ return;
+ }
+
+ // Don't save if there are no cells
+ if (codes.length === 0) {
+ return;
+ }
+
+ // Don't save if we are not connected to a kernel
+ if (connection.state !== WebSocketState.OPEN) {
+ openAlert("Failed to save notebook: not connected to a kernel.");
+ return;
+ }
+
+ Logger.log("saving to ", filename);
+ sendSave({
+ cellIds: cellIds,
+ codes,
+ names: cellNames,
+ filename,
+ configs,
+ layout: getSerializedLayout(),
+ persist: true,
+ }).then(() => {
+ if (userInitiated) {
+ toast({ title: "Notebook saved" });
+ if (autoSaveConfig.format_on_save) {
+ formatAll(updateCellCode);
+ }
+ }
+ setLastSavedNotebook({
+ names: cellNames,
+ codes,
+ configs,
+ layout,
+ });
+ });
+ });
+
+ // Save the notebook with the current filename, only if the filename exists
+ const saveIfNotebookIsNamed = useEvent((userInitiated = false) => {
+ if (filename !== null && connection.state === WebSocketState.OPEN) {
+ saveNotebook(filename, userInitiated);
+ }
+ });
+
+ const handleSaveDialog = (pythonFilename: string) => {
+ updateFilename(pythonFilename).then((name) => {
+ if (name !== null) {
+ saveNotebook(name, true);
+ }
+ });
+ };
+
+ // Save the notebook with the current filename, or prompt the user to name
+ const saveOrNameNotebook = useEvent(() => {
+ saveIfNotebookIsNamed(true);
+
+ // Filename does not exist and we are connected to a kernel
+ if (filename === null && connection.state !== WebSocketState.CLOSED) {
+ openModal(<SaveDialog onClose={closeModal} onSave={handleSaveDialog} />);
+ }
+ });
+
+ const cells = notebookCells(notebook);
+ const codes = cells.map((cell) => cell.code);
+ const cellNames = cells.map((cell) => cell.name);
+ const configs = getCellConfigs(notebook);
+
+ useAutoSave({
+ onSave: saveIfNotebookIsNamed,
+ needsSave: needsSave,
+ codes: codes,
+ cellConfigs: configs,
+ cellNames: cellNames,
+ connStatus: connection,
+ config: autoSaveConfig,
+ kioskMode: kioskMode,
+ });
+
+ return {
+ saveOrNameNotebook,
+ needsSave,
+ closed: connection.state === WebSocketState.CLOSED,
+ };
+}
+
+const SaveDialog = (props: {
+ onClose: () => void;
+ onSave: (filename: string) => void;
+}) => {
+ const { onClose, onSave } = props;
+ const cancelButtonLabel = "Cancel";
+ const [filename, setFilename] = useState<string>();
+ const handleFilenameChange = (name: string) => {
+ setFilename(name);
+ if (name.trim()) {
+ onSave(name);
+ onClose();
+ }
+ };
+
+ return (
+ <DialogContent>
+ <DialogTitle>Save notebook</DialogTitle>
+ <div className="flex flex-col">
+ <Label className="text-md pt-6 px-1">Save as</Label>
+ <FilenameInput
+ onNameChange={handleFilenameChange}
+ placeholderText="filename"
+ className="missing-filename"
+ />
+ </div>
+ <DialogFooter>
+ <Button
+ data-testid="cancel-save-dialog-button"
+ aria-label={cancelButtonLabel}
+ variant="secondary"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ <Button
+ data-testid="submit-save-dialog-button"
+ aria-label="Save"
+ variant="default"
+ disabled={!filename}
+ type="submit"
+ >
+ Save
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ );
+};
diff --git a/frontend/src/core/saving/state.ts b/frontend/src/core/saving/state.ts
new file mode 100644
index 0000000000..cfd1746250
--- /dev/null
+++ b/frontend/src/core/saving/state.ts
@@ -0,0 +1,47 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { atom } from "jotai";
+import { type LayoutState, layoutStateAtom } from "../layout/layout";
+import type { CellConfig } from "../network/types";
+import { arrayShallowEquals } from "@/utils/arrays";
+import { isEqual } from "lodash-es";
+import { notebookAtom, type NotebookState } from "../cells/cells";
+
+export interface LastSavedNotebook {
+ codes: string[];
+ configs: CellConfig[];
+ names: string[];
+ layout: LayoutState;
+}
+
+export const lastSavedNotebookAtom = atom<LastSavedNotebook | undefined>(
+ undefined,
+);
+
+export const needsSaveAtom = atom((get) => {
+ const lastSavedNotebook = get(lastSavedNotebookAtom);
+ const state = get(notebookAtom);
+ const layout = get(layoutStateAtom);
+ return notebookNeedsSave(state, layout, lastSavedNotebook);
+});
+
+export function notebookNeedsSave(
+ state: NotebookState,
+ layout: LayoutState,
+ lastSavedNotebook: LastSavedNotebook | undefined,
+) {
+ if (!lastSavedNotebook) {
+ return false;
+ }
+ const { cellIds, cellData } = state;
+ const data = cellIds.inOrderIds.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, lastSavedNotebook.codes) ||
+ !arrayShallowEquals(names, lastSavedNotebook.names) ||
+ !isEqual(configs, lastSavedNotebook.configs) ||
+ !isEqual(layout.selectedLayout, lastSavedNotebook.layout.selectedLayout) ||
+ !isEqual(layout.layoutData, lastSavedNotebook.layout.layoutData)
+ );
+}
diff --git a/frontend/src/core/saving/useAutoSave.ts b/frontend/src/core/saving/useAutoSave.ts
index 256917f028..163e92060c 100644
--- a/frontend/src/core/saving/useAutoSave.ts
+++ b/frontend/src/core/saving/useAutoSave.ts
@@ -8,7 +8,7 @@ export function useAutoSave(opts: {
codes: string[];
cellConfigs: CellConfig[];
cellNames: string[];
- config: UserConfig;
+ config: UserConfig["save"];
connStatus: ConnectionStatus;
needsSave: boolean;
kioskMode: boolean;
@@ -26,22 +26,25 @@ export function useAutoSave(opts: {
} = opts;
const autosaveTimeoutId = useRef<NodeJS.Timeout | null>(null);
+ const codesString = codes.join(":");
+ const cellConfigsString = cellConfigs
+ .map((config) => JSON.stringify(config))
+ .join(":");
+ const cellNamesString = cellNames.join(":");
+
useEffect(() => {
// If kiosk mode is enabled, do not autosave
if (kioskMode) {
return;
}
- if (config.save.autosave === "after_delay") {
+ if (config.autosave === "after_delay") {
if (autosaveTimeoutId.current !== null) {
clearTimeout(autosaveTimeoutId.current);
}
if (needsSave && connStatus.state === WebSocketState.OPEN) {
- autosaveTimeoutId.current = setTimeout(
- onSave,
- config.save.autosave_delay,
- );
+ autosaveTimeoutId.current = setTimeout(onSave, config.autosave_delay);
}
}
@@ -53,10 +56,10 @@ export function useAutoSave(opts: {
// codes, cellConfigs, cellNames needed in deps array to prevent race condition
// with needsSave when user changes state rapidly
}, [
- codes,
- cellConfigs,
- cellNames,
- config.save,
+ codesString,
+ cellConfigsString,
+ cellNamesString,
+ config,
connStatus.state,
onSave,
kioskMode,
diff --git a/frontend/src/core/state/jotai.ts b/frontend/src/core/state/jotai.ts
index 0e77dbdcfb..5a3df068be 100644
--- a/frontend/src/core/state/jotai.ts
+++ b/frontend/src/core/state/jotai.ts
@@ -1,5 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { type Atom, createStore, useStore } from "jotai";
+import { atom, type Atom, createStore, useStore } from "jotai";
+import { isEqual } from "lodash-es";
import { useEffect } from "react";
/**
@@ -46,3 +47,22 @@ export function useJotaiEffect<T>(
});
}, [atom, effect, store]);
}
+
+const sentinel = Symbol("sentinel");
+
+export function createDeepEqualAtom<T>(
+ baseAtom: Atom<T>,
+ areEqual: (a: T, b: T) => boolean = isEqual,
+) {
+ let cachedValue: T | typeof sentinel = sentinel;
+
+ return atom((get) => {
+ const nextValue = get(baseAtom);
+
+ if (cachedValue === sentinel || !areEqual(cachedValue, nextValue)) {
+ cachedValue = nextValue;
+ }
+
+ return cachedValue;
+ });
+}
diff --git a/frontend/src/core/variables/state.ts b/frontend/src/core/variables/state.ts
index 5d6039a6c5..63ed1a3f8e 100644
--- a/frontend/src/core/variables/state.ts
+++ b/frontend/src/core/variables/state.ts
@@ -15,6 +15,9 @@ const {
useActions,
} = createReducerAndAtoms(initialState, {
setVariables: (state, variables: Variable[]) => {
+ if (variables.length === 0) {
+ return state;
+ }
// start with empty state, but keep the old state's metadata
const oldVariables = { ...state };
const newVariables: Variables = {};
diff --git a/frontend/src/hooks/debug.ts b/frontend/src/hooks/debug.ts
index 2bfd323f05..dbc625266d 100644
--- a/frontend/src/hooks/debug.ts
+++ b/frontend/src/hooks/debug.ts
@@ -49,16 +49,17 @@ export function usePropsDidChange(
return prevProps.current[key] !== props[key];
});
- // If any props are deeply equal, we should warn about it
const equalKeys = changedKeys.filter((key) => {
return dequal(prevProps.current[key], props[key]);
});
if (changedKeys.length > 0) {
Logger.debug(`[${name}] Props changed: ${changedKeys.join(", ")}`);
- if (equalKeys.length > 0) {
+
+ // If all changed keys are deeply equal, we should warn about it
+ if (equalKeys.length === changedKeys.length) {
Logger.debug(
- `[${name}] Props are deeply equal: ${equalKeys.join(", ")}`,
+ `[${name}] ⚠️ Props are deeply equal: ${equalKeys.join(", ")}`,
);
}
}
diff --git a/frontend/src/plugins/core/BadPlugin.tsx b/frontend/src/plugins/core/BadPlugin.tsx
index 7972196f37..71535d3cc7 100644
--- a/frontend/src/plugins/core/BadPlugin.tsx
+++ b/frontend/src/plugins/core/BadPlugin.tsx
@@ -26,7 +26,7 @@ export const BadPluginData: React.FC<Props> = ({
return (
<Alert variant="destructive">
<AlertTitle>Bad Data</AlertTitle>
- <div className="text-md">
+ <div className="text-md prose dark:prose-invert">
<ul>
{error.issues.map((issue) => {
const path = issue.path.join(".");
diff --git a/frontend/src/utils/id-tree.tsx b/frontend/src/utils/id-tree.tsx
index 4f921b394b..11a13a0c16 100644
--- a/frontend/src/utils/id-tree.tsx
+++ b/frontend/src/utils/id-tree.tsx
@@ -78,6 +78,7 @@ export class CollapsibleTree<T> {
return new CollapsibleTree(nodes, this.id);
}
+ @Memoize()
get topLevelIds(): T[] {
return this.nodes.map((n) => n.value);
}
@@ -429,6 +430,7 @@ export class MultiColumn<T> {
return MultiColumn.from(idsList);
}
+ @Memoize()
get topLevelIds(): T[][] {
return this.columns.map((c) => c.topLevelIds);
}
@@ -447,6 +449,7 @@ export class MultiColumn<T> {
return iter();
}
+ @Memoize()
get inOrderIds(): T[] {
return this.columns.flatMap((c) => c.inOrderIds);
}
@@ -487,6 +490,11 @@ export class MultiColumn<T> {
return this.idLength === 1;
}
+ @Memoize()
+ getColumnIds(): CellColumnId[] {
+ return this.columns.map((c) => c.id);
+ }
+
indexOf(column: CollapsibleTree<T>): number {
return this.columns.indexOf(column);
}
diff --git a/frontend/vite.config.mts b/frontend/vite.config.mts
index 59514edeb6..647cbeecd1 100644
--- a/frontend/vite.config.mts
+++ b/frontend/vite.config.mts
@@ -22,9 +22,11 @@ const htmlDevPlugin = (): Plugin => {
// Add react-scan in dev mode
if (isDev) {
+ // For latest, use:
+ // '<head>\n<script src="https://unpkg.com/react-scan/dist/auto.global.js"></script>',
html = html.replace(
"<head>",
- '<head>\n<script src="https://unpkg.com/react-scan/dist/auto.global.js"></script>',
+ '<head>\n<script src="https://unpkg.com/[email protected]/dist/auto.global.js"></script>',
);
}