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: simplify focus and delay on start (#5359)

Myles Scolnick725625d17b72
diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsx
index 264b374709..6861308980 100644
--- a/frontend/src/components/editor/renderers/CellArray.tsx
+++ b/frontend/src/components/editor/renderers/CellArray.tsx
@@ -51,7 +51,7 @@ import { useChromeActions } from "../chrome/state";
import { Column } from "../columns/cell-column";
import { NotebookBanner } from "../notebook-banner";
import { StdinBlockingAlert } from "../stdin-blocking-alert";
-import { useDelayVisibility } from "./vertical-layout/useDelayVisibility";
+import { useFocusFirstEditor } from "./vertical-layout/useFocusFirstEditor";
import { VerticalLayoutWrapper } from "./vertical-layout/vertical-layout-wrapper";
interface CellArrayProps {
@@ -88,7 +88,9 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({
const actions = useCellActions();
const { theme } = useTheme();
const { toggleSidebarPanel } = useChromeActions();
- const { invisible } = useDelayVisibility(notebook.cellIds.idLength, mode);
+
+ // Side-effects
+ useFocusFirstEditor();
// HOTKEYS
useHotkey("global.focusTop", actions.focusTopCell);
@@ -122,7 +124,7 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({
<VerticalLayoutWrapper
// 'pb' allows the user to put the cell in the middle of the screen
className="pb-[40vh]"
- invisible={invisible}
+ invisible={false}
appConfig={appConfig}
innerClassName="pr-4" // For the floating actions
>
@@ -150,7 +152,6 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({
actions={actions}
theme={theme}
hasOnlyOneCell={hasOnlyOneCell}
- invisible={invisible}
hasSetupCell={hasSetupCell}
onDeleteCell={onDeleteCell}
/>
@@ -176,7 +177,6 @@ const CellColumn: React.FC<{
actions: CellActions;
theme: Theme;
hasOnlyOneCell: boolean;
- invisible: boolean;
hasSetupCell: boolean;
onDeleteCell: (payload: { cellId: CellId }) => void;
}> = ({
@@ -191,7 +191,6 @@ const CellColumn: React.FC<{
actions,
theme,
hasOnlyOneCell,
- invisible,
hasSetupCell,
onDeleteCell,
}) => {
diff --git a/frontend/src/components/editor/renderers/vertical-layout/__tests__/useDelayVisibility.test.ts b/frontend/src/components/editor/renderers/vertical-layout/__tests__/useDelayVisibility.test.ts
index 01f83971f5..18559bcad2 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/__tests__/useDelayVisibility.test.ts
+++ b/frontend/src/components/editor/renderers/vertical-layout/__tests__/useDelayVisibility.test.ts
@@ -2,7 +2,6 @@
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import * as cellsModule from "@/core/cells/cells";
import { useDelayVisibility } from "../useDelayVisibility";
describe("useDelayVisibility", () => {
@@ -19,100 +18,70 @@ describe("useDelayVisibility", () => {
});
it("should start with invisible state", () => {
- const { result } = renderHook(() => useDelayVisibility(5, "edit"));
+ const { result } = renderHook(() => useDelayVisibility(5, "read"));
expect(result.current.invisible).toBe(true);
});
- it("should become visible after delay", () => {
- const { result } = renderHook(() => useDelayVisibility(5, "edit"));
+ it("should become visible after delay in read mode", () => {
+ const { result } = renderHook(() => useDelayVisibility(5, "read"));
expect(result.current.invisible).toBe(true);
- // Advance timers by the calculated delay (5-1)*15 = 60ms
+ // Advance timers by the calculated delay (5-1)*30 = 120ms
act(() => {
- vi.advanceTimersByTime(60);
+ vi.advanceTimersByTime(120);
});
expect(result.current.invisible).toBe(false);
});
- it("should cap delay at 100ms for large number of cells", () => {
- const { result } = renderHook(() => useDelayVisibility(20, "edit"));
+ it("should clamp delay at minimum 100ms for small number of cells", () => {
+ const { result } = renderHook(() => useDelayVisibility(2, "read"));
expect(result.current.invisible).toBe(true);
- // Advance timers by 99ms (not enough)
+ // Advance timers by 99ms (not enough, minimum is 100ms)
act(() => {
vi.advanceTimersByTime(99);
});
expect(result.current.invisible).toBe(true);
- // Advance remaining 1ms to reach 100ms cap
+ // Advance remaining 1ms to reach 100ms minimum
act(() => {
vi.advanceTimersByTime(1);
});
expect(result.current.invisible).toBe(false);
});
- it("should not focus any cell in read mode", () => {
- const focusSpy = vi.spyOn(cellsModule, "getNotebook");
+ it("should clamp delay at maximum 2000ms for large number of cells", () => {
+ const { result } = renderHook(() => useDelayVisibility(100, "read"));
- renderHook(() => useDelayVisibility(5, "read"));
+ expect(result.current.invisible).toBe(true);
+ // Advance timers by 1999ms (not enough)
act(() => {
- vi.advanceTimersByTime(100);
+ vi.advanceTimersByTime(1999);
});
+ expect(result.current.invisible).toBe(true);
- expect(focusSpy).not.toHaveBeenCalled();
- });
-
- it("should focus cell from URL if scrollTo parameter exists", () => {
- // Mock location.hash
- const originalHash = window.location.hash;
- Object.defineProperty(window, "location", {
- value: { hash: "#scrollTo=testCell" },
- writable: true,
+ // Advance remaining 1ms to reach 2000ms cap
+ act(() => {
+ vi.advanceTimersByTime(1);
});
+ expect(result.current.invisible).toBe(false);
+ });
- // Mock document.querySelector
- const mockElement = document.createElement("div");
- mockElement.scrollIntoView = vi.fn();
- mockElement.focus = vi.fn();
- mockElement.dataset.cellId = "cell-123";
-
- const querySelectorSpy = vi
- .spyOn(document, "querySelector")
- .mockReturnValue(mockElement as unknown as HTMLElement);
-
- // Mock getNotebook
- const mockEditor = { focus: vi.fn() };
- vi.spyOn(cellsModule, "getNotebook").mockReturnValue({
- cellIds: { iterateTopLevelIds: [] },
- cellData: {},
- cellHandles: {
- "cell-123": { current: { editorView: mockEditor } },
- },
- } as unknown as cellsModule.NotebookState);
+ it("should not apply delay in edit mode", () => {
+ const { result } = renderHook(() => useDelayVisibility(5, "edit"));
- renderHook(() => useDelayVisibility(5, "edit"));
+ // In edit mode, the delay should not be applied, so it should immediately be visible
+ expect(result.current.invisible).toBe(false);
+ });
- act(() => {
- vi.advanceTimersByTime(100);
- });
+ it("should not apply delay in present mode", () => {
+ const { result } = renderHook(() => useDelayVisibility(5, "present"));
- expect(querySelectorSpy).toHaveBeenCalledWith(
- '[data-cell-name="testCell"]',
- );
- // eslint-disable-next-line @typescript-eslint/unbound-method
- expect(mockElement.scrollIntoView).toHaveBeenCalled();
- // eslint-disable-next-line @typescript-eslint/unbound-method
- expect(mockElement.focus).toHaveBeenCalled();
- expect(mockEditor.focus).toHaveBeenCalled();
-
- // Restore original hash
- Object.defineProperty(window, "location", {
- value: { hash: originalHash },
- writable: true,
- });
+ // In present mode, the delay should not be applied
+ expect(result.current.invisible).toBe(false);
});
});
diff --git a/frontend/src/components/editor/renderers/vertical-layout/__tests__/useFocusFirstEditor.test.ts b/frontend/src/components/editor/renderers/vertical-layout/__tests__/useFocusFirstEditor.test.ts
new file mode 100644
index 0000000000..81d8715e1a
--- /dev/null
+++ b/frontend/src/components/editor/renderers/vertical-layout/__tests__/useFocusFirstEditor.test.ts
@@ -0,0 +1,123 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import * as cellsModule from "@/core/cells/cells";
+import { useFocusFirstEditor } from "../useFocusFirstEditor";
+
+describe("useFocusFirstEditor", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
+ cb(0);
+ return 0;
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("should focus the first non-hidden cell after delay", () => {
+ const mockEditor = { focus: vi.fn() };
+ const getNotebookSpy = vi
+ .spyOn(cellsModule, "getNotebook")
+ .mockReturnValue({
+ cellIds: { iterateTopLevelIds: ["cell-1", "cell-2"] },
+ cellData: {
+ "cell-1": { config: { hide_code: false } },
+ "cell-2": { config: { hide_code: false } },
+ },
+ cellHandles: {
+ "cell-1": { current: { editorView: mockEditor } },
+ "cell-2": { current: { editorView: mockEditor } },
+ },
+ } as unknown as cellsModule.NotebookState);
+
+ renderHook(() => useFocusFirstEditor());
+
+ // Advance timers by the delay (100ms)
+ act(() => {
+ vi.advanceTimersByTime(100);
+ });
+
+ expect(getNotebookSpy).toHaveBeenCalled();
+ expect(mockEditor.focus).toHaveBeenCalled();
+ });
+
+ it("should skip hidden cells when focusing", () => {
+ const mockEditor = { focus: vi.fn() };
+ const getNotebookSpy = vi
+ .spyOn(cellsModule, "getNotebook")
+ .mockReturnValue({
+ cellIds: { iterateTopLevelIds: ["cell-1", "cell-2"] },
+ cellData: {
+ "cell-1": { config: { hide_code: true } }, // hidden
+ "cell-2": { config: { hide_code: false } }, // visible
+ },
+ cellHandles: {
+ "cell-1": { current: { editorView: mockEditor } },
+ "cell-2": { current: { editorView: mockEditor } },
+ },
+ } as unknown as cellsModule.NotebookState);
+
+ renderHook(() => useFocusFirstEditor());
+
+ act(() => {
+ vi.advanceTimersByTime(100);
+ });
+
+ expect(getNotebookSpy).toHaveBeenCalled();
+ expect(mockEditor.focus).toHaveBeenCalled();
+ });
+
+ it("should focus cell from URL if scrollTo parameter exists", () => {
+ // Mock location.hash
+ const originalHash = window.location.hash;
+ Object.defineProperty(window, "location", {
+ value: { hash: "#scrollTo=testCell" },
+ writable: true,
+ });
+
+ // Mock document.querySelector
+ const mockElement = document.createElement("div");
+ mockElement.scrollIntoView = vi.fn();
+ mockElement.focus = vi.fn();
+ mockElement.dataset.cellId = "cell-123";
+
+ const querySelectorSpy = vi
+ .spyOn(document, "querySelector")
+ .mockReturnValue(mockElement as unknown as HTMLElement);
+
+ // Mock getNotebook
+ const mockEditor = { focus: vi.fn() };
+ vi.spyOn(cellsModule, "getNotebook").mockReturnValue({
+ cellIds: { iterateTopLevelIds: [] },
+ cellData: {},
+ cellHandles: {
+ "cell-123": { current: { editorView: mockEditor } },
+ },
+ } as unknown as cellsModule.NotebookState);
+
+ renderHook(() => useFocusFirstEditor());
+
+ act(() => {
+ vi.advanceTimersByTime(100);
+ });
+
+ expect(querySelectorSpy).toHaveBeenCalledWith(
+ '[data-cell-name="testCell"]',
+ );
+ // eslint-disable-next-line @typescript-eslint/unbound-method
+ expect(mockElement.scrollIntoView).toHaveBeenCalled();
+ // eslint-disable-next-line @typescript-eslint/unbound-method
+ expect(mockElement.focus).toHaveBeenCalled();
+ expect(mockEditor.focus).toHaveBeenCalled();
+
+ // Restore original hash
+ Object.defineProperty(window, "location", {
+ value: { hash: originalHash },
+ writable: true,
+ });
+ });
+});
diff --git a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
index 48e88c3c5a..dd3278597d 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
+++ b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts
@@ -1,42 +1,28 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { useState } from "react";
-import { getNotebook } from "@/core/cells/cells";
-import type { CellId } from "@/core/cells/ids";
import type { AppMode } from "@/core/mode";
import { useOnMount } from "@/hooks/useLifecycle";
-import { extractCellNameFromHash } from "@/utils/cell-urls";
-import { Logger } from "@/utils/Logger";
+import { clamp } from "@/utils/math";
+
+const DELAY_PER_CELL = 30; // ms
export function useDelayVisibility(numCells: number, mode: AppMode) {
// Start the app as invisible and delay proportional to the number of cells,
// to avoid most of the flickering when the app is loaded (b/c it is
- // streamed). Delaying also helps prevent cell editors from stealing focus.
+ // streamed).
const [invisible, setInvisible] = useState(true);
useOnMount(() => {
- const delay = Math.max(Math.min((numCells - 1) * 15, 100), 0);
- const timeout = setTimeout(() => {
+ // Only do this on read mode
+ if (mode !== "read") {
setInvisible(false);
- // After 1 frame, either focus on the cell from URL or the first cell
- if (mode !== "read") {
- requestAnimationFrame(() => {
- // Check if the URL contains a scrollTo parameter
- const hash = window.location.hash;
- const cellName = extractCellNameFromHash(hash);
+ return;
+ }
- if (cellName) {
- // If we have a scrollTo parameter, focus on that cell
- focusCellByName(cellName);
- } else {
- // Otherwise focus on the first cell
- try {
- focusFirstEditor();
- } catch (error) {
- Logger.warn("Error focusing first editor", error);
- }
- }
- });
- }
+ // linear with cells, at min 100ms and at most 2s
+ const delay = clamp((numCells - 1) * DELAY_PER_CELL, 100, 2000);
+ const timeout = setTimeout(() => {
+ setInvisible(false);
}, delay);
return () => clearTimeout(timeout);
// Delay only when app is first loaded
@@ -44,66 +30,3 @@ export function useDelayVisibility(numCells: number, mode: AppMode) {
return { invisible };
}
-
-function focusFirstEditor() {
- const { cellIds, cellData, cellHandles } = getNotebook();
- // Focus on the first cell if it's been mounted and is not hidden
- for (const cellId of cellIds.iterateTopLevelIds) {
- const handle = cellHandles[cellId];
- const hidden = cellData[cellId].config.hide_code;
- if (!hidden && handle?.current?.editorView) {
- handle.current.editorView.focus();
- return;
- }
- }
-}
-
-let hasScrolledToCell = false;
-
-/**
- * Focus the cell with the given name
- */
-function focusCellByName(cellName: string) {
- // Only do this once per page load
- if (hasScrolledToCell) {
- return;
- }
-
- // Find the cell div with data-cell-name attribute matching the cellName
- const cellElement = document.querySelector(`[data-cell-name="${cellName}"]`);
-
- if (cellElement) {
- // Scroll the element into view
- cellElement.scrollIntoView({
- behavior: "smooth",
- block: "start",
- });
-
- hasScrolledToCell = true;
-
- // Try to focus the cell
- if (cellElement instanceof HTMLElement) {
- cellElement.focus();
-
- // Look for an editor to focus
- const { cellHandles } = getNotebook();
- const cellId = cellElement.dataset.cellId as CellId | undefined;
-
- if (!cellId) {
- Logger.error(`Missing cellId for cell with name ${cellName}`);
- return;
- }
-
- const editor = cellHandles[cellId]?.current?.editorView;
- if (editor) {
- editor.focus();
- }
- }
- } else {
- Logger.warn(
- `Cannot focus cell with name ${cellName} because it was not found`,
- );
- // Fall back to focusing the first editor if cell not found
- focusFirstEditor();
- }
-}
diff --git a/frontend/src/components/editor/renderers/vertical-layout/useFocusFirstEditor.ts b/frontend/src/components/editor/renderers/vertical-layout/useFocusFirstEditor.ts
new file mode 100644
index 0000000000..01301bd11e
--- /dev/null
+++ b/frontend/src/components/editor/renderers/vertical-layout/useFocusFirstEditor.ts
@@ -0,0 +1,107 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import { getNotebook } from "@/core/cells/cells";
+import type { CellId } from "@/core/cells/ids";
+import { useOnMount } from "@/hooks/useLifecycle";
+import { extractCellNameFromHash } from "@/utils/cell-urls";
+import { Logger } from "@/utils/Logger";
+
+/**
+ * Focus the first editor.
+ *
+ * If the URL contains a /#scrollTo= hash, focus on that cell.
+ * Otherwise, focus on the first non-hidden cell.
+ */
+export function useFocusFirstEditor() {
+ useOnMount(() => {
+ const delay = 100; // ms just so its not immediate
+
+ const timeout = setTimeout(() => {
+ // Let the DOM render
+ requestAnimationFrame(() => {
+ // Check if the URL contains a scrollTo parameter
+ const hash = window.location.hash;
+ const cellName = extractCellNameFromHash(hash);
+
+ if (cellName) {
+ // If we have a scrollTo parameter, focus on that cell
+ focusCellByName(cellName);
+ } else {
+ // Otherwise focus on the first cell
+ try {
+ focusFirstEditor();
+ } catch (error) {
+ Logger.warn("Error focusing first editor", error);
+ }
+ }
+ });
+ }, delay);
+
+ return () => clearTimeout(timeout);
+ // Delay only when app is first loaded
+ });
+}
+
+function focusFirstEditor() {
+ const { cellIds, cellData, cellHandles } = getNotebook();
+
+ // Focus on the first cell if it's been mounted and is not hidden
+ for (const cellId of cellIds.iterateTopLevelIds) {
+ const handle = cellHandles[cellId];
+ const hidden = cellData[cellId]?.config.hide_code;
+ if (!hidden && handle?.current?.editorView) {
+ handle.current.editorView.focus();
+ return;
+ }
+ }
+}
+
+let hasScrolledToCell = false;
+
+/**
+ * Focus the cell with the given name
+ */
+function focusCellByName(cellName: string) {
+ // Only do this once per page load
+ if (hasScrolledToCell) {
+ return;
+ }
+
+ // Find the cell div with data-cell-name attribute matching the cellName
+ const cellElement = document.querySelector(`[data-cell-name="${cellName}"]`);
+
+ if (cellElement) {
+ // Scroll the element into view
+ cellElement.scrollIntoView({
+ behavior: "smooth",
+ block: "start",
+ });
+
+ hasScrolledToCell = true;
+
+ // Try to focus the cell
+ if (cellElement instanceof HTMLElement) {
+ cellElement.focus();
+
+ // Look for an editor to focus
+ const { cellHandles } = getNotebook();
+ const cellId = cellElement.dataset.cellId as CellId | undefined;
+
+ if (!cellId) {
+ Logger.error(`Missing cellId for cell with name ${cellName}`);
+ return;
+ }
+
+ const editor = cellHandles[cellId]?.current?.editorView;
+ if (editor) {
+ editor.focus();
+ }
+ }
+ } else {
+ Logger.warn(
+ `Cannot focus cell with name ${cellName} because it was not found`,
+ );
+ // Fall back to focusing the first editor if cell not found
+ focusFirstEditor();
+ }
+}
diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
index d8ffb556f5..916940a7ae 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
@@ -129,7 +129,7 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({
);
}
- if (cells.length === 0) {
+ if (cells.length === 0 && !invisible) {
return (
<div className="flex-1 flex flex-col items-center justify-center py-8">
<Alert variant="info">
diff --git a/frontend/src/core/run-app.tsx b/frontend/src/core/run-app.tsx
index d1ba370eaa..10709b55cd 100644
--- a/frontend/src/core/run-app.tsx
+++ b/frontend/src/core/run-app.tsx
@@ -4,12 +4,15 @@ import { useAtomValue } from "jotai";
import { useEffect } from "react";
import { AppContainer } from "@/components/editor/app-container";
import { AppHeader } from "@/components/editor/header/app-header";
+import { Spinner } from "@/components/icons/spinner";
+import { DelayMount } from "@/components/utils/delay-mount";
import { CellsRenderer } from "../components/editor/renderers/cells-renderer";
import { notebookIsRunningAtom, useCellActions } from "./cells/cells";
import type { AppConfig } from "./config/config-schema";
import { RuntimeState } from "./kernel/RuntimeState";
import { getSessionId } from "./kernel/session";
import { sendComponentValues } from "./network/requests";
+import { isAppConnecting } from "./websocket/connection-utils";
import { useMarimoWebSocket } from "./websocket/useMarimoWebSocket";
interface AppProps {
@@ -34,6 +37,23 @@ export const RunApp: React.FC<AppProps> = ({ appConfig }) => {
});
const isRunning = useAtomValue(notebookIsRunningAtom);
+ const isConnecting = isAppConnecting(connection.state);
+
+ const renderCells = () => {
+ // If we are connecting for more than 2 seconds, show a spinner
+ if (isConnecting) {
+ return (
+ <DelayMount milliseconds={2000} fallback={null}>
+ <Spinner className="mx-auto" />
+ <p className="text-center text-sm text-muted-foreground mt-2">
+ Connecting...
+ </p>
+ </DelayMount>
+ );
+ }
+
+ return <CellsRenderer appConfig={appConfig} mode="read" />;
+ };
return (
<AppContainer
@@ -42,7 +62,7 @@ export const RunApp: React.FC<AppProps> = ({ appConfig }) => {
width={appConfig.width}
>
<AppHeader connection={connection} className={"sm:pt-8"} />
- <CellsRenderer appConfig={appConfig} mode="read" />
+ {renderCells()}
</AppContainer>
);
};