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
consolidate / cleanup cell keyboard props (#5631)
Myles Scolnick16d779c2d058
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex a0a2d2930a..6453e2c7c7 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, useAtomValue, useSetAtom, useStore } from "jotai";+import { useAtom, useAtomValue, useSetAtom } from "jotai";import { ScopeProvider } from "jotai-scope";import {HelpCircleIcon,@@ -33,9 +33,8 @@ import type { LanguageAdapterType } from "@/core/codemirror/language/types";import { canCollapseOutline } from "@/core/dom/outline";import { isErrorMime } from "@/core/mime";import type { AppMode } from "@/core/mode";-import { saveCellConfig, sendStdin } from "@/core/network/requests";+import { sendStdin } from "@/core/network/requests";import type { CellConfig, RuntimeState } from "@/core/network/types";-import { useHotkeysOnElement } from "@/hooks/useHotkey";import { useResizeObserver } from "@/hooks/useResizeObserver";import { cn } from "@/utils/cn";import type { Milliseconds, Seconds } from "@/utils/time";@@ -73,9 +72,9 @@ import { RunButton } from "./cell/RunButton";import { useRunCell } from "./cell/useRunCells";import { HideCodeButton } from "./code/readonly-python-code";import { cellDomProps } from "./common";-import { useCellNavigationProps } from "./focus/focus";-import { focusCell, focusCellEditor } from "./focus/focus-manager";-import { temporarilyShownCodeAtom } from "./focus/state";+import { useCellNavigationProps } from "./navigation/navigation";++import { temporarilyShownCodeAtom } from "./navigation/state";import { OutputArea } from "./Output";import { ConsoleOutput } from "./output/ConsoleOutput";import { CellDragHandle, SortableCell } from "./SortableCell";@@ -134,93 +133,6 @@ function useCellCompletion(};}-/**- * Hook for handling cell hotkeys- */-function useCellHotkeys({- cellRef,- cellId,- runCell,- actions,- canMoveX,- cellConfig,- editorView,- setAiCompletionCell,- cellActionDropdownRef,-}: {- cellRef: React.RefObject<HTMLDivElement | null> | null;- cellId: CellId;- runCell: () => void;- actions: CellComponentActions;- canMoveX: boolean;- cellConfig: CellConfig;- editorView: React.RefObject<EditorView | null>;- setAiCompletionCell: ReturnType<- typeof useSetAtom<typeof aiCompletionCellAtom>- >;- cellActionDropdownRef: React.RefObject<CellActionsDropdownHandle | null>;-}) {- const store = useStore();- useHotkeysOnElement(cellRef, {- "cell.run": runCell,- "cell.runAndNewBelow": () => {- runCell();- actions.moveToNextCell({ cellId, before: false });- },- "cell.runAndNewAbove": () => {- runCell();- actions.moveToNextCell({ cellId, before: true });- },- "cell.createAbove": () => actions.createNewCell({ cellId, before: true }),- "cell.createBelow": () => actions.createNewCell({ cellId, before: false }),- "cell.moveUp": () => actions.moveCell({ cellId, before: true }),- "cell.moveDown": () => actions.moveCell({ cellId, before: false }),- "cell.moveLeft": () =>- canMoveX ? actions.moveCell({ cellId, direction: "left" }) : undefined,- "cell.moveRight": () =>- canMoveX ? actions.moveCell({ cellId, direction: "right" }) : undefined,- "cell.hideCode": () => {- const nextHideCode = !cellConfig.hide_code;- // Fire-and-forget- void saveCellConfig({- 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 cell- editorView.current?.contentDOM.blur();- focusCell(cellId);- } else {- focusCellEditor(store, cellId);- }- },- "cell.focusDown": () =>- actions.moveToNextCell({ cellId, before: false, noCreate: true }),- "cell.focusUp": () =>- actions.moveToNextCell({ cellId, before: true, noCreate: true }),- "cell.sendToBottom": () => actions.sendToBottom({ cellId }),- "cell.sendToTop": () => actions.sendToTop({ cellId }),- "cell.aiCompletion": () => {- let closed = false;- setAiCompletionCell((v) => {- // Toggle close- if (v?.cellId === cellId) {- closed = true;- return null;- }- return { cellId };- });- if (closed) {- derefNotNull(editorView).focus();- }- },- "cell.cellActions": () => {- cellActionDropdownRef.current?.toggle();- },- });-}-/*** Hook for handling hidden cell logic.*@@ -590,20 +502,12 @@ const EditableCellComponent = ({editorViewParentRef,});- // Hotkey listeners- useCellHotkeys({- cellRef,- cellId,- runCell,- actions,+ // Hotkey and focus props+ const navigationProps = useCellNavigationProps(cellId, {canMoveX,- cellConfig,editorView,- setAiCompletionCell,cellActionDropdownRef,});-- const navigationProps = useCellNavigationProps(cellId);const canCollapse = canCollapseOutline(outline);const hasOutput = !isOutputEmpty(output);const hasConsoleOutput = consoleOutputs.length > 0;@@ -1140,20 +1044,12 @@ const SetupCellComponent = ({editorView,);- // Hotkey listeners- useCellHotkeys({- cellRef,- cellId,- runCell,- actions,+ // Hotkeys and focus props+ const navigationProps = useCellNavigationProps(cellId, {canMoveX,- cellConfig,editorView,- setAiCompletionCell,cellActionDropdownRef,});-- const navigationProps = useCellNavigationProps(cellId);const hasOutput = !isOutputEmpty(output);const hasConsoleOutput = consoleOutputs.length > 0;const isErrorOutput = isErrorMime(output?.mimetype);diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsxindex 7038a93e4a..47e48dcbfd 100644--- a/frontend/src/components/editor/cell/code/cell-editor.tsx+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx@@ -37,7 +37,7 @@ import { invariant } from "@/utils/invariant";import { mergeRefs } from "@/utils/mergeRefs";import { AiCompletionEditor } from "../../ai/ai-completion-editor";import { HideCodeButton } from "../../code/readonly-python-code";-import { useCellEditorNavigationProps } from "../../focus/focus";+import { useCellEditorNavigationProps } from "../../navigation/navigation";import { useDeleteCellCallback } from "../useDeleteCell";import { useSplitCellCallback } from "../useSplitCell";import { LanguageToggles } from "./language-toggle";diff --git a/frontend/src/components/editor/focus/focus.ts b/frontend/src/components/editor/focus/focus.tsdeleted file mode 100644index facbd25ea3..0000000000--- a/frontend/src/components/editor/focus/focus.ts+++ /dev/null@@ -1,186 +0,0 @@-/* Copyright 2024 Marimo. All rights reserved. */--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";-import type { CellId } from "@/core/cells/ids";-import { hotkeysAtom, keymapPresetAtom } from "@/core/config/config";-import type { HotkeyAction } from "@/core/hotkeys/hotkeys";-import { parseShortcut } from "@/core/hotkeys/shortcuts";-import { useSaveNotebook } from "@/core/saving/save-component";-import { Events } from "@/utils/events";-import { useRunCell } from "../cell/useRunCells";-import { useCellClipboard } from "./clipboard";-import { focusCell, focusCellEditor } from "./focus-manager";-import { temporarilyShownCodeAtom } from "./state";--/**- * Props for cell keyboard navigation,- * to manage focus and selection.- *- * Handles both keyboard and mouse navigation.- *- * Includes some relevant Jupyter command mode:- * https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Notebook%20Basics.html#Keyboard-Navigation- */-export function useCellNavigationProps(cellId: CellId) {- const setLastFocusedCellId = useSetLastFocusedCellId();- const { saveOrNameNotebook } = useSaveNotebook();- const actions = useCellActions();- const store = useStore();- const setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);- const runCell = useRunCell(cellId);- const keymapPreset = useAtomValue(keymapPresetAtom);- const { copyCell, pasteCell } = useCellClipboard();- const hotkeys = useAtomValue(hotkeysAtom);-- const isShortcutPressed = (- shortcut: HotkeyAction,- evt: React.KeyboardEvent<HTMLElement>,- ) => parseShortcut(hotkeys.getHotkey(shortcut).key)(evt.nativeEvent || evt);-- // This occurs at the cell level and descedants.- const { focusWithinProps } = useFocusWithin({- onFocusWithin: () => {- // On focus, set the last focused cell id.- setLastFocusedCellId(cellId);- },- onBlurWithin: () => {- // On blur, hide the code if it was temporarily shown.- setTemporarilyShownCode(false);- actions.markTouched({ cellId });- },- });-- const { keyboardProps } = useKeyboard({- onKeyDown: (evt) => {- // Event came from an input, do nothing.- if (Events.fromInput(evt)) {- evt.continuePropagation();- return;- }-- // Copy cell- if (isShortcutPressed("command.copyCell", evt)) {- copyCell(cellId);- evt.preventDefault();- return;- }-- // Paste cell- if (isShortcutPressed("command.pasteCell", evt)) {- pasteCell(cellId);- evt.preventDefault();- return;- }-- // Mod+Up/Down moves to the top/bottom of the notebook.- if (Events.isMetaOrCtrl(evt)) {- if (evt.key === "ArrowUp") {- actions.focusTopCell();- return;- }- if (evt.key === "ArrowDown") {- actions.focusBottomCell();- return;- }- }- // Down arrow moves to the next cell.- if (evt.key === "ArrowDown" && !Events.hasModifier(evt)) {- actions.focusCell({ cellId, before: false });- return;- }- // Up arrow moves to the previous cell.- if (evt.key === "ArrowUp" && !Events.hasModifier(evt)) {- actions.focusCell({ cellId, before: true });- return;- }-- // Shift-Enter will run the cell and move to the next cell.- if (isShortcutPressed("cell.runAndNewBelow", evt)) {- runCell();- actions.focusCell({ cellId, before: false });- evt.preventDefault();- return;- }-- // Enter will focus the cell editor.- if (evt.key === "Enter") {- setTemporarilyShownCode(true);- focusCellEditor(store, cellId);- // Prevent default to prevent an new line from being created.- evt.preventDefault();- return;- }-- // Saving- if (evt.key === "s") {- saveOrNameNotebook();- return;- }-- // Create cell before- if (- isShortcutPressed("command.createCellBefore", evt) &&- !Events.hasModifier(evt)- ) {- actions.createNewCell({- cellId,- before: true,- autoFocus: true,- });- }- // Create cell after- if (- isShortcutPressed("command.createCellAfter", evt) &&- !Events.hasModifier(evt)- ) {- actions.createNewCell({- cellId,- before: false,- autoFocus: true,- });- }-- // j/k movement in vim mode.- if (keymapPreset === "vim") {- if (evt.key === "j" && !Events.hasModifier(evt)) {- actions.focusCell({ cellId, before: false });- return;- }- if (evt.key === "k" && !Events.hasModifier(evt)) {- actions.focusCell({ cellId, before: true });- return;- }- }-- evt.continuePropagation();- },- });-- return mergeProps(focusWithinProps, keyboardProps);-}--/**- * Props for cell editor navigation,- * to manage focus and selection.- *- * Handles both keyboard and mouse navigation.- */-export function useCellEditorNavigationProps(cellId: CellId) {- const setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);-- const { keyboardProps } = useKeyboard({- onKeyDown: (evt) => {- if (evt.key === "Escape") {- setTemporarilyShownCode(false);- focusCell(cellId);- }-- evt.continuePropagation();- },- });-- return keyboardProps;-}diff --git a/frontend/src/components/editor/focus/__tests__/clipboard.test.ts b/frontend/src/components/editor/navigation/__tests__/clipboard.test.tssimilarity index 100%rename from frontend/src/components/editor/focus/__tests__/clipboard.test.tsrename to frontend/src/components/editor/navigation/__tests__/clipboard.test.tsdiff --git a/frontend/src/components/editor/focus/__tests__/focus.test.ts b/frontend/src/components/editor/navigation/__tests__/navigation.test.tssimilarity index 81%rename from frontend/src/components/editor/focus/__tests__/focus.test.tsrename to frontend/src/components/editor/navigation/__tests__/navigation.test.tsindex 63b319321b..b9046d2613 100644--- a/frontend/src/components/editor/focus/__tests__/focus.test.ts+++ b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts@@ -1,16 +1,23 @@/* Copyright 2024 Marimo. All rights reserved. */// @vitest-environment jsdom+import type { EditorView } from "@codemirror/view";import { act, renderHook } from "@testing-library/react";+import { createRef } from "react";import { beforeEach, describe, expect, it, vi } from "vitest";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 { CellActionsDropdownHandle } from "../../cell/cell-actions";+import {+ useCellEditorNavigationProps,+ useCellNavigationProps,+} from "../navigation";// Mock only the essential dependencies that we need to control-vi.mock("@/core/cells/cells", () => ({+vi.mock("@/core/cells/cells", async (importOriginal) => ({+ ...(await importOriginal()),useCellActions: vi.fn(),}));@@ -30,7 +37,7 @@ vi.mock("../clipboard", () => ({useCellClipboard: vi.fn(),}));-vi.mock("../focus-manager", () => ({+vi.mock("../focus-utils", () => ({focusCellEditor: vi.fn(),focusCell: vi.fn(),}));@@ -52,7 +59,7 @@ const mockUseCellClipboard = vi.mocked(await import("../clipboard"),).useCellClipboard;-import { focusCell, focusCellEditor } from "../focus-manager";+import { focusCell, focusCellEditor } from "../focus-utils";describe("useCellNavigationProps", () => {const mockCellId = "test-cell-id" as CellId;@@ -90,9 +97,17 @@ describe("useCellNavigationProps", () => {});});+ const options = {+ canMoveX: false,+ editorView: createRef<EditorView>(),+ cellActionDropdownRef: createRef<CellActionsDropdownHandle>(),+ };+describe("keyboard shortcuts", () => {it("should copy cell when 'c' key is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "c" });@@ -108,7 +123,9 @@ describe("useCellNavigationProps", () => {});it("should paste cell when 'v' key is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "v" });@@ -123,7 +140,9 @@ describe("useCellNavigationProps", () => {});it("should move to next cell when ArrowDown is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "ArrowDown" });@@ -140,7 +159,9 @@ describe("useCellNavigationProps", () => {});it("should move to previous cell when ArrowUp is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "ArrowUp" });@@ -157,7 +178,9 @@ describe("useCellNavigationProps", () => {});it("should focus cell editor when Enter is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "Enter", shiftKey: false });@@ -175,7 +198,9 @@ describe("useCellNavigationProps", () => {});it("should run cell and move to next when Shift+Enter is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "Enter", shiftKey: true });@@ -186,7 +211,7 @@ describe("useCellNavigationProps", () => {});expect(mockRunCell).toHaveBeenCalled();- expect(mockCellActions.focusCell).toHaveBeenCalledWith({+ expect(mockCellActions.moveToNextCell).toHaveBeenCalledWith({cellId: mockCellId,before: false,});@@ -194,7 +219,9 @@ describe("useCellNavigationProps", () => {});it("should save notebook when 's' key is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "s" });@@ -208,7 +235,9 @@ describe("useCellNavigationProps", () => {});it("should create cell before when 'a' key is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "a" });@@ -226,7 +255,9 @@ describe("useCellNavigationProps", () => {});it("should create cell after when 'b' key is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "b" });@@ -244,7 +275,9 @@ describe("useCellNavigationProps", () => {});it("should move to top cell when Cmd+ArrowUp is pressed (or Ctrl)", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "ArrowUp", ctrlKey: true });@@ -258,7 +291,9 @@ describe("useCellNavigationProps", () => {});it("should move to bottom cell when Cmd+ArrowDown is pressed (or Ctrl)", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({key: "ArrowDown",@@ -275,7 +310,9 @@ describe("useCellNavigationProps", () => {});it("should move to top cell when Ctrl+ArrowUp is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({ key: "ArrowUp", ctrlKey: true });@@ -289,7 +326,9 @@ describe("useCellNavigationProps", () => {});it("should move to bottom cell when Ctrl+ArrowDown is pressed", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({key: "ArrowDown",@@ -308,7 +347,9 @@ describe("useCellNavigationProps", () => {describe("input event handling", () => {it("should ignore events from input elements", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({key: "c",@@ -328,7 +369,9 @@ describe("useCellNavigationProps", () => {describe("unknown keys", () => {it("should continue propagation for unknown keys", () => {- const { result } = renderHook(() => useCellNavigationProps(mockCellId));+ const { result } = renderHook(() =>+ useCellNavigationProps(mockCellId, options),+ );const mockEvent = Mocks.keyboardEvent({key: "x",diff --git a/frontend/src/components/editor/focus/clipboard.ts b/frontend/src/components/editor/navigation/clipboard.tssimilarity index 100%rename from frontend/src/components/editor/focus/clipboard.tsrename to frontend/src/components/editor/navigation/clipboard.tsdiff --git a/frontend/src/components/editor/focus/focus-manager.ts b/frontend/src/components/editor/navigation/focus-utils.tssimilarity index 100%rename from frontend/src/components/editor/focus/focus-manager.tsrename to frontend/src/components/editor/navigation/focus-utils.tsdiff --git a/frontend/src/components/editor/navigation/navigation.ts b/frontend/src/components/editor/navigation/navigation.tsnew file mode 100644index 0000000000..b1af667601--- /dev/null+++ b/frontend/src/components/editor/navigation/navigation.ts@@ -0,0 +1,353 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { EditorView } from "@codemirror/view";+import { useAtomValue, useSetAtom, useStore } from "jotai";+import { mergeProps, useFocusWithin, useKeyboard } from "react-aria";+import { aiCompletionCellAtom } from "@/core/ai/state";+import { notebookAtom, useCellActions } from "@/core/cells/cells";+import { useSetLastFocusedCellId } from "@/core/cells/focus";+import type { CellId } from "@/core/cells/ids";+import { hotkeysAtom, keymapPresetAtom } from "@/core/config/config";+import type { HotkeyAction } from "@/core/hotkeys/hotkeys";+import { parseShortcut } from "@/core/hotkeys/shortcuts";+import { saveCellConfig } from "@/core/network/requests";+import { useSaveNotebook } from "@/core/saving/save-component";+import { derefNotNull } from "@/utils/dereference";+import { Events } from "@/utils/events";+import type { CellActionsDropdownHandle } from "../cell/cell-actions";+import { useRunCell } from "../cell/useRunCells";+import { useCellClipboard } from "./clipboard";+import { focusCell, focusCellEditor } from "./focus-utils";+import { temporarilyShownCodeAtom } from "./state";++interface HotkeyHandler {+ handle: (cellId: CellId) => boolean;+ bulkHandle: (cellIds: CellId[]) => boolean;+}++/**+ * Wraps a hotkey handler to support bulk handling.+ *+ * If a handler fails mid-way, the bulk handling will stop.+ */+function supportBulkHandle(handler: HotkeyHandler["handle"]): HotkeyHandler {+ return {+ handle: (cellId) => {+ return handler(cellId);+ },+ bulkHandle: (cellIds) => {+ let success = true;+ try {+ for (const cellId of cellIds) {+ success = success && handler(cellId);+ }+ return success;+ } catch {+ return false;+ }+ },+ };+}++function useCellFocusProps(cellId: CellId) {+ const setLastFocusedCellId = useSetLastFocusedCellId();+ const actions = useCellActions();+ const setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);++ // This occurs at the cell level and descedants.+ const { focusWithinProps } = useFocusWithin({+ onFocusWithin: () => {+ // On focus, set the last focused cell id.+ setLastFocusedCellId(cellId);+ },+ onBlurWithin: () => {+ // On blur, hide the code if it was temporarily shown.+ setTemporarilyShownCode(false);+ actions.markTouched({ cellId });+ },+ });++ return focusWithinProps;+}++/**+ * Props for cell keyboard navigation,+ * to manage focus and selection.+ *+ * Handles both keyboard and mouse navigation.+ *+ * Includes some relevant Jupyter command mode:+ * https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Notebook%20Basics.html#Keyboard-Navigation+ */+export function useCellNavigationProps(+ cellId: CellId,+ {+ canMoveX,+ editorView,+ cellActionDropdownRef,+ }: {+ canMoveX: boolean;+ editorView: React.RefObject<EditorView | null>;+ cellActionDropdownRef: React.RefObject<CellActionsDropdownHandle | null>;+ },+) {+ const { saveOrNameNotebook } = useSaveNotebook();+ const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);+ const actions = useCellActions();+ const store = useStore();+ const setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);+ const runCell = useRunCell(cellId);+ const keymapPreset = useAtomValue(keymapPresetAtom);+ const { copyCell, pasteCell } = useCellClipboard();+ const hotkeys = useAtomValue(hotkeysAtom);++ const isShortcutPressed = (+ shortcut: HotkeyAction,+ evt: React.KeyboardEvent<HTMLElement>,+ ) => parseShortcut(hotkeys.getHotkey(shortcut).key)(evt.nativeEvent || evt);++ // Callbacks occur at the cell level and descedants.+ const focusWithinProps = useCellFocusProps(cellId);++ const { keyboardProps } = useKeyboard({+ onKeyDown: (evt) => {+ // Event came from an input, do nothing.+ if (Events.fromInput(evt)) {+ evt.continuePropagation();+ return;+ }++ // Mod+Up/Down moves to the top/bottom of the notebook.+ if (Events.isMetaOrCtrl(evt)) {+ if (evt.key === "ArrowUp") {+ actions.focusTopCell();+ return;+ }+ if (evt.key === "ArrowDown") {+ actions.focusBottomCell();+ return;+ }+ }++ // Enter will focus the cell editor.+ if (evt.key === "Enter" && !Events.hasModifier(evt)) {+ setTemporarilyShownCode(true);+ focusCellEditor(store, cellId);+ // Prevent default to prevent an new line from being created.+ evt.preventDefault();+ return;+ }++ // Saving+ if (evt.key === "s" && !Events.hasModifier(evt)) {+ saveOrNameNotebook();+ return;+ }++ // j/k movement in vim mode.+ if (keymapPreset === "vim") {+ if (evt.key === "j" && !Events.hasModifier(evt)) {+ actions.focusCell({ cellId, before: false });+ return;+ }+ if (evt.key === "k" && !Events.hasModifier(evt)) {+ actions.focusCell({ cellId, before: true });+ return;+ }+ }++ // Down arrow moves to the next cell.+ if (evt.key === "ArrowDown" && !Events.hasModifier(evt)) {+ actions.focusCell({ cellId, before: false });+ return;+ }+ // Up arrow moves to the previous cell.+ if (evt.key === "ArrowUp" && !Events.hasModifier(evt)) {+ actions.focusCell({ cellId, before: true });+ return;+ }++ // Shortcuts+ const shortcuts: Partial<+ Record<HotkeyAction, HotkeyHandler["handle"] | HotkeyHandler>+ > = {+ // Cell actions+ "cell.run": () => {+ runCell();+ return true;+ },+ "cell.runAndNewBelow": (cellId) => {+ runCell();+ actions.moveToNextCell({ cellId, before: false });+ return true;+ },+ "cell.runAndNewAbove": () => {+ runCell();+ actions.moveToNextCell({ cellId, before: true });+ return true;+ },+ "cell.createAbove": (cellId) => {+ actions.createNewCell({ cellId, before: true });+ return true;+ },+ "cell.createBelow": (cellId) => {+ actions.createNewCell({ cellId, before: false });+ return true;+ },+ "cell.moveUp": (cellId) => {+ actions.moveCell({ cellId, before: true });+ return true;+ },+ "cell.moveDown": (cellId) => {+ actions.moveCell({ cellId, before: false });+ return true;+ },+ "cell.moveLeft": (cellId) => {+ if (canMoveX) {+ actions.moveCell({ cellId, direction: "left" });+ return true;+ }+ return false;+ },+ "cell.moveRight": (cellId) => {+ if (canMoveX) {+ actions.moveCell({ cellId, direction: "right" });+ return true;+ }+ return false;+ },+ "cell.hideCode": supportBulkHandle((cellId) => {+ const cellConfig = store.get(notebookAtom).cellData[cellId]?.config;+ if (!cellConfig) {+ return false;+ }+ const nextHideCode = !cellConfig.hide_code;+ // Fire-and-forget+ void saveCellConfig({+ 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 cell+ editorView.current?.contentDOM.blur();+ focusCell(cellId);+ } else {+ focusCellEditor(store, cellId);+ }+ return true;+ }),+ "cell.focusDown": (cellId) => {+ actions.focusCell({ cellId, before: false });+ return true;+ },+ "cell.focusUp": (cellId) => {+ actions.focusCell({ cellId, before: true });+ return true;+ },+ "cell.sendToBottom": (cellId) => {+ actions.sendToBottom({ cellId });+ return true;+ },+ "cell.sendToTop": (cellId) => {+ actions.sendToTop({ cellId });+ return true;+ },+ "cell.aiCompletion": (cellId) => {+ let closed = false;+ setAiCompletionCell((v) => {+ // Toggle close+ if (v?.cellId === cellId) {+ closed = true;+ return null;+ }+ return { cellId };+ });+ if (closed) {+ derefNotNull(editorView).focus();+ }+ return true;+ },+ "cell.cellActions": () => {+ cellActionDropdownRef.current?.toggle();+ return true;+ },++ // Command mode+ "command.copyCell": () => {+ copyCell(cellId);+ return true;+ },+ "command.pasteCell": () => {+ pasteCell(cellId);+ return true;+ },+ "command.createCellBefore": (cellId) => {+ if (Events.hasModifier(evt)) {+ return false;+ }+ actions.createNewCell({ cellId, before: true, autoFocus: true });+ return true;+ },+ "command.createCellAfter": (cellId) => {+ if (Events.hasModifier(evt)) {+ return false;+ }+ actions.createNewCell({ cellId, before: false, autoFocus: true });+ return true;+ },+ };++ // Handle the shortcut+ for (const [shortcut, handler] of Object.entries(shortcuts)) {+ if (isShortcutPressed(shortcut as HotkeyAction, evt)) {+ if (handler instanceof Function) {+ const success = handler(cellId);+ if (success) {+ evt.preventDefault();+ return;+ }+ } else {+ // TODO: Support bulk handling once we have multi-select.+ const success = handler.handle(cellId);+ if (success) {+ evt.preventDefault();+ return;+ }+ }+ return;+ }+ }++ evt.continuePropagation();+ },+ });++ return mergeProps(focusWithinProps, keyboardProps);+}++/**+ * Props for cell editor navigation,+ * to manage focus and selection.+ *+ * Handles both keyboard and mouse navigation.+ */+export function useCellEditorNavigationProps(cellId: CellId) {+ const setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);++ const { keyboardProps } = useKeyboard({+ onKeyDown: (evt) => {+ if (evt.key === "Escape") {+ setTemporarilyShownCode(false);+ focusCell(cellId);+ }++ evt.continuePropagation();+ },+ });++ return keyboardProps;+}diff --git a/frontend/src/components/editor/focus/state.ts b/frontend/src/components/editor/navigation/state.tssimilarity index 100%rename from frontend/src/components/editor/focus/state.tsrename to frontend/src/components/editor/navigation/state.tsdiff --git a/frontend/src/core/cells/scrollCellIntoView.ts b/frontend/src/core/cells/scrollCellIntoView.tsindex 4f7c287f59..8458d51698 100644--- a/frontend/src/core/cells/scrollCellIntoView.ts+++ b/frontend/src/core/cells/scrollCellIntoView.ts@@ -4,7 +4,7 @@ import type { CellHandle } from "@/components/editor/Cell";import {isAnyCellFocused,tryFocus,-} from "@/components/editor/focus/focus-manager";+} from "@/components/editor/navigation/focus-utils";import { retryWithTimeout } from "@/utils/timeout";import { Logger } from "../../utils/Logger";import { goToVariableDefinition } from "../codemirror/go-to-definition/commands";