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.

refactor: lazy-load top-level pages, reduce initial page load (#1295)

Myles Scolnicka802eb24bd04
diff --git a/frontend/src/components/indicator.tsx b/frontend/src/components/debug/indicator.tsx
similarity index 100%
rename from frontend/src/components/indicator.tsx
rename to frontend/src/components/debug/indicator.tsx
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index e63e994ab4..0318c0879a 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -22,13 +22,12 @@ import {
Undo2Icon,
} from "lucide-react";
import { commandPaletteAtom } from "../controls/command-palette";
+import { useCellActions, useNotebook } from "@/core/cells/cells";
import {
canUndoDeletes,
disabledCellIds,
enabledCellIds,
- useCellActions,
- useNotebook,
-} from "@/core/cells/cells";
+} from "@/core/cells/utils";
import { readCode, saveCellConfig } from "@/core/network/requests";
import { Objects } from "@/utils/objects";
import { ActionButton } from "./types";
diff --git a/frontend/src/components/editor/app-container.tsx b/frontend/src/components/editor/app-container.tsx
new file mode 100644
index 0000000000..ccb92fcaff
--- /dev/null
+++ b/frontend/src/components/editor/app-container.tsx
@@ -0,0 +1,37 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { WebSocketState } from "@/core/websocket/types";
+import { cn } from "@/utils/cn";
+import React, { PropsWithChildren } from "react";
+import { StatusOverlay } from "./header/status";
+import { AppConfig } from "@/core/config/config-schema";
+
+interface Props {
+ connectionState: WebSocketState;
+ isRunning: boolean;
+ width: AppConfig["width"];
+}
+
+export const AppContainer: React.FC<PropsWithChildren<Props>> = ({
+ width,
+ connectionState,
+ isRunning,
+ children,
+}) => {
+ return (
+ <>
+ <StatusOverlay state={connectionState} isRunning={isRunning} />
+ <div
+ id="App"
+ className={cn(
+ connectionState === WebSocketState.CLOSED && "disconnected",
+ "bg-background w-full h-full text-textColor",
+ "flex flex-col overflow-y-auto overflow-x-hidden",
+ width === "full" && "config-width-full",
+ )}
+ >
+ {children}
+ </div>
+ </>
+ );
+};
diff --git a/frontend/src/components/editor/header/app-header.tsx b/frontend/src/components/editor/header/app-header.tsx
new file mode 100644
index 0000000000..1dfa9d827b
--- /dev/null
+++ b/frontend/src/components/editor/header/app-header.tsx
@@ -0,0 +1,24 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { ConnectionStatus, WebSocketState } from "@/core/websocket/types";
+import React, { PropsWithChildren } from "react";
+import { Disconnected } from "../Disconnected";
+
+interface Props {
+ className?: string;
+ connection: ConnectionStatus;
+}
+
+export const AppHeader: React.FC<PropsWithChildren<Props>> = ({
+ connection,
+ className,
+ children,
+}) => {
+ return (
+ <div className={className}>
+ {children}
+ {connection.state === WebSocketState.CLOSED && (
+ <Disconnected reason={connection.reason} />
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/editor/header/status.tsx b/frontend/src/components/editor/header/status.tsx
new file mode 100644
index 0000000000..104b790a19
--- /dev/null
+++ b/frontend/src/components/editor/header/status.tsx
@@ -0,0 +1,48 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { Tooltip } from "@/components/ui/tooltip";
+import { notebookScrollToRunning } from "@/core/cells/actions";
+import { WebSocketState } from "@/core/websocket/types";
+import { UnlinkIcon, HourglassIcon } from "lucide-react";
+import React from "react";
+
+export const StatusOverlay: React.FC<{
+ state: WebSocketState;
+ isRunning: boolean;
+}> = ({ state, isRunning }) => {
+ return (
+ <>
+ {state === WebSocketState.OPEN && isRunning && <RunningIcon />}
+ {state === WebSocketState.CLOSED && <NoiseBackground />}
+ {state === WebSocketState.CLOSED && <DisconnectedIcon />}
+ </>
+ );
+};
+
+const topLeftStatus =
+ "absolute top-3 left-4 m-0 flex items-center space-x-3 min-h-[28px] no-print pointer-events-auto z-30";
+
+const DisconnectedIcon = () => (
+ <Tooltip content="App disconnected">
+ <div className={topLeftStatus}>
+ <UnlinkIcon className="closed-app-icon" />
+ </div>
+ </Tooltip>
+);
+
+const RunningIcon = () => (
+ <div
+ className={topLeftStatus}
+ data-testid="loading-indicator"
+ title={"Marimo is busy computing. Hang tight!"}
+ onClick={notebookScrollToRunning}
+ >
+ <HourglassIcon className="running-app-icon" size={30} strokeWidth={1} />
+ </div>
+);
+
+const NoiseBackground = () => (
+ <>
+ <div className="noise" />
+ <div className="disconnected-gradient" />
+ </>
+);
diff --git a/frontend/src/components/pages/edit-page.tsx b/frontend/src/components/pages/edit-page.tsx
new file mode 100644
index 0000000000..46673b804f
--- /dev/null
+++ b/frontend/src/components/pages/edit-page.tsx
@@ -0,0 +1,21 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { EditApp } from "@/core/edit-app";
+import { AppChrome } from "../editor/chrome/wrapper/app-chrome";
+import { CommandPalette } from "../editor/controls/command-palette";
+import { AppConfig, UserConfig } from "@/core/config/config-schema";
+
+interface Props {
+ userConfig: UserConfig;
+ appConfig: AppConfig;
+}
+
+const EditPage = (props: Props) => {
+ return (
+ <AppChrome>
+ <EditApp {...props} />
+ <CommandPalette />
+ </AppChrome>
+ );
+};
+
+export default EditPage;
diff --git a/frontend/src/components/home/home-page.tsx b/frontend/src/components/pages/home-page.tsx
similarity index 99%
rename from frontend/src/components/home/home-page.tsx
rename to frontend/src/components/pages/home-page.tsx
index dff853b032..a258669c8d 100644
--- a/frontend/src/components/home/home-page.tsx
+++ b/frontend/src/components/pages/home-page.tsx
@@ -32,7 +32,7 @@ function tabTarget(path: string) {
return `${getSessionId()}-${encodeURIComponent(path)}`;
}
-export const HomePage: React.FC = () => {
+const HomePage: React.FC = () => {
const fileResponse = useAsyncData(async () => {
const [workspace, recents] = await Promise.all([
getWorkspaceFiles(),
@@ -276,3 +276,5 @@ const CreateNewNotebook: React.FC = () => {
// </div>
// );
// };
+
+export default HomePage;
diff --git a/frontend/src/components/pages/run-page.tsx b/frontend/src/components/pages/run-page.tsx
new file mode 100644
index 0000000000..92c1e7283e
--- /dev/null
+++ b/frontend/src/components/pages/run-page.tsx
@@ -0,0 +1,19 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { AppConfig } from "@/core/config/config-schema";
+import { RunApp } from "@/core/run-app";
+import { StaticBanner } from "../static-html/static-banner";
+
+interface Props {
+ appConfig: AppConfig;
+}
+
+const RunPage = (props: Props) => {
+ return (
+ <>
+ <StaticBanner />
+ <RunApp appConfig={props.appConfig} />
+ </>
+ );
+};
+
+export default RunPage;
diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsx
index 46df4d7d18..8da4dd885f 100644
--- a/frontend/src/core/MarimoApp.tsx
+++ b/frontend/src/core/MarimoApp.tsx
@@ -1,27 +1,27 @@
/* Copyright 2024 Marimo. All rights reserved. */
import "../css/index.css";
+import "../css/app/App.css";
import "iconify-icon";
-import { PropsWithChildren, memo, useEffect } from "react";
+import React, { PropsWithChildren, Suspense, memo } from "react";
import { ErrorBoundary } from "../components/editor/boundary/ErrorBoundary";
-import { initializePlugins } from "../plugins/plugins";
-import { App } from "./App";
import { TooltipProvider } from "../components/ui/tooltip";
import { Toaster } from "../components/ui/toaster";
import { ModalProvider } from "../components/modal/ImperativeModal";
import { DayPickerProvider } from "react-day-picker";
-import { CommandPalette } from "../components/editor/controls/command-palette";
import { useAppConfig, useUserConfig } from "@/core/config/config";
import { initialMode } from "./mode";
-import { AppChrome } from "../components/editor/chrome/wrapper/app-chrome";
-import { StaticBanner } from "../components/static-html/static-banner";
import { CssVariables } from "@/theme/ThemeProvider";
import { useAsyncData } from "@/hooks/useAsyncData";
import { isPyodide } from "./pyodide/utils";
import { PyodideBridge } from "./pyodide/bridge";
import { LargeSpinner } from "@/components/icons/large-spinner";
-import { TailwindIndicator } from "@/components/indicator";
-import { HomePage } from "@/components/home/home-page";
+import { TailwindIndicator } from "@/components/debug/indicator";
+
+// Lazy imports
+const LazyHomePage = React.lazy(() => import("@/components/pages/home-page"));
+const LazyRunPage = React.lazy(() => import("@/components/pages/run-page"));
+const LazyEditPage = React.lazy(() => import("@/components/pages/edit-page"));
/**
* The root component of the Marimo app.
@@ -29,57 +29,62 @@ import { HomePage } from "@/components/home/home-page";
export const MarimoApp: React.FC = memo(() => {
const [userConfig] = useUserConfig();
const [appConfig] = useAppConfig();
+ const editorFontSize = toRem(userConfig.display.code_editor_font_size);
- useEffect(() => {
- initializePlugins();
- }, []);
+ const renderBody = () => {
+ if (initialMode === "home") {
+ return <LazyHomePage />;
+ } else if (initialMode === "read") {
+ return <LazyRunPage appConfig={appConfig} />;
+ } else {
+ return <LazyEditPage userConfig={userConfig} appConfig={appConfig} />;
+ }
+ };
- const body =
- initialMode === "home" ? (
- <HomePage />
- ) : initialMode === "read" ? (
- <>
- <StaticBanner />
- <App userConfig={userConfig} appConfig={appConfig} />
- </>
- ) : (
- <AppChrome>
- <App userConfig={userConfig} appConfig={appConfig} />
- <CommandPalette />
- </AppChrome>
- );
+ return (
+ <Providers>
+ <CssVariables
+ variables={{ "--marimo-code-editor-font-size": editorFontSize }}
+ >
+ {renderBody()}
+ </CssVariables>
+ </Providers>
+ );
+});
+MarimoApp.displayName = "MarimoApp";
+/**
+ * The root with all the providers.
+ */
+const Providers = memo(({ children }: PropsWithChildren) => {
return (
<ErrorBoundary>
- <TooltipProvider>
- <DayPickerProvider initialProps={{}}>
- <PyodideLoader>
- <ModalProvider>
- <CssVariables
- variables={{
- "--marimo-code-editor-font-size": toRem(
- userConfig.display.code_editor_font_size,
- ),
- }}
- >
- {body}
+ <Suspense>
+ <TooltipProvider>
+ <DayPickerProvider initialProps={{}}>
+ <PyodideLoader>
+ <ModalProvider>
+ {children}
<Toaster />
- </CssVariables>
- <TailwindIndicator />
- </ModalProvider>
- </PyodideLoader>
- </DayPickerProvider>
- </TooltipProvider>
+ <TailwindIndicator />
+ </ModalProvider>
+ </PyodideLoader>
+ </DayPickerProvider>
+ </TooltipProvider>
+ </Suspense>
</ErrorBoundary>
);
});
-MarimoApp.displayName = "MarimoApp";
+Providers.displayName = "Providers";
function toRem(px: number) {
return `${px / 16}rem`;
}
-export const PyodideLoader: React.FC<PropsWithChildren> = ({ children }) => {
+/**
+ * HOC to load Pyodide before rendering children, if necessary.
+ */
+const PyodideLoader: React.FC<PropsWithChildren> = ({ children }) => {
if (!isPyodide()) {
return children;
}
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 12ffc1166b..f0f7104321 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -4,8 +4,8 @@ import {
NotebookState,
exportedForTesting,
flattenNotebookCells,
- notebookCells,
} from "../cells";
+import { notebookCells } from "../utils";
import { CellId } from "@/core/cells/ids";
import { OutputMessage } from "@/core/kernel/messages";
import { Seconds } from "@/utils/time";
diff --git a/frontend/src/core/cells/actions.ts b/frontend/src/core/cells/actions.ts
new file mode 100644
index 0000000000..91eea6e041
--- /dev/null
+++ b/frontend/src/core/cells/actions.ts
@@ -0,0 +1,25 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { store } from "../state/jotai";
+import { Objects } from "@/utils/objects";
+import { EditorView } from "@codemirror/view";
+import { getCellEditorView, notebookAtom } from "./cells";
+
+/**
+ * Scroll to the first cell that is currently in "running" state.
+ */
+export function notebookScrollToRunning() {
+ // find cell that is currently in "running" state
+ const { cellRuntime } = store.get(notebookAtom);
+ const cell = Objects.entries(cellRuntime).find(
+ ([cellid, runtimestate]) => runtimestate.status === "running",
+ );
+ if (!cell) {
+ return;
+ }
+ const view = getCellEditorView(cell[0]);
+ view?.dispatch({
+ selection: { anchor: 0 },
+ effects: [EditorView.scrollIntoView(0, { y: "center" })],
+ });
+}
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 7dd3248a9f..396d58ce81 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -19,13 +19,12 @@ import { CellId } from "./ids";
import { prepareCellForExecution, transitionCell } from "./cell";
import { store } from "../state/jotai";
import { createReducerAndAtoms } from "../../utils/createReducer";
-import { arrayInsert, arrayDelete, arrayShallowEquals } from "@/utils/arrays";
+import { arrayInsert, arrayDelete } from "@/utils/arrays";
import { foldAllBulk, unfoldAllBulk } from "../codemirror/editing/commands";
import { mergeOutlines } from "../dom/outline";
import { CellHandle } from "@/components/editor/Cell";
import { Logger } from "@/utils/Logger";
import { Objects } from "@/utils/objects";
-import { EditorView } from "@codemirror/view";
import { splitAtom, selectAtom } from "jotai/utils";
import { isStaticNotebook, parseStaticState } from "../static/static-state";
import { CellLog, getCellLogsForMessage } from "./logs";
@@ -33,7 +32,7 @@ import { deserializeBase64, deserializeJson } from "@/utils/json/base64";
import { historyField } from "@codemirror/commands";
import { clamp } from "@/utils/math";
import { LayoutState } from "../layout/layout";
-import { isEqual } from "lodash-es";
+import { notebookIsRunning } from "./utils";
/**
* The state of the notebook.
@@ -685,6 +684,8 @@ const cellErrorsAtom = atom((get) => {
return errors;
});
+export const notebookHasCellsAtom = atom((get) => get(cellIdsAtom).length > 0);
+
export const notebookOutline = atom((get) => {
const { cellIds, cellRuntime } = get(notebookAtom);
const outlines = cellIds.map((cellId) => cellRuntime[cellId].outline);
@@ -755,6 +756,10 @@ const cellDataAtoms = splitAtom(
);
export const useCellDataAtoms = () => useAtom(cellDataAtoms);
+export const notebookIsRunningAtom = atom((get) =>
+ notebookIsRunning(get(notebookAtom)),
+);
+
/**
* Get the editor views for all cells.
*/
@@ -770,89 +775,6 @@ export const getCellEditorView = (cellId: CellId) => {
return cellHandles[cellId].current?.editorView;
};
-/// HELPERS
-
-export function notebookIsRunning(state: NotebookState) {
- return Object.values(state.cellRuntime).some(
- (cell) => cell.status === "running",
- );
-}
-
-export function notebookScrollToRunning() {
- // find cell that is currently in "running" state
- const { cellRuntime } = store.get(notebookAtom);
- const cell = Objects.entries(cellRuntime).find(
- ([cellid, runtimestate]) => runtimestate.status === "running",
- );
- if (!cell) {
- return;
- }
- const view = getCellEditorView(cell[0]);
- view?.dispatch({
- selection: { anchor: 0 },
- effects: [EditorView.scrollIntoView(0, { y: "center" })],
- });
-}
-
-export function notebookNeedsSave(
- state: NotebookState,
- layout: LayoutState,
- 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, lastSavedNotebook.codes) ||
- !arrayShallowEquals(configs, lastSavedNotebook.configs) ||
- !arrayShallowEquals(names, lastSavedNotebook.names) ||
- !isEqual(layout.selectedLayout, lastSavedNotebook.layout.selectedLayout) ||
- !isEqual(layout.layoutData, lastSavedNotebook.layout.layoutData)
- );
-}
-
-export function notebookNeedsRun(state: NotebookState) {
- return staleCellIds(state).length > 0;
-}
-
-export function notebookCells(state: NotebookState) {
- return state.cellIds.map((cellId) => state.cellData[cellId]);
-}
-
-export function notebookCellEditorViews({ cellHandles }: NotebookState) {
- const views: Record<CellId, EditorView> = {};
- for (const [cell, ref] of Objects.entries(cellHandles)) {
- if (!ref.current) {
- continue;
- }
- views[cell] = ref.current.editorView;
- }
- return views;
-}
-
-export function disabledCellIds(state: NotebookState) {
- const { cellIds, cellData } = state;
- return cellIds
- .map((cellId) => cellData[cellId])
- .filter((cell) => cell.config.disabled);
-}
-
-export function enabledCellIds(state: NotebookState) {
- const { cellIds, cellData } = state;
- return cellIds
- .map((cellId) => cellData[cellId])
- .filter((cell) => !cell.config.disabled);
-}
-
-export function canUndoDeletes(state: NotebookState) {
- return state.history.length > 0;
-}
-
/**
* Cells that are stale and can be run.
*/
diff --git a/frontend/src/core/cells/utils.ts b/frontend/src/core/cells/utils.ts
new file mode 100644
index 0000000000..12459d9dee
--- /dev/null
+++ b/frontend/src/core/cells/utils.ts
@@ -0,0 +1,73 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { CellId } from "./ids";
+import { arrayShallowEquals } from "@/utils/arrays";
+import { Objects } from "@/utils/objects";
+import { EditorView } from "@codemirror/view";
+import { LayoutState } from "../layout/layout";
+import { isEqual } from "lodash-es";
+import { NotebookState, LastSavedNotebook, staleCellIds } from "./cells";
+
+export function notebookIsRunning(state: NotebookState) {
+ return Object.values(state.cellRuntime).some(
+ (cell) => cell.status === "running",
+ );
+}
+
+export function notebookNeedsSave(
+ state: NotebookState,
+ layout: LayoutState,
+ 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, lastSavedNotebook.codes) ||
+ !arrayShallowEquals(configs, lastSavedNotebook.configs) ||
+ !arrayShallowEquals(names, lastSavedNotebook.names) ||
+ !isEqual(layout.selectedLayout, lastSavedNotebook.layout.selectedLayout) ||
+ !isEqual(layout.layoutData, lastSavedNotebook.layout.layoutData)
+ );
+}
+
+export function notebookNeedsRun(state: NotebookState) {
+ return staleCellIds(state).length > 0;
+}
+
+export function notebookCells(state: NotebookState) {
+ return state.cellIds.map((cellId) => state.cellData[cellId]);
+}
+
+export function notebookCellEditorViews({ cellHandles }: NotebookState) {
+ const views: Record<CellId, EditorView> = {};
+ for (const [cell, ref] of Objects.entries(cellHandles)) {
+ if (!ref.current) {
+ continue;
+ }
+ views[cell] = ref.current.editorView;
+ }
+ return views;
+}
+
+export function disabledCellIds(state: NotebookState) {
+ const { cellIds, cellData } = state;
+ return cellIds
+ .map((cellId) => cellData[cellId])
+ .filter((cell) => cell.config.disabled);
+}
+
+export function enabledCellIds(state: NotebookState) {
+ const { cellIds, cellData } = state;
+ return cellIds
+ .map((cellId) => cellData[cellId])
+ .filter((cell) => !cell.config.disabled);
+}
+
+export function canUndoDeletes(state: NotebookState) {
+ return state.history.length > 0;
+}
diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.ts
index 0f3b12468c..a047354e77 100644
--- a/frontend/src/core/codemirror/format.ts
+++ b/frontend/src/core/codemirror/format.ts
@@ -3,11 +3,8 @@ import { EditorView } from "@codemirror/view";
import { CellId } from "../cells/ids";
import { Objects } from "../../utils/objects";
import { sendFormat } from "../network/requests";
-import {
- CellActions,
- getNotebook,
- notebookCellEditorViews,
-} from "../cells/cells";
+import { CellActions, getNotebook } from "../cells/cells";
+import { notebookCellEditorViews } from "../cells/utils";
import {
getEditorCodeAsPython,
updateEditorCodeFromPython,
diff --git a/frontend/src/core/App.tsx b/frontend/src/core/edit-app.tsx
similarity index 71%
rename from frontend/src/core/App.tsx
rename to frontend/src/core/edit-app.tsx
index 4b841b85ed..495afd885f 100644
--- a/frontend/src/core/App.tsx
+++ b/frontend/src/core/edit-app.tsx
@@ -1,7 +1,4 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import "../css/app/App.css";
-
-import { HourglassIcon, UnlinkIcon } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { sendInterrupt, sendRename, sendSave } from "@/core/network/requests";
@@ -13,20 +10,19 @@ import { WebSocketState } from "./websocket/types";
import { useMarimoWebSocket } from "./websocket/useMarimoWebSocket";
import {
LastSavedNotebook,
+ notebookIsRunningAtom,
+ useCellActions,
+ useNotebook,
+} from "./cells/cells";
+import {
canUndoDeletes,
notebookCells,
- notebookIsRunning,
notebookNeedsRun,
notebookNeedsSave,
- notebookScrollToRunning,
- useCellActions,
- useNotebook,
-} from "./cells/cells";
-import { Disconnected } from "../components/editor/Disconnected";
+} from "./cells/utils";
import { AppConfig, UserConfig } from "./config/config-schema";
import { toggleAppMode, viewStateAtom } from "./mode";
import { useHotkey } from "../hooks/useHotkey";
-import { Tooltip } from "../components/ui/tooltip";
import { useImperativeModal } from "../components/modal/ImperativeModal";
import {
DialogContent,
@@ -46,7 +42,7 @@ 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 { useAtom } from "jotai";
+import { useAtom, useAtomValue } from "jotai";
import { useRunStaleCells } from "../components/editor/cell/useRunCells";
import { formatAll } from "./codemirror/format";
import { cn } from "@/utils/cn";
@@ -54,13 +50,15 @@ 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";
interface AppProps {
userConfig: UserConfig;
appConfig: AppConfig;
}
-export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
+export const EditApp: React.FC<AppProps> = ({ userConfig, appConfig }) => {
const notebook = useNotebook();
const { setCells, updateCellCode } = useCellActions();
const [viewState, setViewState] = useAtom(viewStateAtom);
@@ -72,8 +70,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
const isEditing = viewState.mode === "edit";
const isPresenting = viewState.mode === "present";
- const isReading = viewState.mode === "read";
- const isRunning = notebookIsRunning(notebook);
+ const isRunning = useAtomValue(notebookIsRunningAtom);
function alertSaveFailed() {
openAlert("Failed to save notebook: not connected to a kernel.");
@@ -87,7 +84,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
};
}, []);
- const { connStatus } = useMarimoWebSocket({
+ const { connection } = useMarimoWebSocket({
autoInstantiate:
userConfig.runtime.auto_instantiate || viewState.mode === "read",
setCells: (cells, layout) => {
@@ -101,7 +98,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
});
const handleFilenameChange = useEvent(async (name: string | null) => {
- if (connStatus.state !== WebSocketState.OPEN) {
+ if (connection.state !== WebSocketState.OPEN) {
alertSaveFailed();
return null;
}
@@ -139,13 +136,8 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
return;
}
- // Don't save if we are in read mode
- if (isReading) {
- return;
- }
-
// Don't save if we are not connected to a kernel
- if (connStatus.state !== WebSocketState.OPEN) {
+ if (connection.state !== WebSocketState.OPEN) {
alertSaveFailed();
return;
}
@@ -176,7 +168,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
// Save the notebook with the current filename, only if the filename exists
const saveIfNotebookIsNamed = useEvent((userInitiated = false) => {
- if (filename !== null && connStatus.state === WebSocketState.OPEN) {
+ if (filename !== null && connection.state === WebSocketState.OPEN) {
saveNotebook(filename, userInitiated);
}
});
@@ -186,7 +178,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
saveIfNotebookIsNamed(true);
// Filename does not exist and we are connected to a kernel
- if (filename === null && connStatus.state !== WebSocketState.CLOSED) {
+ if (filename === null && connection.state !== WebSocketState.CLOSED) {
openModal(<SaveDialog onClose={closeModal} onSave={handleSaveDialog} />);
}
});
@@ -199,7 +191,7 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
codes: codes,
cellConfigs: configs,
cellNames: cellNames,
- connStatus: connStatus,
+ connStatus: connection,
config: userConfig,
});
@@ -268,9 +260,6 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
sendInterrupt();
});
useHotkey("global.hideCode", () => {
- if (isReading) {
- return;
- }
togglePresenting();
});
@@ -292,111 +281,61 @@ export const App: React.FC<AppProps> = ({ userConfig, appConfig }) => {
const editableCellsArray = (
<CellArray
notebook={notebook}
- connStatus={connStatus}
+ connStatus={connection}
mode={viewState.mode}
userConfig={userConfig}
appConfig={appConfig}
/>
);
- const statusOverlay = (
- <>
- {connStatus.state === WebSocketState.OPEN && isRunning && <RunningIcon />}
- {connStatus.state === WebSocketState.CLOSED && <NoiseBackground />}
- {connStatus.state === WebSocketState.CLOSED && <DisconnectedIcon />}
- </>
- );
-
return (
- <>
- {statusOverlay}
- <div
- id="App"
- className={cn(
- connStatus.state === WebSocketState.CLOSED && "disconnected",
- "bg-background w-full h-full text-textColor",
- "flex flex-col overflow-y-auto overflow-x-hidden",
- appConfig.width === "full" && "config-width-full",
- )}
+ <AppContainer
+ connectionState={connection.state}
+ isRunning={isRunning}
+ width={appConfig.width}
+ >
+ <AppHeader
+ connection={connection}
+ className={cn("pt-4 sm:pt-12 pb-2 mb-4")}
>
- <div
- className={cn(
- (isEditing || isPresenting) && "pt-4 sm:pt-12 pb-2 mb-4",
- isReading && "sm:pt-8",
- )}
- >
- {isEditing && (
- <div className="flex items-center justify-center container">
- <FilenameForm
- filename={filename}
- setFilename={handleFilenameChange}
- />
- </div>
- )}
- {connStatus.state === WebSocketState.CLOSED && (
- <Disconnected reason={connStatus.reason} />
- )}
- </div>
-
- {/* Don't render until we have a single cell */}
- {cells.length > 0 && (
- <CellsRenderer appConfig={appConfig} mode={viewState.mode}>
- <SortableCellsProvider disabled={!isEditing}>
- {editableCellsArray}
- </SortableCellsProvider>
- </CellsRenderer>
+ {isEditing && (
+ <div className="flex items-center justify-center container">
+ <FilenameForm
+ filename={filename}
+ setFilename={handleFilenameChange}
+ />
+ </div>
)}
- </div>
-
- {(isEditing || isPresenting) && (
- <Controls
- filename={filename}
- needsSave={needsSave}
- onSaveNotebook={saveOrNameNotebook}
- getCellsAsJSON={getCellsAsJSON}
- presenting={isPresenting}
- onTogglePresenting={togglePresenting}
- onInterrupt={sendInterrupt}
- onRun={runStaleCells}
- closed={connStatus.state === WebSocketState.CLOSED}
- running={isRunning}
- needsRun={notebookNeedsRun(notebook)}
- undoAvailable={canUndoDeletes(notebook)}
- appWidth={appConfig.width}
- />
+ </AppHeader>
+
+ {/* Don't render until we have a single cell */}
+ {cells.length > 0 && (
+ <CellsRenderer appConfig={appConfig} mode={viewState.mode}>
+ <SortableCellsProvider disabled={!isEditing}>
+ {editableCellsArray}
+ </SortableCellsProvider>
+ </CellsRenderer>
)}
- </>
+
+ <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}
+ />
+ </AppContainer>
);
};
-const topLeftStatus =
- "absolute top-3 left-4 m-0 flex items-center space-x-3 min-h-[28px] no-print pointer-events-auto z-30";
-const DisconnectedIcon = () => (
- <Tooltip content="App disconnected">
- <div className={topLeftStatus}>
- <UnlinkIcon className="closed-app-icon" />
- </div>
- </Tooltip>
-);
-
-const RunningIcon = () => (
- <div
- className={topLeftStatus}
- data-testid="loading-indicator"
- title={"Marimo is busy computing. Hang tight!"}
- onClick={notebookScrollToRunning}
- >
- <HourglassIcon className="running-app-icon" size={30} strokeWidth={1} />
- </div>
-);
-
-const NoiseBackground = () => (
- <>
- <div className="noise" />
- <div className="disconnected-gradient" />
- </>
-);
-
const SaveDialog = (props: {
onClose: () => void;
onSave: (filename: string) => void;
diff --git a/frontend/src/core/layout/layout.ts b/frontend/src/core/layout/layout.ts
index e2ec6dff51..34bc3feb45 100644
--- a/frontend/src/core/layout/layout.ts
+++ b/frontend/src/core/layout/layout.ts
@@ -4,7 +4,8 @@ import { LayoutType } from "@/components/editor/renderers/types";
import { useAtomValue } from "jotai";
import { createReducerAndAtoms } from "@/utils/createReducer";
import { cellRendererPlugins } from "@/components/editor/renderers/plugins";
-import { getNotebook, notebookCells } from "../cells/cells";
+import { getNotebook } from "../cells/cells";
+import { notebookCells } from "../cells/utils";
import { store } from "../state/jotai";
import { Logger } from "@/utils/Logger";
diff --git a/frontend/src/core/run-app.tsx b/frontend/src/core/run-app.tsx
new file mode 100644
index 0000000000..e973771bea
--- /dev/null
+++ b/frontend/src/core/run-app.tsx
@@ -0,0 +1,48 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { useEffect } from "react";
+
+import { notebookIsRunningAtom, useCellActions } from "./cells/cells";
+import { AppConfig } from "./config/config-schema";
+import { RuntimeState } from "./kernel/RuntimeState";
+import { CellsRenderer } from "../components/editor/renderers/cells-renderer";
+import { useAtomValue } from "jotai";
+import { AppContainer } from "@/components/editor/app-container";
+import { AppHeader } from "@/components/editor/header/app-header";
+import { getSessionId } from "./kernel/session";
+import { useMarimoWebSocket } from "./websocket/useMarimoWebSocket";
+
+interface AppProps {
+ appConfig: AppConfig;
+}
+
+export const RunApp: React.FC<AppProps> = ({ appConfig }) => {
+ const { setCells } = useCellActions();
+
+ // Initialize RuntimeState event-listeners
+ useEffect(() => {
+ RuntimeState.INSTANCE.start();
+ return () => {
+ RuntimeState.INSTANCE.stop();
+ };
+ }, []);
+
+ const { connection } = useMarimoWebSocket({
+ autoInstantiate: true,
+ setCells: setCells,
+ sessionId: getSessionId(),
+ });
+
+ const isRunning = useAtomValue(notebookIsRunningAtom);
+
+ return (
+ <AppContainer
+ connectionState={connection.state}
+ isRunning={isRunning}
+ width={appConfig.width}
+ >
+ <AppHeader connection={connection} className={"sm:pt-8"} />
+ <CellsRenderer appConfig={appConfig} mode="read" />
+ </AppContainer>
+ );
+};
diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsx
index 4cb8afd1ff..cf0f82712c 100644
--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx
+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx
@@ -52,7 +52,7 @@ export function useMarimoWebSocket(opts: {
const setAppConfig = useSetAppConfig();
const { setVariables, setMetadata } = useVariablesActions();
const { setLayoutData } = useLayoutActions();
- const [connStatus, setConnStatus] = useAtom(connectionAtom);
+ const [connection, setConnection] = useAtom(connectionAtom);
const { addBanner } = useBannersActions();
const { addPackageAlert } = useAlertActions();
@@ -182,7 +182,7 @@ export function useMarimoWebSocket(opts: {
onOpen: () => {
// If we are open, we can reset our reconnecting flag.
shouldTryReconnecting.current = true;
- setConnStatus({ state: WebSocketState.OPEN });
+ setConnection({ state: WebSocketState.OPEN });
},
/**
@@ -206,7 +206,7 @@ export function useMarimoWebSocket(opts: {
onClose: (e) => {
switch (e.reason) {
case "MARIMO_ALREADY_CONNECTED":
- setConnStatus({
+ setConnection({
state: WebSocketState.CLOSED,
code: WebSocketClosedReason.ALREADY_RUNNING,
reason: "another browser tab is already connected to the kernel",
@@ -217,7 +217,7 @@ export function useMarimoWebSocket(opts: {
case "MARIMO_WRONG_KERNEL_ID":
case "MARIMO_SHUTDOWN":
Logger.warn("WebSocket closed", e.reason);
- setConnStatus({
+ setConnection({
state: WebSocketState.CLOSED,
code: WebSocketClosedReason.KERNEL_DISCONNECTED,
reason: "kernel not found",
@@ -226,7 +226,7 @@ export function useMarimoWebSocket(opts: {
return;
case "MARIMO_MALFORMED_QUERY":
- setConnStatus({
+ setConnection({
state: WebSocketState.CLOSED,
code: WebSocketClosedReason.MALFORMED_QUERY,
reason:
@@ -240,7 +240,7 @@ export function useMarimoWebSocket(opts: {
// - computer might have just woken from sleep
//
// so try reconnecting.
- setConnStatus({ state: WebSocketState.CONNECTING });
+ setConnection({ state: WebSocketState.CONNECTING });
tryReconnecting(e.code, e.reason);
}
},
@@ -250,7 +250,7 @@ export function useMarimoWebSocket(opts: {
*/
onError: (e) => {
Logger.warn("WebSocket error", e);
- setConnStatus({
+ setConnection({
state: WebSocketState.CLOSED,
code: WebSocketClosedReason.KERNEL_DISCONNECTED,
reason: "kernel not found",
@@ -259,5 +259,5 @@ export function useMarimoWebSocket(opts: {
},
});
- return { connStatus };
+ return { connection };
}
diff --git a/frontend/src/css/app/Cell.css b/frontend/src/css/app/Cell.css
index 779d6d0294..79eecf97fd 100644
--- a/frontend/src/css/app/Cell.css
+++ b/frontend/src/css/app/Cell.css
@@ -304,7 +304,7 @@
}
.cm-editor {
- font-size: var(--marimo-code-editor-font-size);
+ font-size: var(--marimo-code-editor-font-size, 0.9rem);
}
/* .Cell is needed to take precedence over codemirror's generated class ... */
@@ -337,7 +337,7 @@
}
.cm-content {
- font-size: var(--marimo-code-editor-font-size);
+ font-size: var(--marimo-code-editor-font-size, 0.9rem);
font-family: var(--monospace-font);
}
}
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 912ca4a135..3e6fe10c48 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -10,8 +10,10 @@ import { maybeRegisterVSCodeBindings } from "./core/vscode/vscode-bindings";
import { patchFetch, patchVegaLoader } from "./core/static/files";
import { isStaticNotebook } from "./core/static/static-state";
import { vegaLoader } from "./plugins/impl/vega/loader";
+import { initializePlugins } from "./plugins/plugins";
maybeRegisterVSCodeBindings();
+initializePlugins();
/**
* Main entry point for the Marimo app.
diff --git a/frontend/src/plugins/layout/CarouselPlugin.tsx b/frontend/src/plugins/layout/carousel/CarouselComponent.tsx
similarity index 75%
rename from frontend/src/plugins/layout/CarouselPlugin.tsx
rename to frontend/src/plugins/layout/carousel/CarouselComponent.tsx
index 9e5f6e64bb..84b5db3e37 100644
--- a/frontend/src/plugins/layout/CarouselPlugin.tsx
+++ b/frontend/src/plugins/layout/carousel/CarouselComponent.tsx
@@ -1,7 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
+
+import "./carousel.css";
+
import React, { PropsWithChildren, useEffect } from "react";
-import { z } from "zod";
-import { IStatelessPlugin, IStatelessPluginProps } from "../stateless-plugin";
import { Swiper, SwiperSlide, SwiperRef } from "swiper/react";
import {
Virtual,
@@ -14,45 +15,10 @@ import { Button } from "@/components/ui/button";
import { cn } from "@/utils/cn";
import { useEventListener } from "@/hooks/useEventListener";
-import "./carousel.css";
-import swiperCss from "swiper/css?inline";
-import swiperCssVirtual from "swiper/css/virtual?inline";
-import swiperCssKeyboard from "swiper/css/keyboard?inline";
-import swiperCssNavigation from "swiper/css/navigation?inline";
-import swiperCssPagination from "swiper/css/pagination?inline";
-import swiperCssScrollbar from "swiper/css/scrollbar?inline";
-
-interface Data {
+interface CarouselComponentProps {
index?: string | null;
height?: string | number | null;
}
-
-export class CarouselPlugin implements IStatelessPlugin<Data> {
- tagName = "marimo-carousel";
-
- validator = z.object({
- index: z.string().nullish(),
- height: z.union([z.string(), z.number()]).nullish(),
- });
-
- cssStyles = [
- swiperCss,
- swiperCssVirtual,
- swiperCssKeyboard,
- swiperCssNavigation,
- swiperCssPagination,
- swiperCssScrollbar,
- ];
-
- render(props: IStatelessPluginProps<Data>): JSX.Element {
- return (
- <CarouselComponent {...props.data}>{props.children}</CarouselComponent>
- );
- }
-}
-
-type CarouselComponentProps = Data;
-
const CarouselComponent = ({
children,
height,
@@ -148,3 +114,5 @@ const CarouselComponent = ({
</Swiper>
);
};
+
+export default CarouselComponent;
diff --git a/frontend/src/plugins/layout/carousel/CarouselPlugin.tsx b/frontend/src/plugins/layout/carousel/CarouselPlugin.tsx
new file mode 100644
index 0000000000..a6242b0cbe
--- /dev/null
+++ b/frontend/src/plugins/layout/carousel/CarouselPlugin.tsx
@@ -0,0 +1,48 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { z } from "zod";
+import {
+ IStatelessPlugin,
+ IStatelessPluginProps,
+} from "../../stateless-plugin";
+
+import swiperCss from "swiper/css?inline";
+import swiperCssVirtual from "swiper/css/virtual?inline";
+import swiperCssKeyboard from "swiper/css/keyboard?inline";
+import swiperCssNavigation from "swiper/css/navigation?inline";
+import swiperCssPagination from "swiper/css/pagination?inline";
+import swiperCssScrollbar from "swiper/css/scrollbar?inline";
+import React from "react";
+
+interface Data {
+ index?: string | null;
+ height?: string | number | null;
+}
+
+export class CarouselPlugin implements IStatelessPlugin<Data> {
+ tagName = "marimo-carousel";
+
+ validator = z.object({
+ index: z.string().nullish(),
+ height: z.union([z.string(), z.number()]).nullish(),
+ });
+
+ // TODO: Move async when we support async css
+ cssStyles = [
+ swiperCss,
+ swiperCssVirtual,
+ swiperCssKeyboard,
+ swiperCssNavigation,
+ swiperCssPagination,
+ swiperCssScrollbar,
+ ];
+
+ render(props: IStatelessPluginProps<Data>): JSX.Element {
+ return (
+ <LazyCarouselComponent {...props.data}>
+ {props.children}
+ </LazyCarouselComponent>
+ );
+ }
+}
+
+const LazyCarouselComponent = React.lazy(() => import("./CarouselComponent"));
diff --git a/frontend/src/plugins/layout/carousel.css b/frontend/src/plugins/layout/carousel/carousel.css
similarity index 100%
rename from frontend/src/plugins/layout/carousel.css
rename to frontend/src/plugins/layout/carousel/carousel.css
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index e3d0562a8a..38823f4210 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -25,7 +25,7 @@ import { AccordionPlugin } from "./layout/AccordionPlugin";
import { CalloutPlugin } from "./layout/CalloutPlugin";
import { JsonOutputPlugin } from "./layout/JsonOutputPlugin";
import { TabsPlugin } from "./impl/TabsPlugin";
-import { CarouselPlugin } from "./layout/CarouselPlugin";
+import { CarouselPlugin } from "./layout/carousel/CarouselPlugin";
import { TexPlugin } from "./layout/TexPlugin";
import { RefreshPlugin } from "./impl/RefreshPlugin";
import { MicrophonePlugin } from "./impl/MicrophonePlugin";