A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: start markdown cells with hidden code (#5627)
Myles Scolnickb0eee6eb023f
diff --git a/frontend/src/__mocks__/notebook.ts b/frontend/src/__mocks__/notebook.tsindex 73132ab427..fe1e7b1e5f 100644--- a/frontend/src/__mocks__/notebook.ts+++ b/frontend/src/__mocks__/notebook.ts@@ -38,6 +38,7 @@ export const MockNotebook = {cellLogs: [],history: [],scrollKey: null,+ untouchedNewCells: new Set(),};},diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex f3c230c513..a0a2d2930a 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -2,7 +2,7 @@import { closeCompletion, completionStatus } from "@codemirror/autocomplete";import type { EditorView } from "@codemirror/view";import clsx from "clsx";-import { useAtom, useSetAtom } from "jotai";+import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";import { ScopeProvider } from "jotai-scope";import {HelpCircleIcon,@@ -16,6 +16,7 @@ import {memo,useCallback,useImperativeHandle,+ useMemo,useRef,useState,} from "react";@@ -38,7 +39,11 @@ import { useHotkeysOnElement } from "@/hooks/useHotkey";import { useResizeObserver } from "@/hooks/useResizeObserver";import { cn } from "@/utils/cn";import type { Milliseconds, Seconds } from "@/utils/time";-import { type CellActions, SETUP_CELL_ID } from "../../core/cells/cells";+import {+ type CellActions,+ createUntouchedCellAtom,+ SETUP_CELL_ID,+} from "../../core/cells/cells";import type { CellId } from "../../core/cells/ids";import type { CellData, CellRuntimeState } from "../../core/cells/types";import { isUninstantiated } from "../../core/cells/utils";@@ -69,7 +74,7 @@ import { useRunCell } from "./cell/useRunCells";import { HideCodeButton } from "./code/readonly-python-code";import { cellDomProps } from "./common";import { useCellNavigationProps } from "./focus/focus";-import { useCellFocusManager } from "./focus/focus-manager";+import { focusCell, focusCellEditor } from "./focus/focus-manager";import { temporarilyShownCodeAtom } from "./focus/state";import { OutputArea } from "./Output";import { ConsoleOutput } from "./output/ConsoleOutput";@@ -155,8 +160,7 @@ function useCellHotkeys({>;cellActionDropdownRef: React.RefObject<CellActionsDropdownHandle | null>;}) {- const focusManager = useCellFocusManager();-+ const store = useStore();useHotkeysOnElement(cellRef, {"cell.run": runCell,"cell.runAndNewBelow": () => {@@ -182,12 +186,13 @@ function useCellHotkeys({configs: { [cellId]: { hide_code: nextHideCode } },});actions.updateCellConfig({ cellId, config: { hide_code: nextHideCode } });+ actions.focusCell({ cellId, before: false });if (nextHideCode) {// Move focus from the editor to the celleditorView.current?.contentDOM.blur();- focusManager.focusCell(cellId);+ focusCell(cellId);} else {- focusManager.focusCellEditor(cellId);+ focusCellEditor(store, cellId);}},"cell.focusDown": () =>@@ -217,13 +222,20 @@ function useCellHotkeys({}/**- * Hook for handling hidden cell logic+ * Hook for handling hidden cell logic.+ *+ * The code is shown if:+ * - hide_code is false+ * - the cell-editor is focused (temporarily shown)+ * - the cell is newly created (untouched)*/function useCellHiddenLogic({+ cellId,cellConfig,languageAdapter,editorView,}: {+ cellId: CellId;cellConfig: CellConfig;languageAdapter: LanguageAdapterType | undefined;editorView: React.RefObject<EditorView | null>;@@ -232,9 +244,13 @@ function useCellHiddenLogic({const [temporarilyVisible, setTemporarilyVisible] = useAtom(temporarilyShownCodeAtom,);+ const isUntouched = useAtomValue(+ useMemo(() => createUntouchedCellAtom(cellId), [cellId]),+ );// The cell code is shown if the cell is not configured to be hidden or if the code is temporarily visible (i.e. when focused).- const isCellCodeShown = !cellConfig.hide_code || temporarilyVisible;+ const isCellCodeShown =+ !cellConfig.hide_code || temporarilyVisible || isUntouched;const isMarkdown = languageAdapter === "markdown";const isMarkdownCodeHidden = isMarkdown && !isCellCodeShown;@@ -567,6 +583,7 @@ const EditableCellComponent = ({showHiddenCode,showHiddenCodeIfMarkdown,} = useCellHiddenLogic({+ cellId,cellConfig,languageAdapter,editorView,@@ -943,11 +960,13 @@ const CellLeftSideActions = (props: {}) => {const { className, connectionState, actions, cellId } = props;- const createBelow = useEvent((opts: { code?: string } = {}) =>- actions.createNewCell({ cellId, before: false, ...opts }),+ const createBelow = useEvent(+ (opts: { code?: string; hideCode?: boolean } = {}) =>+ actions.createNewCell({ cellId, before: false, ...opts }),);- const createAbove = useEvent((opts: { code?: string } = {}) =>- actions.createNewCell({ cellId, before: true, ...opts }),+ const createAbove = useEvent(+ (opts: { code?: string; hideCode?: boolean } = {}) =>+ actions.createNewCell({ cellId, before: true, ...opts }),);const isConnected = isAppConnected(connectionState);diff --git a/frontend/src/components/editor/cell/CreateCellButton.tsx b/frontend/src/components/editor/cell/CreateCellButton.tsxindex c0cbc44768..455dfd5786 100644--- a/frontend/src/components/editor/cell/CreateCellButton.tsx+++ b/frontend/src/components/editor/cell/CreateCellButton.tsx@@ -28,7 +28,7 @@ export const CreateCellButton = ({}: {connectionState: WebSocketState;tooltipContent: React.ReactNode;- onClick: ((opts: { code: string }) => void) | undefined;+ onClick: ((opts: { code: string; hideCode?: boolean }) => void) | undefined;}) => {const baseTooltipContent =getConnectionTooltip(connectionState) || tooltipContent;@@ -66,7 +66,7 @@ export const CreateCellButton = ({};const CreateCellButtonContextMenu = (props: {- onClick: ((opts: { code: string }) => void) | undefined;+ onClick: ((opts: { code: string; hideCode?: boolean }) => void) | undefined;children: React.ReactNode;}) => {const { children, onClick } = props;@@ -102,7 +102,10 @@ const CreateCellButtonContextMenu = (props: {onSelect={(evt) => {evt.stopPropagation();maybeAddMarimoImport({ autoInstantiate: true, createNewCell });- onClick({ code: new MarkdownLanguageAdapter().defaultCode });+ onClick({+ code: new MarkdownLanguageAdapter().defaultCode,+ hideCode: true,+ });}}><div className="mr-3 text-muted-foreground">diff --git a/frontend/src/components/editor/focus/__tests__/focus.test.ts b/frontend/src/components/editor/focus/__tests__/focus.test.tsindex adb6233169..63b319321b 100644--- a/frontend/src/components/editor/focus/__tests__/focus.test.ts+++ b/frontend/src/components/editor/focus/__tests__/focus.test.ts@@ -3,12 +3,11 @@import { act, renderHook } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";-import { Mocks, partialImplementation } from "@/__mocks__/common";+import { Mocks } from "@/__mocks__/common";import { MockNotebook } from "@/__mocks__/notebook";import type { CellActions } from "@/core/cells/cells";import type { CellId } from "@/core/cells/ids";import { useCellEditorNavigationProps, useCellNavigationProps } from "../focus";-import type { CellFocusManager } from "../focus-manager";// Mock only the essential dependencies that we need to controlvi.mock("@/core/cells/cells", () => ({@@ -32,7 +31,8 @@ vi.mock("../clipboard", () => ({}));vi.mock("../focus-manager", () => ({- useCellFocusManager: vi.fn(),+ focusCellEditor: vi.fn(),+ focusCell: vi.fn(),}));// Get mocked functions@@ -51,9 +51,8 @@ const mockUseRunCell = vi.mocked(const mockUseCellClipboard = vi.mocked(await import("../clipboard"),).useCellClipboard;-const mockUseCellFocusManager = vi.mocked(- await import("../focus-manager"),-).useCellFocusManager;++import { focusCell, focusCellEditor } from "../focus-manager";describe("useCellNavigationProps", () => {const mockCellId = "test-cell-id" as CellId;@@ -71,10 +70,6 @@ describe("useCellNavigationProps", () => {focusBottomCell: vi.fn(),createNewCell: vi.fn(),});- const mockFocusManager = partialImplementation<CellFocusManager>({- focusCellEditor: vi.fn(),- focusCell: vi.fn(),- });beforeEach(() => {vi.clearAllMocks();@@ -88,7 +83,6 @@ describe("useCellNavigationProps", () => {mockUseCellActions.mockReturnValue(mockCellActions as unknown as CellActions,);- mockUseCellFocusManager.mockReturnValue(mockFocusManager);mockUseRunCell.mockReturnValue(mockRunCell);mockUseCellClipboard.mockReturnValue({copyCell: mockCopyCell,@@ -173,7 +167,10 @@ describe("useCellNavigationProps", () => {}});- expect(mockFocusManager.focusCellEditor).toHaveBeenCalledWith(mockCellId);+ expect(focusCellEditor).toHaveBeenCalledWith(+ expect.anything(),+ mockCellId,+ );expect(mockEvent.preventDefault).toHaveBeenCalled();});@@ -351,14 +348,9 @@ describe("useCellNavigationProps", () => {describe("useCellEditorNavigationProps", () => {const mockCellId = "test-cell-id" as CellId;- const mockFocusManager = partialImplementation<CellFocusManager>({- focusCellEditor: vi.fn(),- focusCell: vi.fn(),- });beforeEach(() => {vi.clearAllMocks();- mockUseCellFocusManager.mockReturnValue(mockFocusManager);});describe("keyboard shortcuts", () => {@@ -375,7 +367,7 @@ describe("useCellEditorNavigationProps", () => {}});- expect(mockFocusManager.focusCell).toHaveBeenCalledWith(mockCellId);+ expect(focusCell).toHaveBeenCalledWith(mockCellId);expect(mockEvent.continuePropagation).not.toHaveBeenCalled();});@@ -392,7 +384,7 @@ describe("useCellEditorNavigationProps", () => {}});- expect(mockFocusManager.focusCell).not.toHaveBeenCalled();+ expect(focusCell).not.toHaveBeenCalled();expect(mockEvent.continuePropagation).not.toHaveBeenCalled();});});diff --git a/frontend/src/components/editor/focus/focus-manager.ts b/frontend/src/components/editor/focus/focus-manager.tsindex ea651bb33e..4e9f7c07e4 100644--- a/frontend/src/components/editor/focus/focus-manager.ts+++ b/frontend/src/components/editor/focus/focus-manager.ts@@ -1,38 +1,32 @@/* Copyright 2024 Marimo. All rights reserved. */-import { type createStore, useStore } from "jotai";+import type { createStore } from "jotai";import { notebookAtom } from "@/core/cells/cells";import { type CellId, HTMLCellId } from "@/core/cells/ids";import { Logger } from "@/utils/Logger";-export class CellFocusManager {- constructor(private readonly store: ReturnType<typeof createStore>) {}-- focusCellEditor(cellId: CellId): void {- const editor =- this.store.get(notebookAtom).cellHandles[cellId]?.current?.editorView;- if (editor) {- editor.focus();- } else {- Logger.warn(- `[CellFocusManager] focusCellEditor: element not found: ${cellId}`,- );- }- }-- focusCell(cellId: CellId): void {- const element = document.getElementById(HTMLCellId.create(cellId));- if (element) {- tryFocus(element);- } else {- Logger.warn(`[CellFocusManager] focusCell: element not found: ${cellId}`);- }+export function focusCellEditor(+ store: ReturnType<typeof createStore>,+ cellId: CellId,+): void {+ const editor =+ store.get(notebookAtom).cellHandles[cellId]?.current?.editorView;+ if (editor) {+ editor.focus();+ } else {+ Logger.warn(+ `[CellFocusManager] focusCellEditor: element not found: ${cellId}`,+ );}}-export function useCellFocusManager() {- const store = useStore();- return new CellFocusManager(store);+export function focusCell(cellId: CellId): void {+ const element = document.getElementById(HTMLCellId.create(cellId));+ if (element) {+ tryFocus(element);+ } else {+ Logger.warn(`[CellFocusManager] focusCell: element not found: ${cellId}`);+ }}/**diff --git a/frontend/src/components/editor/focus/focus.ts b/frontend/src/components/editor/focus/focus.tsindex 2d0e2830cf..facbd25ea3 100644--- a/frontend/src/components/editor/focus/focus.ts+++ b/frontend/src/components/editor/focus/focus.ts@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */-import { useAtomValue, useSetAtom } from "jotai";+import { useAtomValue, useSetAtom, useStore } from "jotai";import { mergeProps, useFocusWithin, useKeyboard } from "react-aria";import { useCellActions } from "@/core/cells/cells";import { useSetLastFocusedCellId } from "@/core/cells/focus";@@ -12,7 +12,7 @@ import { useSaveNotebook } from "@/core/saving/save-component";import { Events } from "@/utils/events";import { useRunCell } from "../cell/useRunCells";import { useCellClipboard } from "./clipboard";-import { useCellFocusManager } from "./focus-manager";+import { focusCell, focusCellEditor } from "./focus-manager";import { temporarilyShownCodeAtom } from "./state";/**@@ -28,8 +28,8 @@ export function useCellNavigationProps(cellId: CellId) {const setLastFocusedCellId = useSetLastFocusedCellId();const { saveOrNameNotebook } = useSaveNotebook();const actions = useCellActions();+ const store = useStore();const setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);- const focusManager = useCellFocusManager();const runCell = useRunCell(cellId);const keymapPreset = useAtomValue(keymapPresetAtom);const { copyCell, pasteCell } = useCellClipboard();@@ -49,6 +49,7 @@ export function useCellNavigationProps(cellId: CellId) {onBlurWithin: () => {// On blur, hide the code if it was temporarily shown.setTemporarilyShownCode(false);+ actions.markTouched({ cellId });},});@@ -107,7 +108,7 @@ export function useCellNavigationProps(cellId: CellId) {// Enter will focus the cell editor.if (evt.key === "Enter") {setTemporarilyShownCode(true);- focusManager.focusCellEditor(cellId);+ focusCellEditor(store, cellId);// Prevent default to prevent an new line from being created.evt.preventDefault();return;@@ -169,13 +170,12 @@ export function useCellNavigationProps(cellId: CellId) {*/export function useCellEditorNavigationProps(cellId: CellId) {const setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);- const focusManager = useCellFocusManager();const { keyboardProps } = useKeyboard({onKeyDown: (evt) => {if (evt.key === "Escape") {setTemporarilyShownCode(false);- focusManager.focusCell(cellId);+ focusCell(cellId);}evt.continuePropagation();diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex dd4dac7fc8..7c7e5a8929 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -333,6 +333,7 @@ const AddCellButtons: React.FC<{cellId: { type: "__end__", columnId },before: false,code: new MarkdownLanguageAdapter().defaultCode,+ hideCode: true,});}}>diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex aa072485e9..b63745e329 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -2253,7 +2253,7 @@ describe("cell reducer", () => {expect(focusSpy).toHaveBeenCalledWith({cellId: cell2Id,cell: state.cellHandles[cell2Id],- config: state.cellData[cell2Id].config,+ isCodeHidden: false,codeFocus: "top",variableName: undefined,});@@ -2268,7 +2268,7 @@ describe("cell reducer", () => {expect(focusSpy).toHaveBeenCalledWith({cellId: cell1Id,cell: state.cellHandles[cell1Id],- config: state.cellData[cell1Id].config,+ isCodeHidden: false,codeFocus: "bottom",variableName: undefined,});@@ -2289,4 +2289,328 @@ describe("cell reducer", () => {expect(state.cellIds.inOrderIds).toEqual(initialState.cellIds.inOrderIds);});});++ describe("untouched cells functionality", () => {+ it("starts with empty untouchedNewCells set", () => {+ expect(state.untouchedNewCells).toEqual(new Set());+ });++ it("can create a new cell with hideCode option", () => {+ const initialCellCount = state.cellIds.inOrderIds.length;++ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: true,+ });++ expect(state.cellIds.inOrderIds.length).toBe(initialCellCount + 1);+ const newCellId =+ state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];+ expect(state.untouchedNewCells.has(newCellId)).toBe(true);+ });++ it("does not add cell to untouchedNewCells when hideCode is false", () => {+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: false,+ });++ const newCellId =+ state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];+ expect(state.untouchedNewCells.has(newCellId)).toBe(false);+ });++ it("does not add cell to untouchedNewCells when hideCode is undefined", () => {+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ });++ const newCellId =+ state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];+ expect(state.untouchedNewCells.has(newCellId)).toBe(false);+ });++ it("can mark a cell as touched", () => {+ // Create a cell with hideCode+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: true,+ });++ const newCellId =+ state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];+ expect(state.untouchedNewCells.has(newCellId)).toBe(true);++ // Mark it as touched+ actions.markTouched({ cellId: newCellId });++ expect(state.untouchedNewCells.has(newCellId)).toBe(false);+ });++ it("markTouched is idempotent", () => {+ // Create a cell with hideCode+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: true,+ });++ const newCellId =+ state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];+ expect(state.untouchedNewCells.has(newCellId)).toBe(true);++ // Mark it as touched multiple times+ actions.markTouched({ cellId: newCellId });+ actions.markTouched({ cellId: newCellId });+ actions.markTouched({ cellId: newCellId });++ expect(state.untouchedNewCells.has(newCellId)).toBe(false);+ });++ it("can mark a non-existent cell as touched without error", () => {+ const nonExistentCellId = "non-existent" as CellId;++ expect(() => {+ actions.markTouched({ cellId: nonExistentCellId });+ }).not.toThrow();++ expect(state.untouchedNewCells.has(nonExistentCellId)).toBe(false);+ });++ it("can handle multiple untouched cells", () => {+ // Create multiple cells with hideCode+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: true,+ });+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: true,+ });+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: false,+ });++ const cellIds = state.cellIds.inOrderIds;+ const cell1Id = cellIds[cellIds.length - 3];+ const cell2Id = cellIds[cellIds.length - 2];+ const cell3Id = cellIds[cellIds.length - 1];++ expect(state.untouchedNewCells.has(cell1Id)).toBe(true);+ expect(state.untouchedNewCells.has(cell2Id)).toBe(true);+ expect(state.untouchedNewCells.has(cell3Id)).toBe(false);++ // Mark one as touched+ actions.markTouched({ cellId: cell1Id });++ expect(state.untouchedNewCells.has(cell1Id)).toBe(false);+ expect(state.untouchedNewCells.has(cell2Id)).toBe(true);+ expect(state.untouchedNewCells.has(cell3Id)).toBe(false);+ });++ it("preserves untouched state when cells are moved", () => {+ // Create cells with hideCode+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: true,+ });+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: true,+ });++ const cellIds = state.cellIds.inOrderIds;+ const cell1Id = cellIds[cellIds.length - 2];+ const cell2Id = cellIds[cellIds.length - 1];++ expect(state.untouchedNewCells.has(cell1Id)).toBe(true);+ expect(state.untouchedNewCells.has(cell2Id)).toBe(true);++ // Move cell1 to the end+ actions.moveCell({+ cellId: cell1Id,+ before: false,+ });++ // Both cells should still be untouched+ expect(state.untouchedNewCells.has(cell1Id)).toBe(true);+ expect(state.untouchedNewCells.has(cell2Id)).toBe(true);+ });++ it("does not remove untouched state when cell is deleted", () => {+ // We could implement this, but it doesn't actually affect downstream behavior.+ // It is easier to leave it, so `undo` works as expected.++ // Create a cell with hideCode+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: true,+ });++ const newCellId =+ state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];+ expect(state.untouchedNewCells.has(newCellId)).toBe(true);++ // Delete the cell+ actions.deleteCell({ cellId: newCellId });++ // Does not actually remove untouched state+ expect(state.untouchedNewCells.has(newCellId)).toBe(true);+ });++ it("restores untouched state when cell deletion is undone", () => {+ // Create a cell with hideCode+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: true,+ });++ const newCellId =+ state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];+ expect(state.untouchedNewCells.has(newCellId)).toBe(true);++ // Delete the cell+ actions.deleteCell({ cellId: newCellId });+ // Still exists in untouchedNewCells+ expect(state.untouchedNewCells.has(newCellId)).toBe(true);++ // Undo the deletion+ actions.undoDeleteCell();++ // The cell should be restored but no longer untouched+ // (this is expected behavior - undoing doesn't restore untouched state)+ const restoredCellId =+ state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];+ expect(state.untouchedNewCells.has(restoredCellId)).toBe(false);+ });++ it("untouched cell behavior with hide_code config", () => {+ // Create a cell with hideCode and hide_code config+ actions.createNewCell({+ cellId: "__end__",+ before: false,+ hideCode: true,+ });++ const newCellId =+ state.cellIds.inOrderIds[state.cellIds.inOrderIds.length - 1];++ // Update the cell config to hide code+ actions.updateCellConfig({+ cellId: newCellId,+ config: { hide_code: true },+ });++ // Cell should be untouched and have hide_code config+ expect(state.untouchedNewCells.has(newCellId)).toBe(true);+ expect(state.cellData[newCellId].config.hide_code).toBe(true);++ // Code should not be hidden because cell is untouched+ expect(exportedForTesting.isCellCodeHidden(state, newCellId)).toBe(false);++ // Mark as touched+ actions.markTouched({ cellId: newCellId });++ // Now code should be hidden+ expect(state.untouchedNewCells.has(newCellId)).toBe(false);+ expect(exportedForTesting.isCellCodeHidden(state, newCellId)).toBe(true);+ });+ });+});++describe("isCellCodeHidden", () => {+ const state = initialNotebookState();+ const firstCellId = state.cellIds.inOrderIds[0];++ it("returns false when hide_code is false and cell is not untouched", () => {+ const testCellId = "test-cell" as CellId;+ const testState: NotebookState = {+ ...state,+ cellData: {+ ...state.cellData,+ [testCellId]: {+ ...state.cellData[firstCellId],+ id: testCellId,+ config: { hide_code: false, disabled: false, column: null },+ },+ },+ untouchedNewCells: new Set(),+ };++ expect(exportedForTesting.isCellCodeHidden(testState, testCellId)).toBe(+ false,+ );+ });++ it("returns true when hide_code is true and cell is not untouched", () => {+ const testCellId = "test-cell" as CellId;+ const testState: NotebookState = {+ ...state,+ cellData: {+ ...state.cellData,+ [testCellId]: {+ ...state.cellData[firstCellId],+ id: testCellId,+ config: { hide_code: true, disabled: false, column: null },+ },+ },+ untouchedNewCells: new Set(),+ };++ expect(exportedForTesting.isCellCodeHidden(testState, testCellId)).toBe(+ true,+ );+ });++ it("returns false when hide_code is true but cell is untouched", () => {+ const testCellId = "test-cell" as CellId;+ const testState: NotebookState = {+ ...state,+ cellData: {+ ...state.cellData,+ [testCellId]: {+ ...state.cellData[firstCellId],+ id: testCellId,+ config: { hide_code: true, disabled: false, column: null },+ },+ },+ untouchedNewCells: new Set([testCellId]),+ };++ expect(exportedForTesting.isCellCodeHidden(testState, testCellId)).toBe(+ false,+ );+ });++ it("returns false when hide_code is false and cell is untouched", () => {+ const testCellId = "test-cell" as CellId;+ const testState: NotebookState = {+ ...state,+ cellData: {+ ...state.cellData,+ [testCellId]: {+ ...state.cellData[firstCellId],+ id: testCellId,+ config: { hide_code: false, disabled: false, column: null },+ },+ },+ untouchedNewCells: new Set([testCellId]),+ };++ expect(exportedForTesting.isCellCodeHidden(testState, testCellId)).toBe(+ false,+ );+ });});diff --git a/frontend/src/core/cells/__tests__/utils.test.ts b/frontend/src/core/cells/__tests__/utils.test.tsindex da923b6bfa..b9e7926495 100644--- a/frontend/src/core/cells/__tests__/utils.test.ts+++ b/frontend/src/core/cells/__tests__/utils.test.ts@@ -1,7 +1,11 @@/* Copyright 2024 Marimo. All rights reserved. *//* eslint-disable @typescript-eslint/no-explicit-any */import { describe, expect, it } from "vitest";-import { getCellConfigs, type NotebookState } from "@/core/cells/cells";+import {+ getCellConfigs,+ initialNotebookState,+ type NotebookState,+} from "@/core/cells/cells";import { CellId } from "@/core/cells/ids";import type { CellData, CellRuntimeState } from "@/core/cells/types";import { MultiColumn } from "@/utils/id-tree";@@ -22,6 +26,7 @@ describe("getCellConfigs", () => {// Create a mock NotebookStateconst mockState: NotebookState = {+ ...initialNotebookState(),cellIds: MultiColumn.from([[cellId1, cellId2],[cellId3, cellId4],@@ -45,10 +50,6 @@ describe("getCellConfigs", () => {} as CellData,},cellRuntime: {} as Record<CellId, CellRuntimeState>,- cellHandles: {},- history: [],- scrollKey: null,- cellLogs: [],};// Call the function@@ -84,6 +85,7 @@ describe("getCellConfigs", () => {it("should handle single column", () => {const cellId1 = CellId.create();const mockState: NotebookState = {+ ...initialNotebookState(),cellIds: MultiColumn.from([[cellId1]]),cellData: {[cellId1]: {@@ -91,11 +93,7 @@ describe("getCellConfigs", () => {config: { hide_code: false, disabled: false },} as CellData,},- cellRuntime: {},- cellHandles: {},- history: [],- scrollKey: null,- cellLogs: [],+ untouchedNewCells: new Set(),};const result = getCellConfigs(mockState);@@ -105,16 +103,7 @@ describe("getCellConfigs", () => {});it("should handle empty notebook state", () => {- const mockState: NotebookState = {- cellIds: MultiColumn.from([]),- cellData: {},- cellRuntime: {},- cellHandles: {},- history: [],- scrollKey: null,- cellLogs: [],- };-+ const mockState: NotebookState = initialNotebookState();const result = getCellConfigs(mockState);expect(result).toEqual([]);@@ -403,17 +392,13 @@ describe("disabledCellIds", () => {const cellId3 = CellId.create();const state: NotebookState = {+ ...initialNotebookState(),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);@@ -428,17 +413,13 @@ describe("enabledCellIds", () => {const cellId3 = CellId.create();const state: NotebookState = {+ ...initialNotebookState(),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);diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex b6fd945989..ecc4ef4b17 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -40,6 +40,7 @@ import {type CellData,type CellRuntimeState,createCell,+ createCellConfig,createCellRuntimeState,} from "./types";import {@@ -101,6 +102,12 @@ export interface NotebookState {* Logs of all cell messages*/cellLogs: CellLog[];+ /**+ * Set of cells that have been created that are initialized with `hide_code`.+ *+ * These start temporarily open until their first blur event.+ */+ untouchedNewCells: Set<CellId>;}function withScratchCell(notebookState: NotebookState): NotebookState {@@ -125,7 +132,7 @@ function withScratchCell(notebookState: NotebookState): NotebookState {/*** Initial state of the notebook.*/-function initialNotebookState(): NotebookState {+export function initialNotebookState(): NotebookState {return withScratchCell({cellIds: MultiColumn.from([]),cellData: {},@@ -134,6 +141,7 @@ function initialNotebookState(): NotebookState {history: [],scrollKey: null,cellLogs: [],+ untouchedNewCells: new Set<CellId>(),});}@@ -169,6 +177,8 @@ const {autoFocus?: boolean;/** If true, skip creation if code already exists */skipIfCodeExists?: boolean;+ /** Hide the code in the new cell. This will be initially shown until the cell is blurred for the first time. */+ hideCode?: boolean;},) => {const {@@ -179,6 +189,7 @@ const {lastExecutionTime = null,autoFocus = true,skipIfCodeExists = false,+ hideCode = false,} = action;let columnId: CellColumnId;@@ -222,6 +233,7 @@ const {id: newCellId,code,lastCodeRun,+ config: createCellConfig({ hide_code: hideCode }),lastExecutionTime,edited: Boolean(code) && code !== lastCodeRun,}),@@ -235,6 +247,9 @@ const {[newCellId]: createRef(),},scrollKey: autoFocus ? newCellId : null,+ untouchedNewCells: hideCode+ ? new Set([...state.untouchedNewCells, newCellId])+ : state.untouchedNewCells,};},moveCell: (@@ -412,7 +427,7 @@ const {focusAndScrollCellIntoView({cellId: focusCellId,cell: state.cellHandles[focusCellId],- config: state.cellData[focusCellId].config,+ isCodeHidden: isCellCodeHidden(state, focusCellId),codeFocus: before ? "bottom" : "top",variableName: undefined,});@@ -429,7 +444,7 @@ const {focusAndScrollCellIntoView({cellId: cellId,cell: state.cellHandles[cellId],- config: state.cellData[cellId].config,+ isCodeHidden: isCellCodeHidden(state, cellId),codeFocus: undefined,variableName: undefined,});@@ -447,7 +462,7 @@ const {focusAndScrollCellIntoView({cellId: cellId,cell: state.cellHandles[cellId],- config: state.cellData[cellId].config,+ isCodeHidden: isCellCodeHidden(state, cellId),codeFocus: undefined,variableName: undefined,});@@ -986,7 +1001,7 @@ const {focusAndScrollCellIntoView({cellId: nextCellId,cell: state.cellHandles[nextCellId],- config: state.cellData[nextCellId].config,+ isCodeHidden: isCellCodeHidden(state, nextCellId),codeFocus: before ? "bottom" : "top",variableName: undefined,});@@ -994,6 +1009,20 @@ const {return state;},+ markTouched: (state, action: { cellId: CellId }) => {+ const { cellId } = action;++ if (state.untouchedNewCells.has(cellId)) {+ const nextUntouchedNewCells = new Set(state.untouchedNewCells);+ nextUntouchedNewCells.delete(cellId);+ return {+ ...state,+ untouchedNewCells: nextUntouchedNewCells,+ };+ }++ return state;+ },scrollToTarget: (state) => {// Scroll to the specified cell and clear the scroll key.const scrollKey = state.scrollKey;@@ -1010,7 +1039,7 @@ const {focusAndScrollCellIntoView({cellId: cellId,cell: state.cellHandles[cellId],- config: state.cellData[cellId].config,+ isCodeHidden: isCellCodeHidden(state, cellId),codeFocus: undefined,variableName: undefined,});@@ -1330,6 +1359,13 @@ const {},});+function isCellCodeHidden(state: NotebookState, cellId: CellId): boolean {+ return (+ state.cellData[cellId].config.hide_code &&+ !state.untouchedNewCells.has(cellId)+ );+}+// Helper function to update a cell in the arrayfunction updateCellRuntimeState({state,@@ -1587,6 +1623,10 @@ export function flattenTopLevelNotebookCells();}+export function createUntouchedCellAtom(cellId: CellId): Atom<boolean> {+ return atom((get) => get(notebookAtom).untouchedNewCells.has(cellId));+}+export function createTracebackInfoAtom(cellId: CellId,): Atom<TracebackInfo[] | undefined> {@@ -1647,4 +1687,5 @@ export const exportedForTesting = {reducer,createActions,initialNotebookState,+ isCellCodeHidden,};diff --git a/frontend/src/core/cells/scrollCellIntoView.ts b/frontend/src/core/cells/scrollCellIntoView.tsindex e06e5c0d06..4f7c287f59 100644--- a/frontend/src/core/cells/scrollCellIntoView.ts+++ b/frontend/src/core/cells/scrollCellIntoView.ts@@ -5,21 +5,21 @@ import {isAnyCellFocused,tryFocus,} from "@/components/editor/focus/focus-manager";+import { retryWithTimeout } from "@/utils/timeout";import { Logger } from "../../utils/Logger";import { goToVariableDefinition } from "../codemirror/go-to-definition/commands";-import type { CellConfig } from "../network/types";import { type CellId, HTMLCellId } from "./ids";export function focusAndScrollCellIntoView({cellId,cell,- config,+ isCodeHidden,codeFocus,variableName,}: {cellId: CellId;cell: RefObject<CellHandle | null>;- config: CellConfig;+ isCodeHidden: boolean;codeFocus: "top" | "bottom" | undefined;variableName: string | undefined;}) {@@ -41,13 +41,14 @@ export function focusAndScrollCellIntoView({}// If the cell's code is hidden, just focus the cell and not the editor.- if (config.hide_code) {+ if (isCodeHidden) {// Focus the parent element, as this is the one with the event handlers.// https://github.com/marimo-team/marimo/issues/2940tryFocus(element);} else {const editor = cell.current?.editorView;if (!editor) {+ Logger.warn("scrollCellIntoView: editor not found", cellId);return;}// If already focused, do nothing.@@ -55,7 +56,18 @@ export function focusAndScrollCellIntoView({return;}- editor.focus();+ // Try to focus a few times+ retryWithTimeout(+ () => {+ editor.focus();+ return editor.hasFocus;+ },+ {+ retries: 5,+ delay: 20,+ },+ );+if (codeFocus === "top") {// If codeFocus is top, move the cursor to the top of the editor.editor.dispatch({diff --git a/frontend/src/core/cells/session.ts b/frontend/src/core/cells/session.tsindex d27f91541c..9c694aa0bc 100644--- a/frontend/src/core/cells/session.ts+++ b/frontend/src/core/cells/session.ts@@ -5,6 +5,7 @@ import { mergeArray } from "@/utils/edit-distance";import { MultiColumn } from "@/utils/id-tree";import { Logger } from "@/utils/Logger";import { parseOutline } from "../dom/outline";+import type { NotebookState } from "./cells";import { CellId } from "./ids";import {type CellData,@@ -238,7 +239,7 @@ function createCellRuntimeFromSession(export function notebookStateFromSession(session: api.Session["NotebookSessionV1"] | null | undefined,notebook: api.Notebook["NotebookV1"] | null | undefined,-) {+): NotebookState | null {// Merge session and notebook cells using edit distanceconst { cellIds, sessionCellData, notebookCellData } =mergeSessionAndNotebookCells(session, notebook);@@ -275,5 +276,6 @@ export function notebookStateFromSession(history: [],scrollKey: null,cellLogs: [],+ untouchedNewCells: new Set(),};}diff --git a/frontend/src/core/cells/types.ts b/frontend/src/core/cells/types.tsindex 318f482161..05b9439ece 100644--- a/frontend/src/core/cells/types.ts+++ b/frontend/src/core/cells/types.ts@@ -37,6 +37,15 @@ export function createCell({};}+export function createCellConfig(config?: Partial<CellConfig>): CellConfig {+ return {+ hide_code: false,+ disabled: false,+ column: null,+ ...config,+ };+}+export function createCellRuntimeState(state?: Partial<CellRuntimeState>,): CellRuntimeState {diff --git a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.tsindex efc43f0c5b..9c3446a3b0 100644--- a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts+++ b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts@@ -3,7 +3,7 @@import { EditorState } from "@codemirror/state";import { EditorView } from "@codemirror/view";import { describe, expect, it } from "vitest";-import { notebookAtom } from "@/core/cells/cells";+import { initialNotebookState, notebookAtom } from "@/core/cells/cells";import type { CellId } from "@/core/cells/ids";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";import { store } from "@/core/state/jotai";@@ -68,15 +68,10 @@ describe("getTopologicalCellIds", () => {it("should return topologically sorted cell IDs", () => {// Setup mock datastore.set(notebookAtom, {+ ...initialNotebookState(),cellIds: MultiColumn.from([[Cells.cell1, Cells.cell2, Cells.cell3, Cells.cell4],]),- cellData: {},- cellRuntime: {},- cellHandles: {},- history: [],- scrollKey: null,- cellLogs: [],});const variables: Variables = {[Variables.var1]: {@@ -108,13 +103,7 @@ describe("getTopologicalCellIds", () => {describe("getCodes", () => {it("should return only the otherCode when there are no other cells", () => {store.set(notebookAtom, {- cellIds: MultiColumn.from([[]]),- cellData: {},- cellRuntime: {},- cellHandles: {},- history: [],- scrollKey: null,- cellLogs: [],+ ...initialNotebookState(),});const otherCode = "print('Hello World')";const result = getCodes(otherCode);@@ -128,16 +117,12 @@ describe("getCodes", () => {createMockEditorView("x = 1"),];store.set(notebookAtom, {+ ...initialNotebookState(),cellIds: MultiColumn.from([[Cells.cell1, Cells.cell2]]),- cellData: {},- cellRuntime: {},cellHandles: {[Cells.cell1]: { current: mockEditorViews[0] },[Cells.cell2]: { current: mockEditorViews[1] },},- history: [],- scrollKey: null,- cellLogs: [],});const result = getCodes(otherCode);expect(result).toEqual("import os\nx = 1\nprint('Hello World')");@@ -150,16 +135,12 @@ describe("getCodes", () => {createMockEditorView("import os"),];store.set(notebookAtom, {+ ...initialNotebookState(),cellIds: MultiColumn.from([[Cells.cell1, Cells.cell2]]),- cellData: {},- cellRuntime: {},cellHandles: {[Cells.cell1]: { current: mockEditorViews[0] },[Cells.cell2]: { current: mockEditorViews[1] },},- history: [],- scrollKey: null,- cellLogs: [],});const result = getCodes(otherCode);expect(result).toEqual("import os\nx = 1\nprint('Hello World')");@@ -173,17 +154,13 @@ describe("getCodes", () => {createMockEditorView("y = x + 1"),];store.set(notebookAtom, {+ ...initialNotebookState(),cellIds: MultiColumn.from([[Cells.cell1, Cells.cell2, Cells.cell3]]),- cellData: {},- cellRuntime: {},cellHandles: {[Cells.cell1]: { current: mockEditorViews[0] },[Cells.cell2]: { current: mockEditorViews[1] },[Cells.cell3]: { current: mockEditorViews[2] },},- history: [],- scrollKey: null,- cellLogs: [],});store.set(variablesAtom, {[Variables.var1]: {diff --git a/frontend/src/core/wasm/__tests__/state.test.ts b/frontend/src/core/wasm/__tests__/state.test.tsindex 05bc07990a..65edaa11c1 100644--- a/frontend/src/core/wasm/__tests__/state.test.ts+++ b/frontend/src/core/wasm/__tests__/state.test.ts@@ -3,7 +3,7 @@import { createRef } from "react";import { describe, expect, it } from "vitest";import type { NotebookState } from "@/core/cells/cells";-import { notebookAtom } from "@/core/cells/cells";+import { initialNotebookState, notebookAtom } from "@/core/cells/cells";import type { CellId } from "@/core/cells/ids";import { createCell, createCellRuntimeState } from "@/core/cells/types";import type { OutputMessage } from "@/core/kernel/messages";@@ -15,6 +15,7 @@ describe("hasAnyOutputAtom", () => {const createNotebookState = (outputs: Array<OutputMessage | null>,): NotebookState => ({+ ...initialNotebookState(),cellIds: new MultiColumn([CollapsibleTree.from(outputs.map((_, i) => `${i}` as CellId)),]),@@ -37,9 +38,6 @@ describe("hasAnyOutputAtom", () => {cellHandles: Object.fromEntries(outputs.map((_, i) => [`${i}` as CellId, createRef()]),),- cellLogs: [],- scrollKey: null,- history: [],});it("should return false when there are no outputs", () => {