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: focus-up/focus-down cells with vim (#667)
Myles Scolnick2080b71a5cc7
diff --git a/frontend/e2e-tests/cells.spec.ts b/frontend/e2e-tests/cells.spec.tsindex 70b411bac8..05571e757f 100644--- a/frontend/e2e-tests/cells.spec.ts+++ b/frontend/e2e-tests/cells.spec.ts@@ -64,7 +64,7 @@ test("page renders 2 cells", async ({ page }) => {.first().click();// Type into the currently focused cell- await page.locator("*:focus").type(`mo.md("# Cell 0")`);+ await page.locator("*:focus").fill(`mo.md("# Cell 0")`);// Check the rendered cellsawait expect(page.locator("h1")).toHaveText(["Cell 1", "Cell 2"]);@@ -82,7 +82,7 @@ test("page renders 2 cells", async ({ page }) => {.locator(":visible").last().click();- await page.locator("*:focus").type(`mo.md("# Cell 1.5")`);+ await page.locator("*:focus").fill(`mo.md("# Cell 1.5")`);await page.getByTestId("run-button").locator(":visible").last().click();// Verify the rendered cellsdiff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex 32756cb208..6f89f11369 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -315,6 +315,18 @@ const CellComponent = (moveToNextCell({ cellId, before: true, noCreate: true });return true;},+ ...(userConfig.keymap.preset === "vim"+ ? {+ j: () => {+ moveToNextCell({ cellId, before: false, noCreate: true });+ return true;+ },+ k: () => {+ moveToNextCell({ cellId, before: true, noCreate: true });+ return true;+ },+ }+ : {}),});if (!editing) {diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsxindex 3d9b68dffa..beab2236d6 100644--- a/frontend/src/components/editor/renderers/CellArray.tsx+++ b/frontend/src/components/editor/renderers/CellArray.tsx@@ -90,7 +90,12 @@ export const CellArray: React.FC<CellArrayProps> = ({const cells = flattenNotebookCells(notebook);return (- <VerticalLayoutWrapper invisible={invisible} appConfig={appConfig}>+ <VerticalLayoutWrapper+ // 'pb' allows the user to put the cell in the middle of the screen+ className="pb-[40vh]"+ invisible={invisible}+ appConfig={appConfig}+ ><NotebookBanner />{cells.map((cell) => (<Celldiff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 378f60b160..70c1e5e529 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -193,11 +193,12 @@ const { reducer, createActions } = createReducer(initialNotebookState, {const focusCellId = state.cellIds[focusIndex];// can scroll immediately, without setting scrollKey in state, because// CellArray won't need to re-render- focusAndScrollCellIntoView(- focusCellId,- state.cellHandles[focusCellId],- state.cellData[focusCellId].config- );+ focusAndScrollCellIntoView({+ cellId: focusCellId,+ cell: state.cellHandles[focusCellId],+ config: state.cellData[focusCellId].config,+ codeFocus: before ? "bottom" : "top",+ });return state;},focusTopCell: (state) => {@@ -492,11 +493,12 @@ const { reducer, createActions } = createReducer(initialNotebookState, {} else {const nextCellId = state.cellIds[nextCellIndex];// Just focus, no state change- focusAndScrollCellIntoView(- nextCellId,- state.cellHandles[nextCellId],- state.cellData[nextCellId].config- );+ focusAndScrollCellIntoView({+ cellId: nextCellId,+ cell: state.cellHandles[nextCellId],+ config: state.cellData[nextCellId].config,+ codeFocus: before ? "bottom" : "top",+ });return state;}},@@ -516,11 +518,12 @@ const { reducer, createActions } = createReducer(initialNotebookState, {scrollToBottom();} else {const nextCellId = state.cellIds[index];- focusAndScrollCellIntoView(- nextCellId,- state.cellHandles[nextCellId],- state.cellData[nextCellId].config- );+ focusAndScrollCellIntoView({+ cellId: nextCellId,+ cell: state.cellHandles[nextCellId],+ config: state.cellData[nextCellId].config,+ codeFocus: undefined,+ });}return {diff --git a/frontend/src/core/cells/scrollCellIntoView.ts b/frontend/src/core/cells/scrollCellIntoView.tsindex adfe048100..573668633b 100644--- a/frontend/src/core/cells/scrollCellIntoView.ts+++ b/frontend/src/core/cells/scrollCellIntoView.ts@@ -5,11 +5,17 @@ import { CellId, HTMLCellId } from "./ids";import { CellHandle } from "@/components/editor/Cell";import { CellConfig } from "./types";-export function focusAndScrollCellIntoView(- cellId: CellId,- cell: RefObject<CellHandle>,- config: CellConfig-) {+export function focusAndScrollCellIntoView({+ cellId,+ cell,+ config,+ codeFocus,+}: {+ cellId: CellId;+ cell: RefObject<CellHandle>;+ config: CellConfig;+ codeFocus: "top" | "bottom" | undefined;+}) {if (!cell) {return;}@@ -24,7 +30,30 @@ export function focusAndScrollCellIntoView(if (config.hide_code) {element.focus();} else {- cell.current?.editorView.focus();+ const editor = cell.current?.editorView;+ if (!editor) {+ return;+ }+ editor.focus();+ if (codeFocus === "top") {+ // If codeFocus is top, move the cursor to the top of the editor.+ editor.dispatch({+ selection: {+ anchor: 0,+ head: 0,+ },+ });+ } else if (codeFocus === "bottom") {+ // If codeFocus is bottom, move the cursor to the bottom of the editor,+ // but front of the last line.+ const lastLine = editor.state.doc.line(editor.state.doc.lines);+ editor.dispatch({+ selection: {+ anchor: lastLine.from,+ head: lastLine.from,+ },+ });+ }}element.scrollIntoView({diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.tsindex fae6da3821..d5c56fbc1d 100644--- a/frontend/src/core/codemirror/cells/extensions.ts+++ b/frontend/src/core/codemirror/cells/extensions.ts@@ -8,6 +8,7 @@ import { CellActions } from "@/core/cells/cells";import { getEditorCodeAsPython } from "../language/utils";import { formattingChangeEffect } from "../format";import { closeCompletion } from "@codemirror/autocomplete";+import { isAtEndOfEditor, isAtStartOfEditor } from "../utils";export interface MovementCallbacksextends Pick<CellActions, "sendToTop" | "sendToBottom" | "moveToNextCell"> {@@ -116,8 +117,7 @@ export function cellMovementBundle(preventDefault: true,stopPropagation: true,run: (ev) => {- const main = ev.state.selection.main;- if (main.from === 0 && main.to === 0) {+ if (isAtStartOfEditor(ev)) {focusUp();return true;}@@ -129,11 +129,7 @@ export function cellMovementBundle(preventDefault: true,stopPropagation: true,run: (ev) => {- const main = ev.state.selection.main;- if (- main.from === ev.state.doc.length &&- main.to === ev.state.doc.length- ) {+ if (isAtEndOfEditor(ev)) {focusDown();return true;}diff --git a/frontend/src/core/codemirror/extensions.ts b/frontend/src/core/codemirror/extensions.tsindex cb6d999aff..dc165305ac 100644--- a/frontend/src/core/codemirror/extensions.ts+++ b/frontend/src/core/codemirror/extensions.ts@@ -5,6 +5,7 @@ import { formatEditorViews } from "./format";import { smartScrollIntoView } from "../../utils/scroll";import { HOTKEYS } from "@/core/hotkeys/hotkeys";import { CellActions } from "../cells/cells";+import { invariant } from "@/utils/invariant";function acceptPlaceholder(cm: EditorView, text: string) {// if empty, insert the placeholder@@ -86,10 +87,9 @@ export function scrollActiveLineIntoView() {// Only scroll if there is an active lineif (activeLines.length === 1) {const activeLine = activeLines[0] as HTMLElement;- smartScrollIntoView(activeLine, {- top: 30,- bottom: 120,- });+ const appEl = document.getElementById("App");+ invariant(appEl, "App not found");+ smartScrollIntoView(activeLine, { top: 30, bottom: 150 }, appEl);}}});diff --git a/frontend/src/core/codemirror/keymaps/keymaps.ts b/frontend/src/core/codemirror/keymaps/keymaps.tsindex 13a104a917..687bd9437e 100644--- a/frontend/src/core/codemirror/keymaps/keymaps.ts+++ b/frontend/src/core/codemirror/keymaps/keymaps.ts@@ -5,12 +5,15 @@ import { defaultKeymap } from "@codemirror/commands";import { Extension, Prec } from "@codemirror/state";import { EditorView, keymap } from "@codemirror/view";import { vim, Vim } from "@replit/codemirror-vim";+import { vimKeymapExtension } from "./vim";export const KEYMAP_PRESETS = ["default", "vim"] as const;export function keymapBundle(config: KeymapConfig,callbacks: {+ focusUp: () => void;+ focusDown: () => void;deleteCell: () => void;}): Extension[] {@@ -35,6 +38,7 @@ export function keymapBundle(callbacks.deleteCell();});return [+ vimKeymapExtension(callbacks),// delete the cell on double press of "d", if the cell is emptyPrec.highest(doubleCharacterListener(diff --git a/frontend/src/core/codemirror/keymaps/vim.ts b/frontend/src/core/codemirror/keymaps/vim.tsnew file mode 100644index 0000000000..e0fd9a0d27--- /dev/null+++ b/frontend/src/core/codemirror/keymaps/vim.ts@@ -0,0 +1,40 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { keymap } from "@codemirror/view";+import {+ isAtEndOfEditor,+ isAtStartOfEditor,+ isInVimNormalMode,+} from "../utils";++export function vimKeymapExtension(callbacks: {+ focusUp: () => void;+ focusDown: () => void;+}) {+ return [+ keymap.of([+ {+ key: "j",+ run: (ev) => {+ if (isAtEndOfEditor(ev, true) && isInVimNormalMode(ev)) {+ callbacks.focusDown();+ return true;+ }+ return false;+ },+ },+ ]),+ keymap.of([+ {+ key: "k",+ run: (ev) => {+ if (isAtStartOfEditor(ev) && isInVimNormalMode(ev)) {+ callbacks.focusUp();+ return true;+ }+ return false;+ },+ },+ ]),+ ];+}diff --git a/frontend/src/core/codemirror/utils.ts b/frontend/src/core/codemirror/utils.tsnew file mode 100644index 0000000000..b4a54aece7--- /dev/null+++ b/frontend/src/core/codemirror/utils.ts@@ -0,0 +1,38 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { getCM } from "@replit/codemirror-vim";++export function isAtStartOfEditor(ev: { state: EditorState }) {+ const main = ev.state.selection.main;+ return main.from === 0 && main.to === 0;+}++/**+ * Check if the cursor is at the end of the editor.+ *+ * If Vim is enabled, we also allow the second to last character to be selected,+ * since Vim's "normal" mode will select the last character.+ */+export function isAtEndOfEditor(ev: { state: EditorState }, isVim = false) {+ const main = ev.state.selection.main;+ const docLength = ev.state.doc.length;++ if (isVim && main.from === docLength - 1 && main.to === docLength - 1) {+ return true;+ }++ return main.from === docLength && main.to === docLength;+}++export function isInVimNormalMode(ev: EditorView): boolean {+ const vimState = getCM(ev)?.state.vim;+ if (!vimState) {+ return false;+ }+ // If mode is not defined, check 'insertMode' and 'visualMode' instead+ if (!vimState.mode && !vimState.insertMode && !vimState.visualMode) {+ return true;+ }+ return vimState.mode === "normal";+}diff --git a/frontend/src/utils/scroll.ts b/frontend/src/utils/scroll.tsindex 154fe8c680..61ae9790ab 100644--- a/frontend/src/utils/scroll.ts+++ b/frontend/src/utils/scroll.ts@@ -5,7 +5,8 @@*/export function smartScrollIntoView(element: HTMLElement,- offset?: { top: number; bottom: number }+ offset?: { top: number; bottom: number },+ body: HTMLElement | typeof window = window) {const topOffset = offset?.top ?? 0;const bottomOffset = offset?.bottom ?? 0;@@ -13,14 +14,14 @@ export function smartScrollIntoView(if (rect.top < topOffset) {// Element is above the viewport, scroll to its top- window.scrollBy({+ body.scrollBy({top: rect.top - topOffset,behavior: "smooth",});return;} else if (rect.bottom > window.innerHeight - bottomOffset) {// Element is below the viewport, scroll to its bottom- window.scrollBy({+ body.scrollBy({top: rect.bottom - window.innerHeight + bottomOffset,behavior: "smooth",});