Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: navigation, copy/paste, new cells hotkeys when on a cell (#5620)

Myles Scolnick0b7417190116
diff --git a/frontend/.eslintrc.cjs b/frontend/.eslintrc.cjs
index 2081cce314..5a6943ddf4 100644
--- a/frontend/.eslintrc.cjs
+++ b/frontend/.eslintrc.cjs
@@ -180,6 +180,7 @@ module.exports = {
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/require-await": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
+ "@typescript-eslint/unbound-method": "off",
"typescript-eslint/no-unsafe-return": "off",
},
},
diff --git a/frontend/src/__mocks__/common.ts b/frontend/src/__mocks__/common.ts
new file mode 100644
index 0000000000..bcd7284a2f
--- /dev/null
+++ b/frontend/src/__mocks__/common.ts
@@ -0,0 +1,158 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable no-console */
+import { type Mock, vi } from "vitest";
+import { invariant } from "@/utils/invariant";
+
+// Common mock factories
+export const Mocks = {
+ quietLogger: () => ({
+ debug: vi.fn(),
+ log: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ trace: vi.fn(),
+ get: vi.fn().mockImplementation(() => Mocks.quietLogger()),
+ disabled: vi.fn(),
+ }),
+
+ logger: () => ({
+ debug: vi.fn().mockImplementation(console.debug),
+ log: vi.fn().mockImplementation(console.log),
+ warn: vi.fn().mockImplementation(console.warn),
+ error: vi.fn().mockImplementation(console.error),
+ trace: vi.fn().mockImplementation(console.trace),
+ get: vi.fn().mockImplementation(() => Mocks.logger()),
+ disabled: vi.fn(),
+ }),
+
+ toast: vi.fn(),
+
+ clipboard: () => ({
+ write: vi.fn(),
+ writeText: vi.fn(),
+ read: vi.fn(),
+ readText: vi.fn(),
+ }),
+
+ clipboardItem: (data: Record<string, string>) => ({
+ types: Object.keys(data),
+ getType: vi
+ .fn()
+ .mockImplementation((type: string) =>
+ Promise.resolve(new Blob([data[type]?.toString() || ""], { type })),
+ ),
+ supports: vi.fn().mockReturnValue(true),
+ }),
+
+ blob: (parts?: string[], options?: { type?: string }) => ({
+ text: () => Promise.resolve(parts?.[0] || ""),
+ type: options?.type || "text/plain",
+ }),
+
+ event: <T extends React.SyntheticEvent>(props: Partial<T> = {}) => ({
+ preventDefault: vi.fn(),
+ continuePropagation: vi.fn(),
+ target: document.createElement("div"),
+ currentTarget: document.createElement("div"),
+ stopPropagation: vi.fn(),
+ ...props,
+ }),
+
+ keyboardEvent: (
+ props: Partial<React.KeyboardEvent> = {},
+ ): React.KeyboardEvent<HTMLElement> & {
+ continuePropagation: () => void;
+ } =>
+ Mocks.event({
+ ...props,
+ }) as unknown as React.KeyboardEvent<HTMLElement> & {
+ continuePropagation: () => void;
+ },
+};
+
+// Global mock setup functions
+export const SetupMocks = {
+ clipboard: (mockClipboard = Mocks.clipboard()) => {
+ Object.defineProperty(navigator, "clipboard", {
+ value: mockClipboard,
+ writable: true,
+ });
+
+ // Mock ClipboardItem
+ // @ts-expect-error - ClipboardItem types not exact
+ global.ClipboardItem = vi
+ .fn()
+ .mockImplementation((data) => Mocks.clipboardItem(data));
+
+ // Mock Blob
+ global.Blob = vi
+ .fn()
+ .mockImplementation((parts, options) => Mocks.blob(parts, options));
+
+ return mockClipboard;
+ },
+
+ localStorage: () => {
+ const store: Record<string, string> = {};
+
+ Object.defineProperty(window, "localStorage", {
+ value: {
+ getItem: vi.fn((key: string) => store[key] || null),
+ setItem: vi.fn((key: string, value: string) => {
+ store[key] = value;
+ }),
+ removeItem: vi.fn((key: string) => {
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
+ delete store[key];
+ }),
+ clear: vi.fn(() => {
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
+ Object.keys(store).forEach((key) => delete store[key]);
+ }),
+ key: vi.fn((index: number) => Object.keys(store)[index] || null),
+ get length() {
+ return Object.keys(store).length;
+ },
+ },
+ writable: true,
+ });
+ },
+
+ fetch: (mockImplementation?: Mock) => {
+ const mockFetch = vi.fn(mockImplementation);
+ global.fetch = mockFetch;
+ return mockFetch;
+ },
+
+ websocket: () => {
+ const mockWs = {
+ close: vi.fn(),
+ send: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ onopen: null,
+ onclose: null,
+ onmessage: null,
+ onerror: null,
+ readyState: WebSocket.CONNECTING,
+ };
+
+ global.WebSocket = vi.fn(() => mockWs) as unknown as typeof WebSocket;
+ return mockWs;
+ },
+};
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export function asMock<T extends (...args: any[]) => unknown>(fn: T): Mock<T> {
+ invariant(
+ "mock" in fn,
+ "fn must be a mock function, use vi.fn() to create one",
+ );
+ return fn as unknown as Mock<T>;
+}
+
+export function partialImplementation<T extends object>(
+ partial: Partial<T>,
+): T {
+ return partial as unknown as T;
+}
diff --git a/frontend/src/__mocks__/notebook.ts b/frontend/src/__mocks__/notebook.ts
new file mode 100644
index 0000000000..73132ab427
--- /dev/null
+++ b/frontend/src/__mocks__/notebook.ts
@@ -0,0 +1,68 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { vi } from "vitest";
+import type { CellActions, NotebookState } from "@/core/cells/cells";
+import { CellId } from "@/core/cells/ids";
+import type { CellData } from "@/core/cells/types";
+import { MultiColumn } from "@/utils/id-tree";
+import { Objects } from "@/utils/objects";
+
+export const MockNotebook = {
+ *cellIds() {
+ yield CellId.create();
+ },
+
+ notebookState: (opts?: {
+ cellData: Record<string, Partial<CellData>>;
+ }): NotebookState => {
+ const cellData = opts?.cellData || {};
+ return {
+ cellData: Objects.mapValues(cellData, (data, cellId) => ({
+ id: cellId as CellId,
+ code: "",
+ name: `cell-${cellId}`,
+ config: {
+ hide_code: false,
+ disabled: false,
+ column: null,
+ ...data.config,
+ },
+ edited: false,
+ lastCodeRun: null,
+ lastExecutionTime: null,
+ serializedEditorState: null,
+ ...data,
+ })),
+ cellIds: MultiColumn.from([Object.keys(cellData) as CellId[]]),
+ cellRuntime: {},
+ cellHandles: {},
+ cellLogs: [],
+ history: [],
+ scrollKey: null,
+ };
+ },
+
+ cellActions: (actions: Partial<CellActions> = {}): CellActions => {
+ // Create a mock that has vi.fn() for all methods
+ const mockActions: Record<string, () => void> = {};
+
+ // Create vi.fn() for each action
+ for (const [action, fn] of Object.entries(actions)) {
+ mockActions[action] = vi.fn().mockImplementation(fn);
+ }
+
+ // Merge with provided actions
+ return new Proxy(
+ {},
+ {
+ get(_target, prop) {
+ if (prop in mockActions) {
+ return mockActions[prop as keyof typeof mockActions];
+ }
+ throw new Error(
+ `Action ${String(prop)} not mocked. Please add it to MockNotebook.cellActions({})`,
+ );
+ },
+ },
+ ) as unknown as CellActions;
+ },
+};
diff --git a/frontend/src/__tests__/setup.ts b/frontend/src/__tests__/setup.ts
index 8a1512f3d8..e4e67be647 100644
--- a/frontend/src/__tests__/setup.ts
+++ b/frontend/src/__tests__/setup.ts
@@ -1,10 +1,16 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { cleanup } from "@testing-library/react";
-import { afterEach } from "vitest";
+import { afterEach, beforeEach, vi } from "vitest";
import "@testing-library/jest-dom/vitest";
import "blob-polyfill";
+// Global setup for all tests
+beforeEach(() => {
+ // Reset all mocks before each test
+ vi.clearAllMocks();
+});
+
// Cleanup after each test case (e.g., clearing jsdom)
afterEach(() => {
cleanup();
diff --git a/frontend/src/__tests__/test-helpers.ts b/frontend/src/__tests__/test-helpers.ts
new file mode 100644
index 0000000000..fb2e314ad9
--- /dev/null
+++ b/frontend/src/__tests__/test-helpers.ts
@@ -0,0 +1,24 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+/**
+ * Common test patterns
+ */
+export const TestUtils = {
+ /**
+ * Create a promise that resolves after a tick
+ */
+ nextTick: () => new Promise((resolve) => setTimeout(resolve, 0)),
+
+ /**
+ * Wait for a specific condition to be true
+ */
+ waitFor: async (condition: () => boolean, timeout = 1000) => {
+ const start = Date.now();
+ while (!condition() && Date.now() - start < timeout) {
+ await TestUtils.nextTick();
+ }
+ if (!condition()) {
+ throw new Error(`Condition not met within ${timeout}ms`);
+ }
+ },
+};
diff --git a/frontend/src/components/data-table/charts/__tests__/storage.test.ts b/frontend/src/components/data-table/charts/__tests__/storage.test.ts
index 33e7d07c33..2bb22a2916 100644
--- a/frontend/src/components/data-table/charts/__tests__/storage.test.ts
+++ b/frontend/src/components/data-table/charts/__tests__/storage.test.ts
@@ -2,31 +2,17 @@
import { getDefaultStore } from "jotai";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { asMock, SetupMocks } from "@/__mocks__/common";
import type { CellId } from "@/core/cells/ids";
import { ChartSchema } from "../schemas";
import type { TabName } from "../storage";
import { KEY, tabsStorageAtom } from "../storage";
import { ChartType } from "../types";
-// Mock localStorage
-const mockLocalStorage = {
- getItem: vi.fn(),
- setItem: vi.fn(),
- removeItem: vi.fn(),
- clear: vi.fn(),
- length: 0,
- key: vi.fn(),
-};
-
-// Mock window.localStorage
-Object.defineProperty(window, "localStorage", {
- value: mockLocalStorage,
- writable: true,
-});
-
describe("Chart Transforms Storage", () => {
beforeEach(() => {
vi.clearAllMocks();
+ SetupMocks.localStorage();
// Reset the store before each test
const store = getDefaultStore();
store.set(tabsStorageAtom, new Map());
@@ -102,13 +88,13 @@ describe("Chart Transforms Storage", () => {
describe("LocalStorage integration", () => {
it("should call localStorage.setItem when setting data", () => {
// Reset the mock to ensure clean state
- mockLocalStorage.setItem.mockReset();
+ asMock(window.localStorage.setItem).mockReset();
const store = getDefaultStore();
const newMap = new Map();
store.set(tabsStorageAtom, newMap);
- expect(mockLocalStorage.setItem).toHaveBeenCalledWith(
+ expect(window.localStorage.setItem).toHaveBeenCalledWith(
KEY,
JSON.stringify([]),
);
diff --git a/frontend/src/components/editor/controls/keyboard-shortcuts.tsx b/frontend/src/components/editor/controls/keyboard-shortcuts.tsx
index 7aa173e6e8..e7c07495fe 100644
--- a/frontend/src/components/editor/controls/keyboard-shortcuts.tsx
+++ b/frontend/src/components/editor/controls/keyboard-shortcuts.tsx
@@ -235,17 +235,27 @@ export const KeyboardShortcuts: React.FC = () => {
};
const groups = hotkeys.getHotkeyGroups();
- const renderGroup = (group: HotkeyGroup) => {
+ const renderGroup = (group: HotkeyGroup, subHeader?: React.ReactNode) => {
const items = groups[group];
return (
<div className="mb-[40px] gap-2 flex flex-col">
- <h3 className="text-lg font-medium">{group}</h3>
-
- {items.map((item) => renderItem(item))}
+ <div>
+ <h3 className="text-lg font-medium">{group}</h3>
+ {subHeader}
+ </div>
+ {items.map(renderItem)}
</div>
);
};
+ const renderCommandGroup = (group: HotkeyGroup) =>
+ renderGroup(
+ group,
+ <p className="text-xs text-muted-foreground">
+ Press <kbd>Esc</kbd> in a cell to enter command mode
+ </p>,
+ );
+
return (
<Dialog open={isOpen} onOpenChange={(open) => setIsOpen(open)}>
{/* Manually portal so we can adjust positioning: shortcuts modal is too large to offset from top for some screens. */}
@@ -268,9 +278,10 @@ export const KeyboardShortcuts: React.FC = () => {
{renderGroup("Navigation")}
{renderGroup("Running Cells")}
{renderGroup("Creation and Ordering")}
+ {renderCommandGroup("Command")}
{renderGroup("Other")}
<Button
- className="mt-4 hover:bg-destructive/10 hover:border-destructive"
+ className="mt-4 hover:bg-destructive/10 border-destructive hover:border-destructive"
variant="outline"
size="xs"
onClick={handleResetAllShortcuts}
diff --git a/frontend/src/components/editor/focus/__tests__/clipboard.test.ts b/frontend/src/components/editor/focus/__tests__/clipboard.test.ts
new file mode 100644
index 0000000000..ed421a9a13
--- /dev/null
+++ b/frontend/src/components/editor/focus/__tests__/clipboard.test.ts
@@ -0,0 +1,309 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+// @vitest-environment jsdom
+
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { asMock, Mocks, SetupMocks } from "@/__mocks__/common";
+import type { CellActions, NotebookState } from "@/core/cells/cells";
+import type { CellId } from "@/core/cells/ids";
+import { useCellClipboard } from "../clipboard";
+
+// Mock dependencies
+vi.mock("@/components/ui/use-toast", () => ({
+ toast: vi.fn(),
+}));
+
+vi.mock("@/core/cells/cells", () => ({
+ getNotebook: vi.fn(),
+ useCellActions: vi.fn(),
+}));
+
+vi.mock("@/utils/Logger", () => ({
+ Logger: Mocks.quietLogger(),
+}));
+
+import { MockNotebook } from "@/__mocks__/notebook";
+import { toast } from "@/components/ui/use-toast";
+import { getNotebook, useCellActions } from "@/core/cells/cells";
+import { Logger } from "@/utils/Logger";
+
+describe("useCellClipboard", () => {
+ const mockCellId = "test-cell-id" as CellId;
+ const mockCellCode = "print('hello world')";
+ const mockCreateNewCell = vi.fn();
+
+ const mockClipboard = Mocks.clipboard();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ SetupMocks.clipboard(mockClipboard);
+
+ // Setup default mocks
+ asMock(getNotebook).mockReturnValue({
+ cellData: {
+ [mockCellId]: {
+ code: mockCellCode,
+ name: "test-cell",
+ },
+ },
+ } as NotebookState);
+
+ asMock(useCellActions).mockReturnValue({
+ createNewCell: mockCreateNewCell,
+ } as unknown as CellActions);
+ });
+
+ describe("copyCell", () => {
+ it("should copy cell to clipboard with custom mimetype and plain text", async () => {
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.copyCell(mockCellId);
+ });
+
+ expect(mockClipboard.write).toHaveBeenCalledWith([
+ expect.objectContaining({
+ types: ["application/x-marimo-cell", "text/plain"],
+ }),
+ ]);
+
+ expect(toast).toHaveBeenCalledWith({
+ title: "Cell copied",
+ description: "Cell has been copied to clipboard",
+ });
+ });
+
+ it("should show error toast when cell not found", async () => {
+ asMock(getNotebook).mockReturnValue(MockNotebook.notebookState());
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.copyCell(mockCellId);
+ });
+
+ expect(toast).toHaveBeenCalledWith({
+ title: "Error",
+ description: "Cell not found",
+ variant: "danger",
+ });
+ });
+
+ it("should fallback to writeText when clipboard.write fails", async () => {
+ mockClipboard.write.mockRejectedValue(new Error("Write failed"));
+ mockClipboard.writeText.mockResolvedValue(undefined);
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.copyCell(mockCellId);
+ });
+
+ expect(mockClipboard.write).toHaveBeenCalled();
+ expect(mockClipboard.writeText).toHaveBeenCalledWith(mockCellCode);
+ expect(toast).toHaveBeenCalledWith({
+ title: "Cell copied",
+ description: "Cell code has been copied to clipboard",
+ });
+ });
+
+ it("should show error toast when both clipboard methods fail", async () => {
+ mockClipboard.write.mockRejectedValue(new Error("Write failed"));
+ mockClipboard.writeText.mockRejectedValue(new Error("WriteText failed"));
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.copyCell(mockCellId);
+ });
+
+ expect(Logger.error).toHaveBeenCalledWith(
+ "Failed to copy cell to clipboard",
+ expect.any(Error),
+ );
+ expect(toast).toHaveBeenCalledWith({
+ title: "Copy failed",
+ description: "Failed to copy cell to clipboard",
+ variant: "danger",
+ });
+ });
+ });
+
+ describe("pasteCell", () => {
+ it("should paste cell from custom mimetype", async () => {
+ const clipboardData = {
+ code: "x = 42",
+ version: "1.0",
+ };
+
+ const mockItem = {
+ types: ["application/x-marimo-cell"],
+ getType: vi.fn().mockResolvedValue(
+ new Blob([JSON.stringify(clipboardData)], {
+ type: "application/x-marimo-cell",
+ }),
+ ),
+ };
+
+ mockClipboard.read.mockResolvedValue([mockItem]);
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.pasteCell(mockCellId);
+ });
+
+ expect(mockCreateNewCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: false,
+ code: "x = 42",
+ autoFocus: true,
+ });
+ });
+
+ it("should fallback to plain text when custom mimetype fails", async () => {
+ const mockItem = {
+ types: ["text/plain"],
+ getType: vi.fn().mockRejectedValue(new Error("Parse failed")),
+ };
+
+ mockClipboard.read.mockResolvedValue([mockItem]);
+ mockClipboard.readText.mockResolvedValue("plain text code");
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.pasteCell(mockCellId);
+ });
+
+ expect(mockCreateNewCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: false,
+ code: "plain text code",
+ autoFocus: true,
+ });
+ });
+
+ it("should handle invalid clipboard data gracefully", async () => {
+ const mockItem = {
+ types: ["application/x-marimo-cell"],
+ getType: vi.fn().mockResolvedValue(
+ new Blob(["invalid json"], {
+ type: "application/x-marimo-cell",
+ }),
+ ),
+ };
+
+ mockClipboard.read.mockResolvedValue([mockItem]);
+ mockClipboard.readText.mockResolvedValue("fallback text");
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.pasteCell(mockCellId);
+ });
+
+ expect(Logger.warn).toHaveBeenCalledWith(
+ "Failed to parse clipboard cell data",
+ expect.any(Error),
+ );
+ expect(mockCreateNewCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: false,
+ code: "fallback text",
+ autoFocus: true,
+ });
+ });
+
+ it("should show error toast when clipboard is empty", async () => {
+ mockClipboard.read.mockResolvedValue([]);
+ mockClipboard.readText.mockResolvedValue("");
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.pasteCell(mockCellId);
+ });
+
+ expect(toast).toHaveBeenCalledWith({
+ title: "Nothing to paste",
+ description: "No cell or text found in clipboard",
+ variant: "danger",
+ });
+ });
+
+ it("should show error toast when clipboard read fails", async () => {
+ mockClipboard.read.mockRejectedValue(new Error("Read failed"));
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.pasteCell(mockCellId);
+ });
+
+ expect(Logger.error).toHaveBeenCalledWith(
+ "Failed to paste from clipboard",
+ expect.any(Error),
+ );
+ expect(toast).toHaveBeenCalledWith({
+ title: "Paste failed",
+ description: "Failed to read from clipboard",
+ variant: "danger",
+ });
+ });
+
+ it("should handle whitespace-only clipboard text", async () => {
+ mockClipboard.read.mockResolvedValue([]);
+ mockClipboard.readText.mockResolvedValue(" \n\t ");
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.pasteCell(mockCellId);
+ });
+
+ expect(toast).toHaveBeenCalledWith({
+ title: "Nothing to paste",
+ description: "No cell or text found in clipboard",
+ variant: "danger",
+ });
+ });
+
+ it("should handle clipboard data with wrong version", async () => {
+ const clipboardData = {
+ code: "x = 42",
+ version: "2.0", // Wrong version
+ };
+
+ const mockItem = {
+ types: ["application/x-marimo-cell"],
+ getType: vi.fn().mockResolvedValue(
+ new Blob([JSON.stringify(clipboardData)], {
+ type: "application/x-marimo-cell",
+ }),
+ ),
+ };
+
+ mockClipboard.read.mockResolvedValue([mockItem]);
+ mockClipboard.readText.mockResolvedValue("fallback text");
+
+ const { result } = renderHook(() => useCellClipboard());
+
+ await act(async () => {
+ await result.current.pasteCell(mockCellId);
+ });
+
+ expect(Logger.warn).toHaveBeenCalledWith(
+ "Failed to parse clipboard cell data",
+ expect.any(Error),
+ );
+ expect(mockCreateNewCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: false,
+ code: "fallback text",
+ autoFocus: true,
+ });
+ });
+ });
+});
diff --git a/frontend/src/components/editor/focus/__tests__/focus.test.ts b/frontend/src/components/editor/focus/__tests__/focus.test.ts
new file mode 100644
index 0000000000..adb6233169
--- /dev/null
+++ b/frontend/src/components/editor/focus/__tests__/focus.test.ts
@@ -0,0 +1,399 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+// @vitest-environment jsdom
+
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { Mocks, partialImplementation } from "@/__mocks__/common";
+import { MockNotebook } from "@/__mocks__/notebook";
+import type { CellActions } from "@/core/cells/cells";
+import type { CellId } from "@/core/cells/ids";
+import { useCellEditorNavigationProps, useCellNavigationProps } from "../focus";
+import type { CellFocusManager } from "../focus-manager";
+
+// Mock only the essential dependencies that we need to control
+vi.mock("@/core/cells/cells", () => ({
+ useCellActions: vi.fn(),
+}));
+
+vi.mock("@/core/cells/focus", () => ({
+ useSetLastFocusedCellId: vi.fn(),
+}));
+
+vi.mock("@/core/saving/save-component", () => ({
+ useSaveNotebook: vi.fn(),
+}));
+
+vi.mock("../../cell/useRunCells", () => ({
+ useRunCell: vi.fn(),
+}));
+
+vi.mock("../clipboard", () => ({
+ useCellClipboard: vi.fn(),
+}));
+
+vi.mock("../focus-manager", () => ({
+ useCellFocusManager: vi.fn(),
+}));
+
+// Get mocked functions
+const mockUseCellActions = vi.mocked(
+ await import("@/core/cells/cells"),
+).useCellActions;
+const mockUseSetLastFocusedCellId = vi.mocked(
+ await import("@/core/cells/focus"),
+).useSetLastFocusedCellId;
+const mockUseSaveNotebook = vi.mocked(
+ await import("@/core/saving/save-component"),
+).useSaveNotebook;
+const mockUseRunCell = vi.mocked(
+ await import("../../cell/useRunCells"),
+).useRunCell;
+const mockUseCellClipboard = vi.mocked(
+ await import("../clipboard"),
+).useCellClipboard;
+const mockUseCellFocusManager = vi.mocked(
+ await import("../focus-manager"),
+).useCellFocusManager;
+
+describe("useCellNavigationProps", () => {
+ const mockCellId = "test-cell-id" as CellId;
+ const mockSetLastFocusedCellId = vi.fn();
+ const mockSaveOrNameNotebook = vi.fn();
+ const mockSaveIfNotebookIsPersistent = vi.fn();
+ const mockRunCell = vi.fn();
+ const mockCopyCell = vi.fn();
+ const mockPasteCell = vi.fn();
+
+ const mockCellActions = MockNotebook.cellActions({
+ focusCell: vi.fn(),
+ moveToNextCell: vi.fn(),
+ focusTopCell: vi.fn(),
+ focusBottomCell: vi.fn(),
+ createNewCell: vi.fn(),
+ });
+ const mockFocusManager = partialImplementation<CellFocusManager>({
+ focusCellEditor: vi.fn(),
+ focusCell: vi.fn(),
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ // Setup mocks
+ mockUseSetLastFocusedCellId.mockReturnValue(mockSetLastFocusedCellId);
+ mockUseSaveNotebook.mockReturnValue({
+ saveOrNameNotebook: mockSaveOrNameNotebook,
+ saveIfNotebookIsPersistent: mockSaveIfNotebookIsPersistent,
+ });
+ mockUseCellActions.mockReturnValue(
+ mockCellActions as unknown as CellActions,
+ );
+ mockUseCellFocusManager.mockReturnValue(mockFocusManager);
+ mockUseRunCell.mockReturnValue(mockRunCell);
+ mockUseCellClipboard.mockReturnValue({
+ copyCell: mockCopyCell,
+ pasteCell: mockPasteCell,
+ });
+ });
+
+ describe("keyboard shortcuts", () => {
+ it("should copy cell when 'c' key is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "c" });
+
+ act(() => {
+ // Simulate the keyboard event
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockCopyCell).toHaveBeenCalledWith(mockCellId);
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should paste cell when 'v' key is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "v" });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockPasteCell).toHaveBeenCalledWith(mockCellId);
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should move to next cell when ArrowDown is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "ArrowDown" });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockCellActions.focusCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: false,
+ });
+ });
+
+ it("should move to previous cell when ArrowUp is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "ArrowUp" });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockCellActions.focusCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: true,
+ });
+ });
+
+ it("should focus cell editor when Enter is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "Enter", shiftKey: false });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockFocusManager.focusCellEditor).toHaveBeenCalledWith(mockCellId);
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should run cell and move to next when Shift+Enter is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "Enter", shiftKey: true });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockRunCell).toHaveBeenCalled();
+ expect(mockCellActions.focusCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: false,
+ });
+ expect(mockEvent.preventDefault).toHaveBeenCalled();
+ });
+
+ it("should save notebook when 's' key is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "s" });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockSaveOrNameNotebook).toHaveBeenCalled();
+ });
+
+ it("should create cell before when 'a' key is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "a" });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockCellActions.createNewCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: true,
+ autoFocus: true,
+ });
+ });
+
+ it("should create cell after when 'b' key is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "b" });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockCellActions.createNewCell).toHaveBeenCalledWith({
+ cellId: mockCellId,
+ before: false,
+ autoFocus: true,
+ });
+ });
+
+ it("should move to top cell when Cmd+ArrowUp is pressed (or Ctrl)", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "ArrowUp", ctrlKey: true });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockCellActions.focusTopCell).toHaveBeenCalled();
+ });
+
+ it("should move to bottom cell when Cmd+ArrowDown is pressed (or Ctrl)", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "ArrowDown",
+ ctrlKey: true,
+ });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockCellActions.focusBottomCell).toHaveBeenCalled();
+ });
+
+ it("should move to top cell when Ctrl+ArrowUp is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({ key: "ArrowUp", ctrlKey: true });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockCellActions.focusTopCell).toHaveBeenCalled();
+ });
+
+ it("should move to bottom cell when Ctrl+ArrowDown is pressed", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "ArrowDown",
+ ctrlKey: true,
+ });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockCellActions.focusBottomCell).toHaveBeenCalled();
+ });
+ });
+
+ describe("input event handling", () => {
+ it("should ignore events from input elements", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "c",
+ target: document.createElement("input"), // Input element
+ });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockCopyCell).not.toHaveBeenCalled();
+ expect(mockEvent.continuePropagation).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("unknown keys", () => {
+ it("should continue propagation for unknown keys", () => {
+ const { result } = renderHook(() => useCellNavigationProps(mockCellId));
+
+ const mockEvent = Mocks.keyboardEvent({
+ key: "x",
+ target: document.createElement("div"),
+ });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockEvent.continuePropagation).not.toHaveBeenCalled();
+ });
+ });
+});
+
+describe("useCellEditorNavigationProps", () => {
+ const mockCellId = "test-cell-id" as CellId;
+ const mockFocusManager = partialImplementation<CellFocusManager>({
+ focusCellEditor: vi.fn(),
+ focusCell: vi.fn(),
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockUseCellFocusManager.mockReturnValue(mockFocusManager);
+ });
+
+ describe("keyboard shortcuts", () => {
+ it("should focus cell when Escape is pressed", () => {
+ const { result } = renderHook(() =>
+ useCellEditorNavigationProps(mockCellId),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "Escape" });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockFocusManager.focusCell).toHaveBeenCalledWith(mockCellId);
+ expect(mockEvent.continuePropagation).not.toHaveBeenCalled();
+ });
+
+ it("should continue propagation for other keys", () => {
+ const { result } = renderHook(() =>
+ useCellEditorNavigationProps(mockCellId),
+ );
+
+ const mockEvent = Mocks.keyboardEvent({ key: "Enter" });
+
+ act(() => {
+ if (result.current.onKeyDown) {
+ result.current.onKeyDown(mockEvent);
+ }
+ });
+
+ expect(mockFocusManager.focusCell).not.toHaveBeenCalled();
+ expect(mockEvent.continuePropagation).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/frontend/src/components/editor/focus/clipboard.ts b/frontend/src/components/editor/focus/clipboard.ts
new file mode 100644
index 0000000000..8aed9479f8
--- /dev/null
+++ b/frontend/src/components/editor/focus/clipboard.ts
@@ -0,0 +1,144 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+
+import useEvent from "react-use-event-hook";
+import { z } from "zod";
+import { toast } from "@/components/ui/use-toast";
+import { getNotebook, useCellActions } from "@/core/cells/cells";
+import type { CellId } from "@/core/cells/ids";
+import { Logger } from "@/utils/Logger";
+
+const MARIMO_CELL_MIMETYPE = "application/x-marimo-cell";
+
+interface ClipboardCellData {
+ code: string;
+ version: "1.0";
+}
+
+const ClipboardCellDataSchema = z.object({
+ code: z.string(),
+ version: z.literal("1.0"),
+});
+
+// NOTE: We don't support Cut yet. We can wait for feedback before implementing.
+// It is a bit more complex as will need to:
+// - include id, outputs, and name
+// - delete the existing cell, but don't place on the undo stack
+// - don't want to invalidate downstream cells
+
+export function useCellClipboard() {
+ const actions = useCellActions();
+
+ const copyCell = useEvent(async (cellId: CellId) => {
+ const cellData = getNotebook().cellData[cellId];
+ if (!cellData) {
+ toast({
+ title: "Error",
+ description: "Cell not found",
+ variant: "danger",
+ });
+ return;
+ }
+
+ try {
+ const clipboardData: ClipboardCellData = {
+ code: cellData.code,
+ version: "1.0",
+ };
+
+ // Create clipboard item with both custom mimetype and plain text
+ const clipboardItem = new ClipboardItem({
+ [MARIMO_CELL_MIMETYPE]: new Blob([JSON.stringify(clipboardData)], {
+ type: MARIMO_CELL_MIMETYPE,
+ }),
+ "text/plain": new Blob([cellData.code], {
+ type: "text/plain",
+ }),
+ });
+
+ await navigator.clipboard.write([clipboardItem]);
+
+ toast({
+ title: "Cell copied",
+ description: "Cell has been copied to clipboard",
+ });
+ } catch (error) {
+ Logger.error("Failed to copy cell to clipboard", error);
+
+ // Fallback to simple text copy
+ try {
+ await navigator.clipboard.writeText(cellData.code);
+ toast({
+ title: "Cell copied",
+ description: "Cell code has been copied to clipboard",
+ });
+ } catch {
+ toast({
+ title: "Copy failed",
+ description: "Failed to copy cell to clipboard",
+ variant: "danger",
+ });
+ }
+ }
+ });
+
+ const pasteCell = useEvent(async (cellId: CellId) => {
+ try {
+ const clipboardItems = await navigator.clipboard.read();
+
+ // Look for our custom mimetype first
+ for (const item of clipboardItems) {
+ if (item.types.includes(MARIMO_CELL_MIMETYPE)) {
+ const blob = await item.getType(MARIMO_CELL_MIMETYPE);
+ const text = await blob.text();
+
+ try {
+ const clipboardData = ClipboardCellDataSchema.parse(
+ JSON.parse(text),
+ );
+
+ // Create a new cell with the copied data after the current cell
+ // We don't use name or config yet, as it may not be desired or make sense to copy over as well.
+ actions.createNewCell({
+ cellId,
+ before: false,
+ code: clipboardData.code,
+ autoFocus: true,
+ });
+ return;
+ } catch (parseError) {
+ Logger.warn("Failed to parse clipboard cell data", parseError);
+ }
+ }
+ }
+
+ // Fallback to plain text
+ const text = await navigator.clipboard.readText();
+ if (text.trim()) {
+ actions.createNewCell({
+ cellId,
+ before: false,
+ code: text,
+ autoFocus: true,
+ });
+ } else {
+ toast({
+ title: "Nothing to paste",
+ description: "No cell or text found in clipboard",
+ variant: "danger",
+ });
+ }
+ } catch (error) {
+ Logger.error("Failed to paste from clipboard", error);
+ toast({
+ title: "Paste failed",
+ description: "Failed to read from clipboard",
+ variant: "danger",
+ });
+ }
+ });
+
+ return {
+ copyCell,
+ pasteCell,
+ };
+}
diff --git a/frontend/src/components/editor/focus/focus.ts b/frontend/src/components/editor/focus/focus.ts
index 9583814684..2d0e2830cf 100644
--- a/frontend/src/components/editor/focus/focus.ts
+++ b/frontend/src/components/editor/focus/focus.ts
@@ -5,8 +5,13 @@ 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 { keymapPresetAtom } from "@/core/config/config";
+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 { useCellFocusManager } from "./focus-manager";
import { temporarilyShownCodeAtom } from "./state";
@@ -15,13 +20,25 @@ import { temporarilyShownCodeAtom } from "./state";
* 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 setTemporarilyShownCode = useSetAtom(temporarilyShownCodeAtom);
const focusManager = useCellFocusManager();
+ 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({
@@ -37,35 +54,103 @@ export function useCellNavigationProps(cellId: CellId) {
const { keyboardProps } = useKeyboard({
onKeyDown: (evt) => {
- // Came from an input, do nothing.
+ // 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") {
- actions.moveToNextCell({ cellId, before: false, noCreate: true });
+ if (evt.key === "ArrowDown" && !Events.hasModifier(evt)) {
+ actions.focusCell({ cellId, before: false });
+ return;
}
// Up arrow moves to the previous cell.
- if (evt.key === "ArrowUp") {
- actions.moveToNextCell({ cellId, before: true, noCreate: true });
+ 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);
focusManager.focusCellEditor(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") {
- actions.moveToNextCell({ cellId, before: false, noCreate: true });
+ if (evt.key === "j" && !Events.hasModifier(evt)) {
+ actions.focusCell({ cellId, before: false });
+ return;
}
- if (evt.key === "k") {
- actions.moveToNextCell({ cellId, before: true, noCreate: true });
+ if (evt.key === "k" && !Events.hasModifier(evt)) {
+ actions.focusCell({ cellId, before: true });
+ return;
}
}
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 39dd74a77c..b6fd945989 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -426,11 +426,13 @@ const {
}
const cellId = column.first();
- const cellData = state.cellData[cellId];
- const cellHandle = state.cellHandles[cellId];
- if (!cellData.config.hide_code) {
- cellHandle.current?.editorView.focus();
- }
+ focusAndScrollCellIntoView({
+ cellId: cellId,
+ cell: state.cellHandles[cellId],
+ config: state.cellData[cellId].config,
+ codeFocus: undefined,
+ variableName: undefined,
+ });
scrollToTop();
return state;
},
@@ -442,11 +444,13 @@ const {
}
const cellId = column.last();
- const cellData = state.cellData[cellId];
- const cellHandle = state.cellHandles[cellId];
- if (!cellData.config.hide_code) {
- cellHandle.current?.editorView.focus();
- }
+ focusAndScrollCellIntoView({
+ cellId: cellId,
+ cell: state.cellHandles[cellId],
+ config: state.cellData[cellId].config,
+ codeFocus: undefined,
+ variableName: undefined,
+ });
scrollToBottom();
return state;
},
diff --git a/frontend/src/core/hotkeys/__tests__/shortcuts.test.ts b/frontend/src/core/hotkeys/__tests__/shortcuts.test.ts
index 980d0a82fe..bb28e5b350 100644
--- a/frontend/src/core/hotkeys/__tests__/shortcuts.test.ts
+++ b/frontend/src/core/hotkeys/__tests__/shortcuts.test.ts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { parseShortcut } from "../shortcuts";
describe("parseShortcut", () => {
@@ -33,6 +33,26 @@ describe("parseShortcut", () => {
expect(shortcut(event)).toBe(true);
});
+ it("should recognize Mod key shortcuts", () => {
+ const shortcut = parseShortcut("Mod-ArrowRight");
+ const event = new KeyboardEvent("keydown", {
+ key: "ArrowRight",
+ metaKey: true,
+ ctrlKey: false,
+ });
+ expect(shortcut(event)).toBe(true);
+
+ const shortcut2 = parseShortcut("Mod-ArrowRight");
+ const event2 = new KeyboardEvent("keydown", {
+ key: "ArrowRight",
+ ctrlKey: true,
+ metaKey: false,
+ });
+ expect(shortcut2(event2)).toBe(true);
+
+ vi.restoreAllMocks();
+ });
+
it("should recognize Space key shortcuts", () => {
const shortcut = parseShortcut("Space");
const event = new KeyboardEvent("keydown", { code: "Space" });
diff --git a/frontend/src/core/hotkeys/hotkeys.ts b/frontend/src/core/hotkeys/hotkeys.ts
index 37fbd32543..de4d522876 100644
--- a/frontend/src/core/hotkeys/hotkeys.ts
+++ b/frontend/src/core/hotkeys/hotkeys.ts
@@ -42,6 +42,7 @@ export type HotkeyGroup =
| "Navigation"
| "Editing"
| "Markdown"
+ | "Command"
| "Other";
const DEFAULT_HOT_KEY = {
@@ -380,6 +381,28 @@ const DEFAULT_HOT_KEY = {
group: "Editing",
key: "Ctrl-k",
},
+
+ // Command mode (edit a cell, not the editor)
+ "command.createCellBefore": {
+ name: "Create a cell before current cell",
+ group: "Command",
+ key: "a",
+ },
+ "command.createCellAfter": {
+ name: "Create a cell after current cell",
+ group: "Command",
+ key: "b",
+ },
+ "command.copyCell": {
+ name: "Copy cell",
+ group: "Command",
+ key: "c",
+ },
+ "command.pasteCell": {
+ name: "Paste cell",
+ group: "Command",
+ key: "v",
+ },
} satisfies Record<string, Hotkey>;
export type HotkeyAction = keyof typeof DEFAULT_HOT_KEY;
diff --git a/frontend/src/core/hotkeys/shortcuts.ts b/frontend/src/core/hotkeys/shortcuts.ts
index b247667266..6daa00a27b 100644
--- a/frontend/src/core/hotkeys/shortcuts.ts
+++ b/frontend/src/core/hotkeys/shortcuts.ts
@@ -25,6 +25,10 @@ function areKeysPressed(keys: string[], e: KeyboardEvent): boolean {
let satisfied = true;
for (const key of keys) {
switch (key) {
+ case "mod":
+ // Accept both meta and ctrl
+ satisfied &&= e.metaKey || e.ctrlKey;
+ break;
case "ctrl":
satisfied &&= e.ctrlKey;
break;
@@ -50,13 +54,14 @@ function areKeysPressed(keys: string[], e: KeyboardEvent): boolean {
}
}
+ // If the shortcut does not include a modifier, ensure the modifier is not pressed
if (!keys.includes("shift")) {
satisfied &&= !e.shiftKey;
}
- if (!keys.includes("ctrl")) {
+ if (!keys.includes("ctrl") && !keys.includes("mod")) {
satisfied &&= !e.ctrlKey;
}
- if (!keys.includes("meta")) {
+ if (!keys.includes("meta") && !keys.includes("mod")) {
satisfied &&= !e.metaKey;
}
if (!keys.includes("alt")) {
@@ -77,6 +82,12 @@ function normalizeKey(key: string): string {
return specialKeys[key.toLowerCase()] || key.toLowerCase();
}
+/**
+ * Returns a function that checks if a shortcut is pressed.
+ *
+ * @param shortcut - The shortcut to check.
+ * @returns A function that checks if the shortcut is pressed.
+ */
export function parseShortcut(
shortcut: string | typeof NOT_SET,
): (e: KeyboardEvent) => boolean {
diff --git a/frontend/src/core/kernel/__tests__/handlers.test.ts b/frontend/src/core/kernel/__tests__/handlers.test.ts
index 42343d20d6..4849df2ab7 100644
--- a/frontend/src/core/kernel/__tests__/handlers.test.ts
+++ b/frontend/src/core/kernel/__tests__/handlers.test.ts
@@ -1,5 +1,4 @@
/* Copyright 2024 Marimo. All rights reserved. */
-/* eslint-disable @typescript-eslint/unbound-method */
import { describe, expect, it, vi } from "vitest";
import { queryParamHandlers } from "../queryParamHandlers";
diff --git a/frontend/src/core/wasm/__tests__/router.test.ts b/frontend/src/core/wasm/__tests__/router.test.ts
index cb3276d582..0e67d11367 100644
--- a/frontend/src/core/wasm/__tests__/router.test.ts
+++ b/frontend/src/core/wasm/__tests__/router.test.ts
@@ -1,5 +1,4 @@
/* Copyright 2024 Marimo. All rights reserved. */
-/* eslint-disable @typescript-eslint/unbound-method */
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { PyodideRouter } from "../router";
diff --git a/frontend/src/core/wasm/__tests__/store.test.ts b/frontend/src/core/wasm/__tests__/store.test.ts
index 11424b3138..8c5c61ea1d 100644
--- a/frontend/src/core/wasm/__tests__/store.test.ts
+++ b/frontend/src/core/wasm/__tests__/store.test.ts
@@ -1,5 +1,4 @@
/* Copyright 2024 Marimo. All rights reserved. */
-/* eslint-disable @typescript-eslint/unbound-method */
import { describe, expect, it, vi } from "vitest";
import {
CompositeFileStore,
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
index 8bff2e463e..8beff09a51 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
+++ b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
@@ -2,6 +2,7 @@
import { act, render, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { TestUtils } from "@/__tests__/test-helpers";
import type { UIElementId } from "@/core/cells/ids";
import { MarimoIncomingMessageEvent } from "@/core/dom/events";
import { getDirtyFields, visibleForTesting } from "../AnyWidgetPlugin";
@@ -155,7 +156,7 @@ describe("LoadedSlot", () => {
// Render without any prop changes
rerender(<LoadedSlot {...mockProps} />);
- await new Promise((resolve) => setTimeout(resolve, 0));
+ await TestUtils.nextTick();
// Still only called once
expect(mockWidget.render).toHaveBeenCalledTimes(1);
@@ -170,7 +171,7 @@ describe("LoadedSlot", () => {
}}
/>,
);
- await new Promise((resolve) => setTimeout(resolve, 0));
+ await TestUtils.nextTick();
// Wait a render
await waitFor(() => {
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
index 3db8065053..90ff068a3c 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
+++ b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
@@ -8,6 +8,7 @@ import {
it,
vi,
} from "vitest";
+import { TestUtils } from "@/__tests__/test-helpers";
import type { Base64String } from "@/utils/json/base64";
import {
type AnyWidgetMessage,
@@ -145,7 +146,7 @@ describe("Model", () => {
model.send({ test: true }, callback);
expect(sendToWidget).toHaveBeenCalledWith({ content: { test: true } });
- await new Promise((resolve) => setTimeout(resolve, 0)); // flush
+ await TestUtils.nextTick(); // flush
expect(callback).toHaveBeenCalledWith(null);
});
@@ -219,7 +220,7 @@ describe("Model", () => {
const callback = vi.fn();
model.on("change", callback);
model.updateAndEmitDiffs({ foo: "changed", bar: 456 });
- await new Promise((resolve) => setTimeout(resolve, 0)); // flush
+ await TestUtils.nextTick(); // flush
expect(callback).toHaveBeenCalledTimes(1);
});
});
diff --git a/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts b/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts
index 82a15bc43e..758a2dfc5c 100644
--- a/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts
+++ b/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts
@@ -1,5 +1,4 @@
/* Copyright 2024 Marimo. All rights reserved. */
-/* eslint-disable @typescript-eslint/unbound-method */
import { afterEach, describe, expect, it, vi } from "vitest";
import { vegaLoader } from "../loader";
import { resolveVegaSpecData } from "../resolve-data";
diff --git a/frontend/src/utils/__tests__/local-storage.test.ts b/frontend/src/utils/__tests__/local-storage.test.ts
index 69f0dd5215..1b477783a2 100644
--- a/frontend/src/utils/__tests__/local-storage.test.ts
+++ b/frontend/src/utils/__tests__/local-storage.test.ts
@@ -2,6 +2,7 @@
import { afterEach, describe, expect, it } from "vitest";
import { z } from "zod";
+import { TestUtils } from "@/__tests__/test-helpers";
import { filenameAtom } from "@/core/saving/file-state";
import { store } from "@/core/state/jotai";
import { NotebookScopedLocalStorage } from "../localStorage";
@@ -68,7 +69,7 @@ describe("NotebookScopedLocalStorage", () => {
// Change filename and verify key updates
store.set(filenameAtom, "other.py");
// Force a small delay to allow the subscription to process
- await new Promise((resolve) => setTimeout(resolve, 0));
+ await TestUtils.nextTick();
expect(storage.createScopedKey(KEY, "other.py")).toEqual("test:other.py");
expect(storage.get(KEY)).toEqual({ name: "Jane Doe", age: 25 });
diff --git a/frontend/src/utils/events.ts b/frontend/src/utils/events.ts
index 7f26c3c76b..8a0837450b 100644
--- a/frontend/src/utils/events.ts
+++ b/frontend/src/utils/events.ts
@@ -72,4 +72,14 @@ export const Events = {
e.target.closest(".cm-editor") !== null)) // Add check for CodeMirror editor
);
},
+
+ hasModifier: (
+ e: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey">,
+ ) => {
+ return e.ctrlKey || e.metaKey || e.altKey || e.shiftKey;
+ },
+
+ isMetaOrCtrl: (e: Pick<KeyboardEvent, "metaKey" | "ctrlKey">) => {
+ return e.metaKey || e.ctrlKey;
+ },
};