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
chore: refactor cell actions in codemirror (#4027)
Myles Scolnickac1061d017f1
diff --git a/frontend/src/__tests__/lru.test.ts b/frontend/src/__tests__/lru.test.tsnew file mode 100644index 0000000000..51d32a2e35--- /dev/null+++ b/frontend/src/__tests__/lru.test.ts@@ -0,0 +1,74 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, test, expect } from "vitest";+import { LRUCache } from "../utils/lru";++describe("LRUCache", () => {+ test("basic get/set operations", () => {+ const cache = new LRUCache<string, number>(3);+ cache.set("a", 1);+ cache.set("b", 2);+ cache.set("c", 3);++ expect(cache.get("a")).toBe(1);+ expect(cache.get("b")).toBe(2);+ expect(cache.get("c")).toBe(3);+ });++ test("evicts least recently used item when over capacity", () => {+ const cache = new LRUCache<string, number>(3);+ cache.set("a", 1);+ cache.set("b", 2);+ cache.set("c", 3);+ cache.set("d", 4);++ // "a" should be evicted as it was the least recently used+ expect(cache.get("a")).toBeUndefined();+ expect(cache.get("b")).toBe(2);+ expect(cache.get("c")).toBe(3);+ expect(cache.get("d")).toBe(4);+ });++ test("accessing an item makes it most recently used", () => {+ const cache = new LRUCache<string, number>(3);+ cache.set("a", 1);+ cache.set("b", 2);+ cache.set("c", 3);++ // Access "a", making it most recently used+ cache.get("a");+ cache.set("d", 4);++ // "b" should be evicted as it becomes the least recently used+ expect(cache.get("b")).toBeUndefined();+ expect(cache.get("a")).toBe(1);+ expect(cache.get("c")).toBe(3);+ expect(cache.get("d")).toBe(4);+ });++ test("updating existing key maintains order", () => {+ const cache = new LRUCache<string, number>(3);+ cache.set("a", 1);+ cache.set("b", 2);+ cache.set("c", 3);++ // Update "a"+ cache.set("a", 10);+ cache.set("d", 4);++ // "b" should be evicted as "a" was moved to most recent+ expect(cache.get("b")).toBeUndefined();+ expect(cache.get("a")).toBe(10);+ expect(cache.get("c")).toBe(3);+ expect(cache.get("d")).toBe(4);+ });++ test("keys() returns iterator in order", () => {+ const cache = new LRUCache<string, number>(3);+ cache.set("a", 1);+ cache.set("b", 2);+ cache.set("c", 3);++ const keys = [...cache.keys()];+ expect(keys).toEqual(["a", "b", "c"]);+ });+});diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex db845506d0..24f0614d67 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -154,16 +154,13 @@ const CellComponent = (debuggerActive,appClosed,canDelete,- updateCellCode,prepareForRun,createNewCell,deleteCell,- focusCell,moveCell,setStdinResponse,moveToNextCell,updateCellConfig,- clearSerializedEditorState,sendToBottom,sendToTop,collapseCell,@@ -661,17 +658,9 @@ const CellComponent = (status={status}serializedEditorState={serializedEditorState}runCell={handleRun}- updateCellCode={updateCellCode}setEditorView={(ev) => {editorView.current = ev;}}- createNewCell={createNewCell}- deleteCell={deleteCell}- focusCell={focusCell}- moveCell={moveCell}- moveToNextCell={moveToNextCell}- updateCellConfig={updateCellConfig}- clearSerializedEditorState={clearSerializedEditorState}userConfig={userConfig}editorViewRef={editorView}editorViewParentRef={editorViewParentRef}diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsxindex 5ada9a1cb6..d64dec6052 100644--- a/frontend/src/components/editor/actions/useCellActionButton.tsx+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx@@ -74,7 +74,6 @@ export function useCellActionButtons({ cell }: Props) {const {createNewCell: createCell,updateCellConfig,- updateCellCode,updateCellName,moveCell,sendToTop,@@ -218,7 +217,7 @@ export function useCellActionButtons({ cell }: Props) {if (!editorView) {return;}- formatEditorViews({ [cellId]: editorView }, updateCellCode);+ formatEditorViews({ [cellId]: editorView });},},{diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 487d32b042..fe93047653 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -2,16 +2,12 @@import { historyField } from "@codemirror/commands";import { EditorState, StateEffect } from "@codemirror/state";import { EditorView, ViewPlugin } from "@codemirror/view";-import React, { memo, useCallback, useEffect, useRef, useMemo } from "react";+import React, { memo, useEffect, useRef, useMemo } from "react";import { setupCodeMirror } from "@/core/codemirror/cm";import { getFeatureFlag } from "@/core/config/feature-flag";import useEvent from "react-use-event-hook";-import {- type CellActions,- notebookAtom,- useCellActions,-} from "@/core/cells/cells";+import { notebookAtom, useCellActions } from "@/core/cells/cells";import type { CellRuntimeState, CellData } from "@/core/cells/types";import type { UserConfig } from "@/core/config/config-schema";import type { Theme } from "@/theme/useTheme";@@ -43,19 +39,8 @@ import { store } from "@/core/state/jotai";export interface CellEditorPropsextends Pick<CellRuntimeState, "status">,- Pick<CellData, "id" | "code" | "serializedEditorState" | "config">,- Pick<- CellActions,- | "updateCellCode"- | "createNewCell"- | "deleteCell"- | "focusCell"- | "moveCell"- | "updateCellConfig"- | "clearSerializedEditorState"- > {+ Pick<CellData, "id" | "code" | "serializedEditorState" | "config"> {runCell: () => void;- moveToNextCell: CellActions["moveToNextCell"] | undefined;theme: Theme;showPlaceholder: boolean;editorViewRef: React.MutableRefObject<EditorView | null>;@@ -93,14 +78,6 @@ const CellEditorInternal = ({serializedEditorState,setEditorView,runCell,- updateCellCode,- createNewCell,- deleteCell,- focusCell,- moveCell,- moveToNextCell,- updateCellConfig,- clearSerializedEditorState,userConfig,editorViewRef,editorViewParentRef,@@ -114,7 +91,7 @@ const CellEditorInternal = ({const setLastFocusedCellId = useSetLastFocusedCellId();const loading = status === "running" || status === "queued";- const { sendToTop, sendToBottom } = useCellActions();+ const cellActions = useCellActions();const splitCell = useSplitCellCallback();const isMarkdown = languageAdapter === "markdown";@@ -125,46 +102,22 @@ const CellEditorInternal = ({return false;}- deleteCell({ cellId });+ cellActions.deleteCell({ cellId });return true;});- const createBelow = useCallback(- () => createNewCell({ cellId, before: false }),- [cellId, createNewCell],- );- const createAbove = useCallback(- () => createNewCell({ cellId, before: true }),- [cellId, createNewCell],- );- const moveDown = useCallback(- () => moveCell({ cellId, before: false }),- [cellId, moveCell],- );- const moveUp = useCallback(- () => moveCell({ cellId, before: true }),- [cellId, moveCell],- );- const focusDown = useCallback(- () => focusCell({ cellId, before: false }),- [cellId, focusCell],- );- const focusUp = useCallback(- () => focusCell({ cellId, before: true }),- [cellId, focusCell],- );-const toggleHideCode = useEvent(() => {// Use cellConfig.hide_code instead of hidden, since it may be temporarily shownconst nextHidden = !cellConfig.hide_code;// Fire-and-forget savevoid saveCellConfig({ configs: { [cellId]: { hide_code: nextHidden } } });- updateCellConfig({ cellId, config: { hide_code: nextHidden } });+ cellActions.updateCellConfig({ cellId, config: { hide_code: nextHidden } });return nextHidden;});+const autoInstantiate = useAtomValue(autoInstantiateAtom);const afterToggleMarkdown = useEvent(() => {- maybeAddMarimoImport(autoInstantiate, createNewCell);+ maybeAddMarimoImport(autoInstantiate, cellActions.createNewCell);});const aiEnabled = isAiEnabled(userConfig);@@ -174,18 +127,14 @@ const CellEditorInternal = ({cellId,showPlaceholder,enableAI: aiEnabled,- cellCodeCallbacks: {- updateCellCode,+ cellActions: {+ ...cellActions,afterToggleMarkdown,- },- cellMovementCallbacks: {onRun: runCell,deleteCell: handleDelete,- createAbove,- createBelow,createManyBelow: (cells) => {for (const code of [...cells].reverse()) {- createNewCell({+ cellActions.createNewCell({code,before: false,cellId: cellId,@@ -194,14 +143,7 @@ const CellEditorInternal = ({});}},- moveUp,- moveDown,- focusUp,- focusDown,- sendToTop,- sendToBottom,splitCell,- moveToNextCell,toggleHideCode,aiCellCompletion: () => {let closed = false;@@ -248,19 +190,9 @@ const CellEditorInternal = ({aiEnabled,theme,showPlaceholder,- createAbove,- createBelow,- focusUp,- focusDown,- moveUp,- moveDown,- moveToNextCell,- sendToTop,- sendToBottom,+ cellActions,splitCell,- createNewCell,toggleHideCode,- updateCellCode,handleDelete,runCell,setAiCompletionCell,@@ -274,7 +206,7 @@ const CellEditorInternal = ({const rtc = realTimeCollaboration(cellId, (code) => {// It's not really a formatting change,// but this means it won't be marked as stale- updateCellCode({ cellId, code, formattingChange: true });+ cellActions.updateCellCode({ cellId, code, formattingChange: true });});extensions.push(rtc.extension);code = rtc.code;@@ -299,7 +231,7 @@ const CellEditorInternal = ({const rtc = realTimeCollaboration(cellId, (code) => {// It's not really a formatting change,// but this means it won't be marked as stale- updateCellCode({ cellId, code, formattingChange: true });+ cellActions.updateCellCode({ cellId, code, formattingChange: true });});extensions.push(rtc.extension);}@@ -324,7 +256,7 @@ const CellEditorInternal = ({(code) => {// It's not really a formatting change,// but this means it won't be marked as stale- updateCellCode({ cellId, code, formattingChange: true });+ cellActions.updateCellCode({ cellId, code, formattingChange: true });},code,);@@ -345,7 +277,7 @@ const CellEditorInternal = ({switchLanguage(ev, getInitialLanguageAdapter(ev.state).type);setEditorView(ev);// Clear the serialized state so that we don't re-create the editor next time- clearSerializedEditorState({ cellId });+ cellActions.clearSerializedEditorState({ cellId });});useEffect(() => {diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 075d4efacd..27ff72a699 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -95,7 +95,7 @@ const CellArrayInternal: React.FC<CellArrayProps> = ({useHotkey("global.foldCode", actions.foldAll);useHotkey("global.unfoldCode", actions.unfoldAll);useHotkey("global.formatAll", () => {- formatAll(actions.updateCellCode);+ formatAll();});// Catch all to avoid native OS behavior// Otherwise a user might try to hide a cell and accidentally hide the OS windowdiff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsxindex fc8bddb646..a0f82a8d91 100644--- a/frontend/src/components/scratchpad/scratchpad.tsx+++ b/frontend/src/components/scratchpad/scratchpad.tsx@@ -137,14 +137,6 @@ export const ScratchPad: React.FC = () => {status="idle"serializedEditorState={null}runCell={handleRun}- updateCellCode={updateCellCode}- createNewCell={Functions.NOOP}- deleteCell={Functions.NOOP}- focusCell={Functions.NOOP}- moveCell={Functions.NOOP}- moveToNextCell={undefined}- updateCellConfig={Functions.NOOP}- clearSerializedEditorState={Functions.NOOP}userConfig={userConfig}editorViewRef={ref}setEditorView={(ev) => {diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex 1dca862861..dc12ba6243 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -21,7 +21,6 @@ import { python } from "@codemirror/lang-python";import { EditorState } from "@codemirror/state";import type { CellHandle } from "@/components/editor/Cell";import { foldAllBulk, unfoldAllBulk } from "@/core/codemirror/editing/commands";-import type { MovementCallbacks } from "@/core/codemirror/cells/extensions";import { adaptiveLanguageConfiguration } from "@/core/codemirror/language/extension";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";import {@@ -80,15 +79,14 @@ function createEditor(content: string) {extensions: [python(),adaptiveLanguageConfiguration({+ cellId: "cell1" as CellId,completionConfig: {activate_on_typing: true,copilot: false,codeium_api_key: null,},hotkeys: new OverridingHotkeyProvider({}),- showPlaceholder: true,- enableAI: true,- cellMovementCallbacks: {} as MovementCallbacks,+ placeholderType: "marimo-import",}),],});diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 382cd27bfa..1627d9e5a7 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -913,6 +913,12 @@ const {action: { cellId: CellId; before: boolean; noCreate?: boolean },) => {const { cellId, before, noCreate = false } = action;++ // Can't move focus of scratch cell+ if (cellId === SCRATCH_CELL_ID) {+ return state;+ }+const column = state.cellIds.findWithId(cellId);const index = column.indexOfOrThrow(cellId);const nextCellIndex = before ? index - 1 : index + 1;diff --git a/frontend/src/core/codemirror/__tests__/extensions.test.ts b/frontend/src/core/codemirror/__tests__/extensions.test.tsnew file mode 100644index 0000000000..8b0d49465d--- /dev/null+++ b/frontend/src/core/codemirror/__tests__/extensions.test.ts@@ -0,0 +1,114 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { EditorView } from "@codemirror/view";+import { EditorState } from "@codemirror/state";+import * as scrollUtils from "../../../utils/scroll";+import { scrollActiveLineIntoView } from "../extensions";+import { formattingChangeEffect } from "../format";++// Mock the smartScrollIntoView function+vi.mock("../../../utils/scroll", () => ({+ smartScrollIntoView: vi.fn(),+}));++describe("scrollActiveLineIntoView", () => {+ let view: EditorView;+ let mockAppElement: HTMLElement;++ beforeEach(() => {+ // Create a mock App element+ mockAppElement = document.createElement("div");+ mockAppElement.id = "App";+ document.body.append(mockAppElement);++ // Create an editor view with the scrollActiveLineIntoView extension+ view = new EditorView({+ state: EditorState.create({+ doc: "line 1\nline 2\nline 3",+ extensions: [scrollActiveLineIntoView()],+ }),+ });++ // Add the editor to the document+ document.body.append(view.dom);++ // Reset the mock+ vi.mocked(scrollUtils.smartScrollIntoView).mockClear();+ });++ afterEach(() => {+ // Clean up+ view.destroy();+ mockAppElement.remove();+ if (document.body.contains(view.dom)) {+ view.dom.remove();+ }+ });++ it("should not scroll when editor does not have focus", () => {+ // Simulate a height change and doc change+ view.dispatch({+ changes: { from: 0, to: 0, insert: "new line\n" },+ });++ // The editor doesn't have focus by default+ expect(vi.mocked(scrollUtils.smartScrollIntoView)).not.toHaveBeenCalled();+ });++ it("should scroll active line into view when height and doc change", () => {+ // Mock the focus state+ Object.defineProperty(view, "hasFocus", { value: true });++ // Add an active line element+ const activeLine = document.createElement("div");+ activeLine.className = "cm-activeLine cm-line";+ view.dom.append(activeLine);++ // Simulate a height change and doc change+ view.dispatch({+ changes: { from: 0, to: 0, insert: "new line\n" },+ });++ // Check that smartScrollIntoView was called with the right arguments+ expect(vi.mocked(scrollUtils.smartScrollIntoView)).toHaveBeenCalledWith(+ activeLine,+ { top: 30, bottom: 150 },+ mockAppElement,+ );+ });++ it("should not scroll when there is no active line", () => {+ // Mock the focus state+ Object.defineProperty(view, "hasFocus", { value: true });++ // Simulate a height change and doc change+ view.dispatch({+ changes: { from: 0, to: 0, insert: "new line\n" },+ });++ // No active line element, so smartScrollIntoView should not be called+ expect(vi.mocked(scrollUtils.smartScrollIntoView)).not.toHaveBeenCalled();+ });++ it("should not scroll for formatting changes", () => {+ // Mock the focus state+ Object.defineProperty(view, "hasFocus", { value: true });++ // Add an active line element+ const activeLine = document.createElement("div");+ activeLine.className = "cm-activeLine cm-line";+ view.dom.append(activeLine);++ // Create a transaction with the formatting change effect+ const transaction = view.state.update({+ changes: { from: 0, to: 0, insert: "formatted line\n" },+ effects: [formattingChangeEffect.of(true)],+ });++ // Dispatch the transaction+ view.dispatch(transaction);++ // Should not scroll for formatting changes+ expect(vi.mocked(scrollUtils.smartScrollIntoView)).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/core/codemirror/__tests__/setup.test.ts b/frontend/src/core/codemirror/__tests__/setup.test.tsindex 84cfb7eaf7..749f21db2c 100644--- a/frontend/src/core/codemirror/__tests__/setup.test.ts+++ b/frontend/src/core/codemirror/__tests__/setup.test.ts@@ -7,11 +7,16 @@ import type { CellId } from "@/core/cells/ids";import { Objects } from "@/utils/objects";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";import { PythonLanguageAdapter } from "../language/python";+import type { CodemirrorCellActions } from "../cells/state";-vi.mock("@/core/config/config", () => ({- parseAppConfig: () => ({}),- parseUserConfig: () => ({}),-}));+vi.mock("@/core/config/config", async (importOriginal) => {+ const original = await importOriginal<{}>();+ return {+ ...original,+ parseAppConfig: () => ({}),+ parseUserConfig: () => ({}),+ };+});function namedFunction(name: string) {const fn = () => false;@@ -24,27 +29,14 @@ function getOpts() {cellId: "0" as CellId,showPlaceholder: false,enableAI: false,- cellMovementCallbacks: {- onRun: namedFunction("onRun"),+ cellActions: {+ toggleHideCode: namedFunction("toggleHideCode"),aiCellCompletion: namedFunction("aiCellCompletion"),- deleteCell: namedFunction("deleteCell"),- createAbove: namedFunction("createAbove"),- createBelow: namedFunction("createBelow"),createManyBelow: namedFunction("createManyBelow"),- moveUp: namedFunction("moveUp"),- moveDown: namedFunction("moveDown"),- focusUp: namedFunction("focusUp"),- focusDown: namedFunction("focusDown"),- sendToTop: namedFunction("sendToTop"),- sendToBottom: namedFunction("sendToBottom"),- splitCell: namedFunction("splitCell"),- moveToNextCell: namedFunction("moveToNextCell"),- toggleHideCode: namedFunction("toggleHideCode"),- },- cellCodeCallbacks: {- updateCellCode: namedFunction("updateCellCode"),+ onRun: namedFunction("onRun"),+ deleteCell: namedFunction("deleteCell"),afterToggleMarkdown: namedFunction("afterToggleMarkdown"),- },+ } as unknown as CodemirrorCellActions,completionConfig: {activate_on_typing: false,copilot: false,@@ -124,19 +116,14 @@ test("placeholder adds another extension", () => {const opts = getOpts();const withAI = new PythonLanguageAdapter().getExtension(+ opts.cellId,opts.completionConfig,opts.hotkeys,"marimo-import",- opts.cellMovementCallbacks,).flat();const withoutAI = new PythonLanguageAdapter()- .getExtension(- opts.completionConfig,- opts.hotkeys,- "none",- opts.cellMovementCallbacks,- )+ .getExtension(opts.cellId, opts.completionConfig, opts.hotkeys, "none").flat();expect(withAI.length - 1).toBe(withoutAI.length);});@@ -144,20 +131,10 @@ test("placeholder adds another extension", () => {test("ai adds more extensions", () => {const opts = getOpts();const withAI = new PythonLanguageAdapter()- .getExtension(- opts.completionConfig,- opts.hotkeys,- "ai",- opts.cellMovementCallbacks,- )+ .getExtension(opts.cellId, opts.completionConfig, opts.hotkeys, "ai").flat();const withoutAI = new PythonLanguageAdapter()- .getExtension(- opts.completionConfig,- opts.hotkeys,- "none",- opts.cellMovementCallbacks,- )+ .getExtension(opts.cellId, opts.completionConfig, opts.hotkeys, "none").flat();expect(withAI.length - 2).toBe(withoutAI.length);});diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.tsindex f3d9c05bc7..8f7e38b281 100644--- a/frontend/src/core/codemirror/cells/extensions.ts+++ b/frontend/src/core/codemirror/cells/extensions.ts@@ -4,61 +4,32 @@ import { EditorView, type KeyBinding, keymap } from "@codemirror/view";import { type CellId, HTMLCellId } from "@/core/cells/ids";import { type Extension, Prec } from "@codemirror/state";import { formatKeymapExtension } from "../extensions";-import type { CellActions } from "@/core/cells/cells";import { getEditorCodeAsPython } from "../language/utils";import { formattingChangeEffect } from "../format";import { closeCompletion, completionStatus } from "@codemirror/autocomplete";import { isAtEndOfEditor, isAtStartOfEditor } from "../utils";import { goToDefinitionAtCursorPosition } from "../go-to-definition/utils";--export interface MovementCallbacks- extends Pick<CellActions, "splitCell" | "sendToTop" | "sendToBottom"> {- moveToNextCell: CellActions["moveToNextCell"] | undefined;- onRun: () => void;- deleteCell: () => void;- createAbove: () => void;- createBelow: () => void;- createManyBelow: (content: string[]) => void;- moveUp: () => void;- moveDown: () => void;- focusUp: () => void;- focusDown: () => void;- toggleHideCode: () => boolean;- aiCellCompletion: () => boolean;-}+import {+ cellActionsState,+ cellIdState,+ type CodemirrorCellActions,+} from "./state";+import { SCRATCH_CELL_ID } from "@/core/cells/cells";/**- * Extensions for cell movement+ * Extensions for cell actions*/-export function cellMovementBundle(- cellId: CellId,- callbacks: MovementCallbacks,- hotkeys: HotkeyProvider,-): Extension[] {- const {- onRun,- deleteCell,- createAbove,- createBelow,- moveUp,- moveDown,- focusUp,- focusDown,- sendToTop,- sendToBottom,- splitCell,- moveToNextCell,- toggleHideCode,- aiCellCompletion,- } = callbacks;+function cellKeymaps(cellId: CellId, hotkeys: HotkeyProvider): Extension[] {+ const keybindings: KeyBinding[] = [];- const keybindings: KeyBinding[] = [+ keybindings.push({key: hotkeys.getHotkey("cell.run").key,preventDefault: true,stopPropagation: true,- run: () => {- onRun();+ run: (ev) => {+ const actions = ev.state.facet(cellActionsState);+ actions.onRun();return true;},},@@ -67,12 +38,13 @@ export function cellMovementBundle(preventDefault: true,stopPropagation: true,run: (ev) => {- onRun();- if (!moveToNextCell) {+ const actions = ev.state.facet(cellActionsState);+ actions.onRun();+ if (cellId === SCRATCH_CELL_ID) {return true;}ev.contentDOM.blur();- moveToNextCell({ cellId, before: false });+ actions.moveToNextCell({ cellId, before: false });return true;},},@@ -81,221 +53,230 @@ export function cellMovementBundle(preventDefault: true,stopPropagation: true,run: (ev) => {- onRun();- if (!moveToNextCell) {+ const actions = ev.state.facet(cellActionsState);+ actions.onRun();+ if (cellId === SCRATCH_CELL_ID) {return true;}ev.contentDOM.blur();- moveToNextCell({ cellId, before: true });+ actions.moveToNextCell({ cellId, before: true });return true;},},{- key: hotkeys.getHotkey("cell.delete").key,+ key: hotkeys.getHotkey("cell.aiCompletion").key,preventDefault: true,stopPropagation: true,- run: (cm) => {- // Cannot delete non-empty cells for safety- if (cm.state.doc.length === 0) {- deleteCell();+ run: (ev) => {+ const actions = ev.state.facet(cellActionsState);+ const closed = actions.aiCellCompletion();+ if (closed) {+ ev.contentDOM.focus();}- // shortcuts.delete (shift-backspace) overlaps with- // defaultKeymap's deleteCharBackward (backspace); we don't want- // shift-backspace to trigger character deletion, because otherwise- // users might accidentally delete their whole notebook if they- // absent-mindedly held these keys. That's why we always return true.return true;},},- {- key: hotkeys.getHotkey("cell.moveUp").key,- preventDefault: true,- stopPropagation: true,- run: () => {- moveUp();- return true;+ );++ if (cellId !== SCRATCH_CELL_ID) {+ keybindings.push(+ {+ key: hotkeys.getHotkey("cell.goToDefinition").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ goToDefinitionAtCursorPosition(ev);+ return true;+ },},- },- {- key: hotkeys.getHotkey("cell.moveDown").key,- preventDefault: true,- stopPropagation: true,- run: () => {- moveDown();- return true;+ {+ key: hotkeys.getHotkey("cell.delete").key,+ preventDefault: true,+ stopPropagation: true,+ run: (cm) => {+ // Cannot delete non-empty cells for safety+ if (cm.state.doc.length === 0) {+ const actions = cm.state.facet(cellActionsState);+ actions.deleteCell();+ }+ // shortcuts.delete (shift-backspace) overlaps with+ // defaultKeymap's deleteCharBackward (backspace); we don't want+ // shift-backspace to trigger character deletion, because otherwise+ // users might accidentally delete their whole notebook if they+ // absent-mindedly held these keys. That's why we always return true.+ return true;+ },},- },- {- key: "ArrowUp",- preventDefault: true,- stopPropagation: true,- run: (ev) => {- // Skip if we are in the middle of an autocompletion- const hasAutocomplete = completionStatus(ev.state);- if (hasAutocomplete) {- return false;- }-- if (isAtStartOfEditor(ev)) {- focusUp();+ {+ key: hotkeys.getHotkey("cell.moveUp").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ const actions = ev.state.facet(cellActionsState);+ actions.moveCell({ cellId, before: true });return true;- }- return false;+ },},- },- {- key: "ArrowDown",- preventDefault: true,- stopPropagation: true,- run: (ev) => {- // Skip if we are in the middle of an autocompletion- const hasAutocomplete = completionStatus(ev.state);- if (hasAutocomplete) {- return false;- }-- if (isAtEndOfEditor(ev)) {- focusDown();+ {+ key: hotkeys.getHotkey("cell.moveDown").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ const actions = ev.state.facet(cellActionsState);+ actions.moveCell({ cellId, before: false });return true;- }- return false;+ },},- },- {- key: hotkeys.getHotkey("cell.focusDown").key,- preventDefault: true,- stopPropagation: true,- run: () => {- focusDown();- return true;+ {+ key: "ArrowUp",+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ // Skip if we are in the middle of an autocompletion+ const hasAutocomplete = completionStatus(ev.state);+ if (hasAutocomplete) {+ return false;+ }++ if (isAtStartOfEditor(ev)) {+ const actions = ev.state.facet(cellActionsState);+ actions.moveToNextCell({ cellId, before: true });+ return true;+ }+ return false;+ },},- },- {- key: hotkeys.getHotkey("cell.focusUp").key,- preventDefault: true,- stopPropagation: true,- run: () => {- focusUp();- return true;+ {+ key: "ArrowDown",+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ // Skip if we are in the middle of an autocompletion+ const hasAutocomplete = completionStatus(ev.state);+ if (hasAutocomplete) {+ return false;+ }++ if (isAtEndOfEditor(ev)) {+ const actions = ev.state.facet(cellActionsState);+ actions.moveToNextCell({ cellId, before: false });+ return true;+ }+ return false;+ },},- },- {- key: hotkeys.getHotkey("cell.sendToBottom").key,- preventDefault: true,- stopPropagation: true,- run: () => {- sendToBottom({ cellId });- return true;+ {+ key: hotkeys.getHotkey("cell.focusDown").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ const actions = ev.state.facet(cellActionsState);+ actions.moveToNextCell({ cellId, before: false });+ return true;+ },},- },- {- key: hotkeys.getHotkey("cell.sendToTop").key,- preventDefault: true,- stopPropagation: true,- run: () => {- sendToTop({ cellId });- return true;+ {+ key: hotkeys.getHotkey("cell.focusUp").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ const actions = ev.state.facet(cellActionsState);+ actions.moveToNextCell({ cellId, before: true });+ return true;+ },},- },- {- key: hotkeys.getHotkey("cell.createAbove").key,- preventDefault: true,- stopPropagation: true,- run: (ev) => {- ev.contentDOM.blur();- createAbove();- return true;+ {+ key: hotkeys.getHotkey("cell.sendToBottom").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ const actions = ev.state.facet(cellActionsState);+ actions.sendToBottom({ cellId });+ return true;+ },},- },- {- key: hotkeys.getHotkey("cell.createBelow").key,- preventDefault: true,- stopPropagation: true,- run: (ev) => {- ev.contentDOM.blur();- createBelow();- return true;+ {+ key: hotkeys.getHotkey("cell.sendToTop").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ const actions = ev.state.facet(cellActionsState);+ actions.sendToTop({ cellId });+ return true;+ },},- },- {- key: hotkeys.getHotkey("cell.hideCode").key,- preventDefault: true,- stopPropagation: true,- run: (ev) => {- const isHidden = toggleHideCode();- closeCompletion(ev);- // If we are newly hidden, blur the editor- if (isHidden) {+ {+ key: hotkeys.getHotkey("cell.createAbove").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {ev.contentDOM.blur();- // Focus on the parent element- // https://github.com/marimo-team/marimo/issues/2941- document- .getElementById(HTMLCellId.create(cellId))- ?.parentElement?.focus();- } else {- ev.contentDOM.focus();- }- return true;+ const actions = ev.state.facet(cellActionsState);+ actions.createNewCell({ cellId, before: true });+ return true;+ },},- },- {- key: hotkeys.getHotkey("cell.aiCompletion").key,- preventDefault: true,- stopPropagation: true,- run: (ev) => {- const closed = aiCellCompletion();- if (closed) {- ev.contentDOM.focus();- }- return true;+ {+ key: hotkeys.getHotkey("cell.createBelow").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ ev.contentDOM.blur();+ const actions = ev.state.facet(cellActionsState);+ actions.createNewCell({ cellId, before: false });+ return true;+ },},- },- {- key: hotkeys.getHotkey("cell.goToDefinition").key,- preventDefault: true,- stopPropagation: true,- run: (ev) => {- goToDefinitionAtCursorPosition(ev);- return true;+ {+ key: hotkeys.getHotkey("cell.hideCode").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ const actions = ev.state.facet(cellActionsState);+ const isHidden = actions.toggleHideCode();+ closeCompletion(ev);+ // If we are newly hidden, blur the editor+ if (isHidden) {+ ev.contentDOM.blur();+ // Focus on the parent element+ // https://github.com/marimo-team/marimo/issues/2941+ document+ .getElementById(HTMLCellId.create(cellId))+ ?.parentElement?.focus();+ } else {+ ev.contentDOM.focus();+ }+ return true;+ },},- },- {- key: hotkeys.getHotkey("cell.splitCell").key,- preventDefault: true,- stopPropagation: true,- run: (ev) => {- splitCell({ cellId });- if (!moveToNextCell) {+ {+ key: hotkeys.getHotkey("cell.splitCell").key,+ preventDefault: true,+ stopPropagation: true,+ run: (ev) => {+ const actions = ev.state.facet(cellActionsState);+ actions.splitCell({ cellId });+ if (!actions.moveToNextCell) {+ return true;+ }+ requestAnimationFrame(() => {+ ev.contentDOM.blur();+ actions.moveToNextCell({ cellId, before: false }); // focus new cell+ });return true;- }- requestAnimationFrame(() => {- ev.contentDOM.blur();- moveToNextCell({ cellId, before: false }); // focus new cell- });- return true;+ },},- },- ];+ );+ }// Highest priority so that we can override the default keymapreturn [Prec.high(keymap.of(keybindings))];}-export interface CodeCallbacks {- updateCellCode: CellActions["updateCellCode"];- afterToggleMarkdown: () => void;-}-/*** Extensions for cell code editing*/-export function cellCodeEditingBundle(- cellId: CellId,- callbacks: CodeCallbacks,- hotkeys: HotkeyProvider,-): Extension[] {- const { updateCellCode } = callbacks;-+function cellCodeEditing(hotkeys: HotkeyProvider): Extension[] {const onChangePlugin = EditorView.updateListener.of((update) => {if (update.docChanged) {// Check if the doc update was a formatting change@@ -304,7 +285,9 @@ export function cellCodeEditingBundle(tr.effects.some((effect) => effect.is(formattingChangeEffect)),);const nextCode = getEditorCodeAsPython(update.view);- updateCellCode({+ const cellActions = update.view.state.facet(cellActionsState);+ const cellId = update.view.state.facet(cellIdState);+ cellActions.updateCellCode({cellId,code: nextCode,formattingChange: isFormattingChange,@@ -312,15 +295,13 @@ export function cellCodeEditingBundle(}});- return [onChangePlugin, formatKeymapExtension(cellId, callbacks, hotkeys)];+ return [onChangePlugin, formatKeymapExtension(hotkeys)];}/*** Extension for auto-running markdown cells*/-export function markdownAutoRunExtension(- callbacks: MovementCallbacks,-): Extension {+export function markdownAutoRunExtension(): Extension {return EditorView.updateListener.of((update) => {// If the doc didn't change, ignoreif (!update.docChanged) {@@ -342,6 +323,20 @@ export function markdownAutoRunExtension(return;}- callbacks.onRun();+ const actions = update.view.state.facet(cellActionsState);+ actions.onRun();});}++export function cellBundle(+ cellId: CellId,+ hotkeys: HotkeyProvider,+ cellActions: CodemirrorCellActions,+): Extension[] {+ return [+ cellActionsState.of(cellActions),+ cellIdState.of(cellId),+ cellKeymaps(cellId, hotkeys),+ cellCodeEditing(hotkeys),+ ];+}diff --git a/frontend/src/core/codemirror/cells/state.ts b/frontend/src/core/codemirror/cells/state.tsnew file mode 100644index 0000000000..5b017dd1d4--- /dev/null+++ b/frontend/src/core/codemirror/cells/state.ts@@ -0,0 +1,30 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { CellId } from "@/core/cells/ids";+import { Facet } from "@codemirror/state";+import type { CellActions } from "@/core/cells/cells";++export interface CodemirrorCellActions extends CellActions {+ toggleHideCode: () => boolean;+ aiCellCompletion: () => boolean;+ createManyBelow: (content: string[]) => void;+ onRun: () => void;+ deleteCell: () => void;+ afterToggleMarkdown: () => void;+}++/**+ * State for cell actions+ */+export const cellActionsState = Facet.define<+ CodemirrorCellActions,+ CodemirrorCellActions+>({+ combine: (values) => values[0],+});++/**+ * State for cell id+ */+export const cellIdState = Facet.define<CellId, CellId>({+ combine: (values) => values[0],+});diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.tsindex a072bf8892..fc515cfce8 100644--- a/frontend/src/core/codemirror/cm.ts+++ b/frontend/src/core/codemirror/cm.ts@@ -40,12 +40,7 @@ import type { CompletionConfig, KeymapConfig } from "../config/config-schema";import type { Theme } from "../../theme/useTheme";import { findReplaceBundle } from "./find-replace/extension";-import {- type CodeCallbacks,- type MovementCallbacks,- cellCodeEditingBundle,- cellMovementBundle,-} from "./cells/extensions";+import { cellBundle } from "./cells/extensions";import type { CellId } from "../cells/ids";import { keymapBundle } from "./keymaps/keymaps";import { scrollActiveLineIntoView } from "./extensions";@@ -65,41 +60,48 @@ import { requestEditCompletion } from "./ai/request";import { getCurrentLanguageAdapter } from "./language/commands";import { aiExtension } from "@marimo-team/codemirror-ai";import { getFeatureFlag } from "../config/feature-flag";+import type { CodemirrorCellActions } from "./cells/state";+import { cellConfigExtension } from "./config/extension";export interface CodeMirrorSetupOpts {cellId: CellId;showPlaceholder: boolean;enableAI: boolean;- cellMovementCallbacks: MovementCallbacks;- cellCodeCallbacks: CodeCallbacks;+ cellActions: CodemirrorCellActions;completionConfig: CompletionConfig;keymapConfig: KeymapConfig;theme: Theme;hotkeys: HotkeyProvider;}+function getPlaceholderType(opts: CodeMirrorSetupOpts) {+ const { showPlaceholder, enableAI } = opts;+ return showPlaceholder ? "marimo-import" : enableAI ? "ai" : "none";+}+/*** Setup CodeMirror for a cell*/export const setupCodeMirror = (opts: CodeMirrorSetupOpts): Extension[] => {const {cellId,- cellMovementCallbacks,- cellCodeCallbacks,keymapConfig,hotkeys,enableAI,+ cellActions,+ completionConfig,} = opts;+ const placeholderType = getPlaceholderType(opts);return [// Editor keymaps (vim or defaults) based on user config- keymapBundle(keymapConfig, cellMovementCallbacks),+ keymapBundle(keymapConfig),dndBundle(),pasteBundle(),jupyterHelpExtension(),// Cell editing- cellMovementBundle(cellId, cellMovementCallbacks, hotkeys),- cellCodeEditingBundle(cellId, cellCodeCallbacks, hotkeys),+ cellConfigExtension(completionConfig, hotkeys, placeholderType),+ cellBundle(cellId, hotkeys, cellActions),// Comes last so that it can be overriddenbasicBundle(opts),// Underline cmd+clickable placeholder@@ -137,7 +139,8 @@ const startCompletionAtEndOfLine = (cm: EditorView): boolean => {// Based on codemirror's basicSetup extensionexport const basicBundle = (opts: CodeMirrorSetupOpts): Extension[] => {- const { theme, hotkeys, completionConfig } = opts;+ const { theme, hotkeys, completionConfig, cellId } = opts;+ const placeholderType = getPlaceholderType(opts);return [///// View@@ -173,7 +176,12 @@ export const basicBundle = (opts: CodeMirrorSetupOpts): Extension[] => {keymap.of(foldKeymap),///// Language Support- adaptiveLanguageConfiguration(opts),+ adaptiveLanguageConfiguration({+ placeholderType,+ completionConfig,+ hotkeys,+ cellId,+ }),///// EditinghistoryCompartment.of(history()),diff --git a/frontend/src/core/codemirror/config/extension.ts b/frontend/src/core/codemirror/config/extension.tsindex 462852a4f1..f42574dbd2 100644--- a/frontend/src/core/codemirror/config/extension.ts+++ b/frontend/src/core/codemirror/config/extension.ts@@ -2,8 +2,11 @@import type { CompletionConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { Facet } from "@codemirror/state";-import type { MovementCallbacks } from "../cells/extensions";+import type { CellId } from "@/core/cells/ids";+/**+ * State for completion config+ */export const completionConfigState = Facet.define<CompletionConfig,CompletionConfig@@ -11,6 +14,9 @@ export const completionConfigState = Facet.define<combine: (values) => values[0],});+/**+ * State for hotkeys provider+ */export const hotkeysProviderState = Facet.define<HotkeyProvider,HotkeyProvider@@ -18,14 +24,33 @@ export const hotkeysProviderState = Facet.define<combine: (values) => values[0],});+/**+ * State for placeholder type+ */export type PlaceholderType = "marimo-import" | "ai" | "none";export const placeholderState = Facet.define<PlaceholderType, PlaceholderType>({combine: (values) => values[0],});-export const movementCallbacksState = Facet.define<- MovementCallbacks,- MovementCallbacks->({+/**+ * State for cell id+ */+export const cellIdState = Facet.define<CellId, CellId>({combine: (values) => values[0],});++/**+ * Extension for cell config+ */+export function cellConfigExtension(+ completionConfig: CompletionConfig,+ hotkeys: HotkeyProvider,+ placeholderType: PlaceholderType,+) {+ return [+ // Store state+ completionConfigState.of(completionConfig),+ hotkeysProviderState.of(hotkeys),+ placeholderState.of(placeholderType),+ ];+}diff --git a/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.tsnew file mode 100644index 0000000000..703cbd2c32--- /dev/null+++ b/frontend/src/core/codemirror/copilot/__tests__/getCode.test.ts@@ -0,0 +1,195 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, it, expect, vi } from "vitest";+import { getTopologicalCellIds } from "../getCodes";+import { notebookAtom } from "@/core/cells/cells";+import { variablesAtom } from "@/core/variables/state";+import { store } from "@/core/state/jotai";+import { MultiColumn } from "@/utils/id-tree";+import type { CellId } from "@/core/cells/ids";+import type { VariableName, Variables } from "@/core/variables/types";+import { getCodes } from "../getCodes";+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";++import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";+import { cellConfigExtension } from "../../config/extension";+import { adaptiveLanguageConfiguration } from "../../language/extension";+const Cells = {+ cell1: "cell1" as CellId,+ cell2: "cell2" as CellId,+ cell3: "cell3" as CellId,+ cell4: "cell4" as CellId,+};++const Variables = {+ var1: "var1" as VariableName,+ var2: "var2" as VariableName,+ var3: "var3" as VariableName,+};++function createMockEditorView(code: string) {+ const view = new EditorView({+ state: EditorState.create({+ doc: code,+ extensions: [+ adaptiveLanguageConfiguration({+ cellId: "cell1" as CellId,+ completionConfig: {+ copilot: false,+ activate_on_typing: true,+ codeium_api_key: null,+ },+ hotkeys: new OverridingHotkeyProvider({}),+ placeholderType: "marimo-import",+ }),+ cellConfigExtension(+ {+ copilot: false,+ activate_on_typing: true,+ codeium_api_key: null,+ },+ new OverridingHotkeyProvider({}),+ "marimo-import",+ ),+ ],+ }),+ });++ return {+ editorView: view,+ registerRun: vi.fn(),+ };+}++describe("getTopologicalCellIds", () => {+ it("should return topologically sorted cell IDs", () => {+ // Setup mock data+ store.set(notebookAtom, {+ cellIds: MultiColumn.from([+ [Cells.cell1, Cells.cell2, Cells.cell3, Cells.cell4],+ ]),+ cellData: {},+ cellRuntime: {},+ cellHandles: {},+ history: [],+ scrollKey: null,+ cellLogs: [],+ });+ const variables: Variables = {+ [Variables.var1]: {+ name: Variables.var1,+ declaredBy: [Cells.cell1],+ usedBy: [Cells.cell2, Cells.cell3],+ },+ [Variables.var2]: {+ name: Variables.var2,+ declaredBy: [Cells.cell2],+ usedBy: [Cells.cell4],+ },+ [Variables.var3]: {+ name: Variables.var3,+ declaredBy: [Cells.cell3],+ usedBy: [],+ },+ };+ store.set(variablesAtom, variables);++ // Call the function+ const result = getTopologicalCellIds();++ // Assert the result+ expect(result).toEqual(["cell1", "cell2", "cell3", "cell4"]);+ });+});++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: [],+ });+ const otherCode = "print('Hello World')";+ const result = getCodes(otherCode);+ expect(result).toEqual("print('Hello World')");+ });++ it("should concatenate codes from multiple cells", () => {+ const otherCode = "print('Hello World')";+ const mockEditorViews = [+ createMockEditorView("import os"),+ createMockEditorView("x = 1"),+ ];+ store.set(notebookAtom, {+ 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')");+ });++ it("should sort import statements at the top", () => {+ const otherCode = "print('Hello World')";+ const mockEditorViews = [+ createMockEditorView("x = 1"),+ createMockEditorView("import os"),+ ];+ store.set(notebookAtom, {+ 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')");+ });++ it("should return topologically sorted codes", () => {+ const otherCode = "print('Hello World')";+ const mockEditorViews = [+ createMockEditorView("import os"),+ createMockEditorView("x = 1"),+ createMockEditorView("y = x + 1"),+ ];+ store.set(notebookAtom, {+ 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]: {+ name: Variables.var1,+ declaredBy: [Cells.cell1],+ usedBy: [Cells.cell2, Cells.cell3],+ },+ });+ const result = getCodes(otherCode);+ expect(result).toEqual("import os\nx = 1\ny = x + 1\nprint('Hello World')");+ });+});diff --git a/frontend/src/core/codemirror/copilot/getCodes.ts b/frontend/src/core/codemirror/copilot/getCodes.tsindex 1c9d267c0b..451b89ff05 100644--- a/frontend/src/core/codemirror/copilot/getCodes.ts+++ b/frontend/src/core/codemirror/copilot/getCodes.ts@@ -1,8 +1,18 @@/* Copyright 2024 Marimo. All rights reserved. */-import { getAllEditorViews } from "@/core/cells/cells";+import { getAllEditorViews, notebookAtom } from "@/core/cells/cells";import { getEditorCodeAsPython } from "../language/utils";+import { store } from "@/core/state/jotai";+import { variablesAtom } from "@/core/variables/state";+import type { CellId } from "@/core/cells/ids";+import { Objects } from "@/utils/objects";export function getCodes(otherCode: string) {+ const codes = getOtherCellsCode(otherCode);++ return [...codes, otherCode].join("\n");+}++export function getOtherCellsCode(otherCode: string) {// Get all other cells' code// Put `import` statements at the top, as it can help copilot give better suggestions// TODO: we should sort this topologically@@ -25,5 +35,83 @@ export function getCodes(otherCode: string) {return 0;});- return [...codes, otherCode].join("\n");+ return codes;+}++export function getTopologicalCellIds() {+ const notebook = store.get(notebookAtom);+ const variables = store.get(variablesAtom);+ const cellIds = notebook.cellIds.inOrderIds;++ // Build adjacency list+ const adjacency = new Map<CellId, CellId[]>();+ cellIds.forEach((id) => adjacency.set(id, []));++ // Link "declaredBy -> usedBy"+ for (const { declaredBy, usedBy } of Object.values(variables)) {+ if (!declaredBy || !usedBy) {+ continue;+ }+ const declArr = Array.isArray(declaredBy) ? declaredBy : [declaredBy];+ declArr.forEach((declCell) => {+ usedBy.forEach((useCell) => {+ if (useCell !== declCell) {+ adjacency.get(declCell)?.push(useCell);+ }+ });+ });+ }++ // Kahn's algorithm for topological sort+ const inDegree = new Map<CellId, number>();+ cellIds.forEach((id) => inDegree.set(id, 0));++ adjacency.forEach((targets) => {+ targets.forEach((t) => {+ inDegree.set(t, (inDegree.get(t) || 0) + 1);+ });+ });++ const queue: CellId[] = [];+ inDegree.forEach((deg, id) => {+ if (deg === 0) {+ queue.push(id);+ }+ });++ const sorted: CellId[] = [];+ while (queue.length > 0) {+ const current = queue.shift();+ if (!current) {+ break;+ }+ sorted.push(current);+ adjacency.get(current)?.forEach((t) => {+ inDegree.set(t, (inDegree.get(t) || 0) - 1);+ if (inDegree.get(t) === 0) {+ queue.push(t);+ }+ });+ }++ return sorted;+}++export function getTopologicalCodes(): {+ cellIds: CellId[];+ codes: Record<CellId, string>;+} {+ const cellIds = getTopologicalCellIds();+ const notebook = store.get(notebookAtom);+ const codes = Objects.fromEntries(+ cellIds.map((id) => {+ const handle = notebook.cellHandles[id];+ return [+ id,+ handle?.current ? getEditorCodeAsPython(handle.current.editorView) : "",+ ];+ }),+ );++ return { cellIds, codes };}diff --git a/frontend/src/core/codemirror/extensions.ts b/frontend/src/core/codemirror/extensions.tsindex c804a106dd..bd861fd1e1 100644--- a/frontend/src/core/codemirror/extensions.ts+++ b/frontend/src/core/codemirror/extensions.ts@@ -1,6 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */import { EditorView, keymap } from "@codemirror/view";-import type { CellId } from "../cells/ids";import { formatEditorViews, formattingChangeEffect } from "./format";import {getCurrentLanguageAdapter,@@ -9,23 +8,19 @@ import {import { smartScrollIntoView } from "../../utils/scroll";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { invariant } from "@/utils/invariant";-import type { CodeCallbacks } from "./cells/extensions";+import { cellActionsState, cellIdState } from "./cells/state";/*** Add a keymap to format the code in the editor.*/-export function formatKeymapExtension(- cellId: CellId,- callbacks: CodeCallbacks,- hotkeys: HotkeyProvider,-) {- const { updateCellCode, afterToggleMarkdown } = callbacks;+export function formatKeymapExtension(hotkeys: HotkeyProvider) {return keymap.of([{key: hotkeys.getHotkey("cell.format").key,preventDefault: true,run: (ev) => {- formatEditorViews({ [cellId]: ev }, updateCellCode);+ const cellId = ev.state.facet(cellIdState);+ formatEditorViews({ [cellId]: ev });return true;},},@@ -34,17 +29,24 @@ export function formatKeymapExtension(preventDefault: true,run: (ev) => {const currentLanguage = getCurrentLanguageAdapter(ev);+ // Early return if not a supported languageif (currentLanguage !== "markdown" && currentLanguage !== "python") {return false;}++ // Toggle between markdown and pythonconst destinationLanguage =currentLanguage === "python" ? "markdown" : "python";const response = toggleToLanguage(ev, destinationLanguage, {force: true,});++ // Handle post-toggle actionsif (response === "markdown") {- afterToggleMarkdown();+ const actions = ev.state.facet(cellActionsState);+ actions.afterToggleMarkdown();}+return response !== false;},},@@ -60,7 +62,7 @@ export function formatKeymapExtension(*/export function scrollActiveLineIntoView() {return EditorView.updateListener.of((update) => {- // Ignore the editor does not have focus, ignore+ // Ignore if the editor does not have focus, ignoreif (!update.view.hasFocus) {return;}diff --git a/frontend/src/core/codemirror/format.ts b/frontend/src/core/codemirror/format.tsindex 32932307e7..04dd1c4ea9 100644--- a/frontend/src/core/codemirror/format.ts+++ b/frontend/src/core/codemirror/format.ts@@ -4,7 +4,7 @@ import type { EditorView } from "@codemirror/view";import type { CellId } from "../cells/ids";import { Objects } from "../../utils/objects";import { sendFormat } from "../network/requests";-import { type CellActions, getNotebook } from "../cells/cells";+import { getNotebook } from "../cells/cells";import { notebookCellEditorViews } from "../cells/utils";import {getEditorCodeAsPython,@@ -12,6 +12,7 @@ import {} from "./language/utils";import { StateEffect } from "@codemirror/state";import { getResolvedMarimoConfig } from "../config/config";+import { cellActionsState } from "./cells/state";export const formattingChangeEffect = StateEffect.define<boolean>();@@ -19,10 +20,7 @@ export const formattingChangeEffect = StateEffect.define<boolean>();* Format the code in the editor views via the marimo server,* and update the editor views with the formatted code.*/-export async function formatEditorViews(- views: Record<CellId, EditorView>,- updateCellCode: CellActions["updateCellCode"],-) {+export async function formatEditorViews(views: Record<CellId, EditorView>) {const codes = Objects.mapValues(views, (view) => getEditorCodeAsPython(view));const formatResponse = await sendFormat({@@ -47,7 +45,12 @@ export async function formatEditorViews(continue;}- updateCellCode({ cellId, code: formattedCode, formattingChange: true });+ const actions = view.state.facet(cellActionsState);+ actions.updateCellCode({+ cellId,+ code: formattedCode,+ formattingChange: true,+ });updateEditorCodeFromPython(view, formattedCode);}}@@ -55,7 +58,7 @@ export async function formatEditorViews(/*** Format all cells in the notebook.*/-export function formatAll(updateCellCode: CellActions["updateCellCode"]) {+export function formatAll() {const views = notebookCellEditorViews(getNotebook());- return formatEditorViews(views, updateCellCode);+ return formatEditorViews(views);}diff --git a/frontend/src/core/codemirror/keymaps/keymaps.ts b/frontend/src/core/codemirror/keymaps/keymaps.tsindex 956a6e4303..b3512391a7 100644--- a/frontend/src/core/codemirror/keymaps/keymaps.ts+++ b/frontend/src/core/codemirror/keymaps/keymaps.ts@@ -7,17 +7,11 @@ import { type EditorView, keymap } from "@codemirror/view";import { getCM, vim } from "@replit/codemirror-vim";import { vimKeymapExtension } from "./vim";import { once } from "@/utils/once";+import { cellActionsState } from "../cells/state";export const KEYMAP_PRESETS = ["default", "vim"] as const;-export function keymapBundle(- config: KeymapConfig,- callbacks: {- focusUp: () => void;- focusDown: () => void;- deleteCell: () => void;- },-): Extension[] {+export function keymapBundle(config: KeymapConfig): Extension[] {switch (config.preset) {case "default":return [@@ -57,7 +51,8 @@ export function keymapBundle((view) => view.state.doc.toString() === "",(view) => {if (view.state.doc.toString() === "") {- callbacks.deleteCell();+ const actions = view.state.facet(cellActionsState);+ actions.deleteCell();return true;}return false;@@ -67,7 +62,7 @@ export function keymapBundle(// Base vim modevim({ status: false }),// Custom vim keymaps for cell navigation- Prec.high(vimKeymapExtension(callbacks)),+ Prec.high(vimKeymapExtension()),];default:logNever(config.preset);diff --git a/frontend/src/core/codemirror/keymaps/vim.ts b/frontend/src/core/codemirror/keymaps/vim.tsindex 6411f67dd6..ba2b653a09 100644--- a/frontend/src/core/codemirror/keymaps/vim.ts+++ b/frontend/src/core/codemirror/keymaps/vim.ts@@ -13,11 +13,9 @@ import { Logger } from "@/utils/Logger";import { goToDefinitionAtCursorPosition } from "../go-to-definition/utils";import { once } from "@/utils/once";import { onIdle } from "@/utils/idle";+import { cellActionsState, cellIdState } from "../cells/state";-export function vimKeymapExtension(callbacks: {- focusUp: () => void;- focusDown: () => void;-}): Extension[] {+export function vimKeymapExtension(): Extension[] {addCustomVimCommandsOnce();return [@@ -26,7 +24,9 @@ export function vimKeymapExtension(callbacks: {key: "j",run: (ev) => {if (isAtEndOfEditor(ev, true) && isInVimNormalMode(ev)) {- callbacks.focusDown();+ const actions = ev.state.facet(cellActionsState);+ const cellId = ev.state.facet(cellIdState);+ actions.moveToNextCell({ cellId, before: false });return true;}return false;@@ -38,7 +38,9 @@ export function vimKeymapExtension(callbacks: {key: "k",run: (ev) => {if (isAtStartOfEditor(ev) && isInVimNormalMode(ev)) {- callbacks.focusUp();+ const actions = ev.state.facet(cellActionsState);+ const cellId = ev.state.facet(cellIdState);+ actions.moveToNextCell({ cellId, before: true });return true;}return false;diff --git a/frontend/src/core/codemirror/language/__tests__/extension.test.ts b/frontend/src/core/codemirror/language/__tests__/extension.test.tsindex e81991e0ce..45ff2348bd 100644--- a/frontend/src/core/codemirror/language/__tests__/extension.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/extension.test.ts@@ -8,26 +8,35 @@ import {} from "../extension";import { EditorState } from "@codemirror/state";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";-import type { MovementCallbacks } from "../../cells/extensions";import { store } from "@/core/state/jotai";import { capabilitiesAtom } from "@/core/config/capabilities";import { EditorView } from "@codemirror/view";+import type { CellId } from "@/core/cells/ids";+import { cellConfigExtension } from "../../config/extension";function createState(content: string, selection?: { anchor: number }) {const state = EditorState.create({doc: content,extensions: [adaptiveLanguageConfiguration({+ cellId: "cell1" as CellId,completionConfig: {copilot: false,activate_on_typing: true,codeium_api_key: null,},hotkeys: new OverridingHotkeyProvider({}),- enableAI: true,- showPlaceholder: true,- cellMovementCallbacks: {} as MovementCallbacks,+ placeholderType: "marimo-import",}),+ cellConfigExtension(+ {+ copilot: false,+ activate_on_typing: true,+ codeium_api_key: null,+ },+ new OverridingHotkeyProvider({}),+ "marimo-import",+ ),],selection,});diff --git a/frontend/src/core/codemirror/language/__tests__/utils.test.ts b/frontend/src/core/codemirror/language/__tests__/utils.test.tsindex 389aa0d5e9..812f7fc073 100644--- a/frontend/src/core/codemirror/language/__tests__/utils.test.ts+++ b/frontend/src/core/codemirror/language/__tests__/utils.test.ts@@ -9,7 +9,8 @@ import { EditorView } from "@codemirror/view";import { describe, it, expect } from "vitest";import { adaptiveLanguageConfiguration, switchLanguage } from "../extension";import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";-import type { MovementCallbacks } from "../../cells/extensions";+import type { CellId } from "@/core/cells/ids";+import { cellConfigExtension } from "../../config/extension";function createEditor(doc: string) {return new EditorView({@@ -23,10 +24,18 @@ function createEditor(doc: string) {codeium_api_key: null,},hotkeys: new OverridingHotkeyProvider({}),- showPlaceholder: true,- enableAI: true,- cellMovementCallbacks: {} as MovementCallbacks,+ placeholderType: "marimo-import",+ cellId: "cell1" as CellId,}),+ cellConfigExtension(+ {+ activate_on_typing: true,+ copilot: false,+ codeium_api_key: null,+ },+ new OverridingHotkeyProvider({}),+ "marimo-import",+ ),],}),});diff --git a/frontend/src/core/codemirror/language/extension.ts b/frontend/src/core/codemirror/language/extension.tsindex 714953f8fd..a649e91e60 100644--- a/frontend/src/core/codemirror/language/extension.ts+++ b/frontend/src/core/codemirror/language/extension.ts@@ -15,21 +15,21 @@ import {import { clamp } from "@/utils/math";import type { CompletionConfig } from "@/core/config/config-schema";import {+ cellIdState,completionConfigState,hotkeysProviderState,- movementCallbacksState,placeholderState,+ type PlaceholderType,} from "../config/extension";import { historyCompartment } from "../editing/extensions";import { history } from "@codemirror/commands";import { formattingChangeEffect } from "../format";import { getEditorCodeAsPython } from "./utils";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";-import type { CodeMirrorSetupOpts } from "../cm";import { getLanguageAdapters, LanguageAdapters } from "./LanguageAdapters";import { createPanel } from "../react-dom/createPanel";import { LanguagePanelComponent } from "./panel";-+import type { CellId } from "@/core/cells/ids";/*** Compartment to keep track of the current language and extension.* When the language changes, the extensions inside the compartment will be updated.@@ -116,7 +116,7 @@ function updateLanguageAdapterAndCode(const completionConfig = view.state.facet(completionConfigState);const hotkeysProvider = view.state.facet(hotkeysProviderState);const placeholderType = view.state.facet(placeholderState);- const movementCallbacks = view.state.facet(movementCallbacksState);+ const cellId = view.state.facet(cellIdState);let cursor = view.state.selection.main.head;// If keepCodeAsIs is true, we just keep the original code@@ -143,10 +143,10 @@ function updateLanguageAdapterAndCode(setLanguageAdapter.of(nextLanguage),languageCompartment.reconfigure(nextLanguage.getExtension(+ cellId,completionConfig,hotkeysProvider,placeholderType,- movementCallbacks,),),// Clear history@@ -177,44 +177,23 @@ function createLanguagePanel(view: EditorView): Panel {/*** Set of extensions to enable adaptive language configuration.*/-export function adaptiveLanguageConfiguration(- opts: Pick<- CodeMirrorSetupOpts,- | "completionConfig"- | "hotkeys"- | "showPlaceholder"- | "enableAI"- | "cellMovementCallbacks"- >,-) {- const {- showPlaceholder,- enableAI,- completionConfig,- hotkeys,- cellMovementCallbacks,- } = opts;-- const placeholderType = showPlaceholder- ? "marimo-import"- : enableAI- ? "ai"- : "none";+export function adaptiveLanguageConfiguration(opts: {+ placeholderType: PlaceholderType;+ completionConfig: CompletionConfig;+ hotkeys: HotkeyProvider;+ cellId: CellId;+}) {+ const { placeholderType, completionConfig, hotkeys, cellId } = opts;return [- // Store state- completionConfigState.of(completionConfig),- hotkeysProviderState.of(hotkeys),- placeholderState.of(placeholderType),- movementCallbacksState.of(cellMovementCallbacks),// Language adapterlanguageToggle(),languageCompartment.of(LanguageAdapters.python().getExtension(+ cellId,completionConfig,hotkeys,placeholderType,- cellMovementCallbacks,),),languageAdapterState,@@ -282,13 +261,13 @@ export function reconfigureLanguageEffect() {const language = view.state.field(languageAdapterState);const placeholderType = view.state.facet(placeholderState);- const movementCallbacks = view.state.facet(movementCallbacksState);+ const cellId = view.state.facet(cellIdState);return languageCompartment.reconfigure(language.getExtension(+ cellId,completionConfig,hotkeysProvider,placeholderType,- movementCallbacks,),);}diff --git a/frontend/src/core/codemirror/language/markdown.ts b/frontend/src/core/codemirror/language/markdown.tsindex 13db20729e..56fc88c661 100644--- a/frontend/src/core/codemirror/language/markdown.ts+++ b/frontend/src/core/codemirror/language/markdown.ts@@ -17,11 +17,9 @@ import type { CompletionConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";import { indentOneTab } from "./utils/indentOneTab";import { type QuotePrefixKind, splitQuotePrefix } from "./utils/quotes";-import {- markdownAutoRunExtension,- type MovementCallbacks,-} from "../cells/extensions";+import { markdownAutoRunExtension } from "../cells/extensions";import type { PlaceholderType } from "../config/extension";+import type { CellId } from "@/core/cells/ids";const quoteKinds = [['"""', '"""'],@@ -158,10 +156,10 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {}getExtension(+ _cellId: CellId,_completionConfig: CompletionConfig,hotkeys: HotkeyProvider,_: PlaceholderType,- movementCallbacks: MovementCallbacks,): Extension[] {return [markdown({@@ -201,7 +199,7 @@ export class MarkdownLanguageAdapter implements LanguageAdapter {override: [emojiCompletionSource, lucideIconCompletionSource],}),// Markdown autorun- markdownAutoRunExtension(movementCallbacks),+ markdownAutoRunExtension(),python().support,];}diff --git a/frontend/src/core/codemirror/language/python.ts b/frontend/src/core/codemirror/language/python.tsindex 2d1cc6b890..97d10e059a 100644--- a/frontend/src/core/codemirror/language/python.ts+++ b/frontend/src/core/codemirror/language/python.ts@@ -20,8 +20,8 @@ import {smartPlaceholderExtension,clickablePlaceholderExtension,} from "../placeholder/extensions";-import type { MovementCallbacks } from "../cells/extensions";-+import type { CellId } from "@/core/cells/ids";+import { cellActionsState } from "../cells/state";/*** Language adapter for Python.*/@@ -42,10 +42,10 @@ export class PythonLanguageAdapter implements LanguageAdapter {}getExtension(+ _cellId: CellId,completionConfig: CompletionConfig,_hotkeys: HotkeyProvider,placeholderType: PlaceholderType,- cellMovementCallbacks: MovementCallbacks,): Extension[] {return [// Whether or not to require keypress to activate autocompletion (default@@ -69,7 +69,10 @@ export class PythonLanguageAdapter implements LanguageAdapter {beforeText: "Start coding or ",linkText: "generate",afterText: " with AI.",- onClick: cellMovementCallbacks.aiCellCompletion,+ onClick: (ev) => {+ const cellActions = ev.state.facet(cellActionsState);+ cellActions.aiCellCompletion();+ },}): [],];diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.tsindex 78e9fd38e5..e852c752bf 100644--- a/frontend/src/core/codemirror/language/sql.ts+++ b/frontend/src/core/codemirror/language/sql.ts@@ -1,16 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import type { Extension } from "@codemirror/state";import type { LanguageAdapter } from "./types";-import {- sql,- StandardSQL,- schemaCompletionSource,- MySQL,- PostgreSQL,- SQLite,- type SQLDialect,- type SQLConfig,-} from "@codemirror/lang-sql";import dedent from "string-dedent";import type { CompletionConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";@@ -34,6 +24,17 @@ import { parser } from "@lezer/python";import type { SyntaxNode, TreeCursor } from "@lezer/common";import { parseArgsKwargs } from "./utils/ast";import { Logger } from "@/utils/Logger";+import type { CellId } from "@/core/cells/ids";+import {+ sql,+ StandardSQL,+ type SQLConfig,+ schemaCompletionSource,+ type SQLDialect,+ PostgreSQL,+ MySQL,+ SQLite,+} from "@codemirror/lang-sql";import { LRUCache } from "@/utils/lru";import type { DataSourceConnection } from "@/core/kernel/messages";@@ -151,6 +152,7 @@ export class SQLLanguageAdapter implements LanguageAdapter {}getExtension(+ _cellId: CellId,_completionConfig: CompletionConfig,_hotkeys: HotkeyProvider,): Extension[] {diff --git a/frontend/src/core/codemirror/language/types.ts b/frontend/src/core/codemirror/language/types.tsindex 0488d02667..d9fdd5f00c 100644--- a/frontend/src/core/codemirror/language/types.ts+++ b/frontend/src/core/codemirror/language/types.ts@@ -3,7 +3,7 @@ import type { CompletionConfig } from "@/core/config/config-schema";import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";import type { Extension } from "@codemirror/state";import type { PlaceholderType } from "../config/extension";-import type { MovementCallbacks } from "../cells/extensions";+import type { CellId } from "@/core/cells/ids";/*** A language adapter is a class that can transform code from one language to@@ -17,10 +17,10 @@ export interface LanguageAdapter {transformOut(code: string): [string, number];isSupported(code: string): boolean;getExtension(+ cellId: CellId,completionConfig: CompletionConfig,hotkeys: HotkeyProvider,placeholderType: PlaceholderType,- movementCallbacks: MovementCallbacks,): Extension[];}diff --git a/frontend/src/core/codemirror/misc/__tests__/paste.test.ts b/frontend/src/core/codemirror/misc/__tests__/paste.test.tsindex 7774414ec4..f07d00f676 100644--- a/frontend/src/core/codemirror/misc/__tests__/paste.test.ts+++ b/frontend/src/core/codemirror/misc/__tests__/paste.test.ts@@ -3,8 +3,10 @@ import { describe, it, expect, vi } from "vitest";import { extractCells, pasteBundle } from "../paste";import { EditorView } from "@codemirror/view";import { EditorState } from "@codemirror/state";-import { movementCallbacksState } from "../../config/extension";-import type { MovementCallbacks } from "../../cells/extensions";+import {+ cellActionsState,+ type CodemirrorCellActions,+} from "../../cells/state";describe("extractCells", () => {it("returns empty array for non-marimo text", () => {@@ -176,9 +178,9 @@ describe("pasteBundle", () => {doc: "",extensions: [extension,- movementCallbacksState.of({+ cellActionsState.of({createManyBelow,- } as Partial<MovementCallbacks> as MovementCallbacks),+ } as never as CodemirrorCellActions),],}),});@@ -214,9 +216,9 @@ def _():doc: "",extensions: [extension,- movementCallbacksState.of({+ cellActionsState.of({createManyBelow,- } as Partial<MovementCallbacks> as MovementCallbacks),+ } as never as CodemirrorCellActions),],}),});diff --git a/frontend/src/core/codemirror/misc/paste.ts b/frontend/src/core/codemirror/misc/paste.tsindex 96c083aa43..7519d2761c 100644--- a/frontend/src/core/codemirror/misc/paste.ts+++ b/frontend/src/core/codemirror/misc/paste.ts@@ -1,7 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import type { Extension } from "@codemirror/state";import { EditorView } from "@codemirror/view";-import { movementCallbacksState } from "../config/extension";+import { cellActionsState } from "../cells/state";export function pasteBundle(): Extension[] {return [@@ -17,8 +17,8 @@ export function pasteBundle(): Extension[] {return false;}- const movementCallbacks = view.state.facet(movementCallbacksState);- movementCallbacks.createManyBelow(cells);+ const actions = view.state.facet(cellActionsState);+ actions.createManyBelow(cells);return true;},}),diff --git a/frontend/src/core/codemirror/placeholder/extensions.ts b/frontend/src/core/codemirror/placeholder/extensions.tsindex b14f7a36a9..7b252c5151 100644--- a/frontend/src/core/codemirror/placeholder/extensions.ts+++ b/frontend/src/core/codemirror/placeholder/extensions.ts@@ -53,14 +53,14 @@ export function clickablePlaceholderExtension(opts: {beforeText: string;linkText: string;afterText: string;- onClick: () => void;+ onClick: (ev: EditorView) => void;}): Extension[] {const { beforeText, linkText, afterText, onClick } = opts;// Create a placeholder// Needs to be a function to keep event listeners// See https://github.com/codemirror/dev/issues/1457- const createPlaceholder = () => {+ const createPlaceholder = (ev: EditorView) => {const placeholderText = document.createElement("span");placeholderText.append(document.createTextNode(beforeText));const link = document.createElement("span");@@ -68,7 +68,7 @@ export function clickablePlaceholderExtension(opts: {link.classList.add("cm-clickable-placeholder");link.onclick = (evt) => {evt.stopPropagation();- onClick();+ onClick(ev);};placeholderText.append(link);placeholderText.append(document.createTextNode(afterText));diff --git a/frontend/src/core/saving/save-component.tsx b/frontend/src/core/saving/save-component.tsxindex fbedd17335..8bdd5624ae 100644--- a/frontend/src/core/saving/save-component.tsx+++ b/frontend/src/core/saving/save-component.tsx@@ -5,7 +5,7 @@ import { sendSave } from "@/core/network/requests";import { FilenameInput } from "@/components/editor/header/filename-input";import { WebSocketState } from "../websocket/types";-import { useCellActions, useNotebook, getCellConfigs } from "../cells/cells";+import { useNotebook, getCellConfigs } from "../cells/cells";import { notebookCells } from "../cells/utils";import type { AppConfig } from "../config/config-schema";import { useImperativeModal } from "../../components/modal/ImperativeModal";@@ -75,9 +75,8 @@ export const SaveComponent = ({ kioskMode, appConfig }: SaveNotebookProps) => {);};-export function useSaveNotebook({ kioskMode, appConfig }: SaveNotebookProps) {+export function useSaveNotebook({ kioskMode }: SaveNotebookProps) {const autoSaveConfig = useAtomValue(autoSaveConfigAtom);- const { updateCellCode } = useCellActions();const notebook = useNotebook();const [connection] = useAtom(connectionAtom);const filename = useFilename();@@ -121,7 +120,7 @@ export function useSaveNotebook({ kioskMode, appConfig }: SaveNotebookProps) {persist: true,}).then(() => {if (userInitiated && autoSaveConfig.format_on_save) {- formatAll(updateCellCode);+ formatAll();}setLastSavedNotebook({names: cellNames,diff --git a/frontend/src/core/websocket/createWsUrl.ts b/frontend/src/core/websocket/createWsUrl.tsindex eadfb63af4..8ccd4ad809 100644--- a/frontend/src/core/websocket/createWsUrl.ts+++ b/frontend/src/core/websocket/createWsUrl.ts@@ -9,9 +9,11 @@ export function createWsUrl(sessionId: string): string {return resolveToWsUrl(`ws?${searchParams.toString()}`);}-export function resolveToWsUrl(relativeUrl: string): string {+export function resolveToWsUrl(+ relativeUrl: string,+): `ws://${string}` | `wss://${string}` {if (relativeUrl.startsWith("ws:") || relativeUrl.startsWith("wss:")) {- return relativeUrl;+ return relativeUrl as `ws://${string}` | `wss://${string}`;}const baseUri = new URL(document.baseURI);const protocol = baseUri.protocol === "https:" ? "wss:" : "ws:";diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex a885616d9f..49051b9527 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -246,7 +246,14 @@ export default defineConfig({sourcemap: isDev,},resolve: {- dedupe: ["react", "react-dom", "@emotion/react", "@emotion/cache"],+ dedupe: [+ "react",+ "react-dom",+ "@emotion/react",+ "@emotion/cache",+ "@codemirror/view",+ "@codemirror/state",+ ],},worker: {format: "es",