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
feat: add scroll to cell (#4162)
Myles Scolnicke8caf88f8074
diff --git a/frontend/src/components/editor/actions/useCellActionButton.tsx b/frontend/src/components/editor/actions/useCellActionButton.tsxindex d64dec6052..1a08fd571a 100644--- a/frontend/src/components/editor/actions/useCellActionButton.tsx+++ b/frontend/src/components/editor/actions/useCellActionButton.tsx@@ -26,6 +26,7 @@ import {ChevronLeftIcon,ChevronRightIcon,ScissorsIcon,+ LinkIcon,} from "lucide-react";import type { ActionButton } from "./types";import { MultiIcon } from "@/components/icons/multi-icon";@@ -56,6 +57,8 @@ import type { CellConfig, RuntimeState } from "@/core/network/types";import { kioskModeAtom } from "@/core/mode";import { switchLanguage } from "@/core/codemirror/language/extension";import { useSplitCellCallback } from "../cell/useSplitCell";+import { canLinkToCell, createCellLink } from "@/utils/cell-urls";+import { copyToClipboard } from "@/utils/copy";export interface CellActionButtonPropsextends Pick<CellData, "name" | "config"> {@@ -369,6 +372,21 @@ export function useCellActionButtons({ cell }: Props) {},],+ // Link to cell+ [+ {+ icon: <LinkIcon size={13} strokeWidth={1.5} />,+ label: "Copy link to cell",+ disabled: !canLinkToCell(name),+ tooltip: canLinkToCell(name)+ ? undefined+ : "Only named cells can be linked to",+ handle: async () => {+ await copyToClipboard(createCellLink(name));+ },+ },+ ],+// Delete[{diff --git a/frontend/src/components/editor/cell/cell-actions.tsx b/frontend/src/components/editor/cell/cell-actions.tsxindex c0a3d2bf65..07eb7462dd 100644--- a/frontend/src/components/editor/cell/cell-actions.tsx+++ b/frontend/src/components/editor/cell/cell-actions.tsx@@ -21,6 +21,7 @@ import {PopoverTrigger,} from "@/components/ui/popover";import {+ Tooltip,TooltipContent,TooltipRoot,TooltipTrigger,@@ -39,7 +40,7 @@ import { useAtomValue } from "jotai";import { cellFocusDetailsAtom } from "@/core/cells/focus";import type { CellId } from "@/core/cells/ids";import { CommandList } from "cmdk";-+import { cn } from "@/utils/cn";interface Props extends CellActionButtonProps {children: React.ReactNode;showTooltip?: boolean;@@ -73,11 +74,37 @@ const CellActionsDropdownInternal = (<Fragment key={i}><CommandGroup key={i}>{group.map((action) => {+ let body = (+ <div className="flex items-center flex-1">+ {action.icon && (+ <div className="mr-2 w-5 text-muted-foreground">+ {action.icon}+ </div>+ )}+ <div className="flex-1">{action.label}</div>+ <div className="flex-shrink-0 text-sm">+ {action.hotkey && renderMinimalShortcut(action.hotkey)}+ {action.rightElement}+ </div>+ </div>+ );++ if (action.tooltip) {+ body = (+ <Tooltip content={action.tooltip} delayDuration={100}>+ {body}+ </Tooltip>+ );+ }+return (<CommandItemkey={action.label}+ // Disable with classname instead of disabled prop+ // otherwise the tooltip doesn't work+ className={cn(action.disabled && "!opacity-50")}onSelect={() => {- if (action.disableClick) {+ if (action.disableClick || action.disabled) {return;}action.handle();@@ -85,19 +112,7 @@ const CellActionsDropdownInternal = (}}variant={action.variant}>- <div className="flex items-center flex-1">- {action.icon && (- <div className="mr-2 w-5 text-muted-foreground">- {action.icon}- </div>- )}- <div className="flex-1">{action.label}</div>- <div className="flex-shrink-0 text-sm">- {action.hotkey &&- renderMinimalShortcut(action.hotkey)}- {action.rightElement}- </div>- </div>+ {body}</CommandItem>);})}diff --git a/frontend/src/components/editor/cell/cell-context-menu.tsx b/frontend/src/components/editor/cell/cell-context-menu.tsxindex 1674ef7c7b..8adb725a00 100644--- a/frontend/src/components/editor/cell/cell-context-menu.tsx+++ b/frontend/src/components/editor/cell/cell-context-menu.tsx@@ -27,6 +27,7 @@ import { Logger } from "@/utils/Logger";import { copyToClipboard } from "@/utils/copy";import { toast } from "@/components/ui/use-toast";import { sendToPanelManager } from "@/core/vscode/vscode-bindings";+import { Tooltip } from "@/components/ui/tooltip";interface Props extends CellActionButtonProps {children: React.ReactNode;@@ -154,6 +155,8 @@ export const CellActionsContextMenu = ({ children, ...props }: Props) => {},];+ const allActions: ActionButton[][] = [DEFAULT_CONTEXT_MENU_ITEMS, ...actions];+return (<ContextMenu><ContextMenuTrigger@@ -169,36 +172,53 @@ export const CellActionsContextMenu = ({ children, ...props }: Props) => {{children}</ContextMenuTrigger><ContextMenuContent className="w-[300px]">- {[DEFAULT_CONTEXT_MENU_ITEMS, ...actions].map((group, i) => (+ {allActions.map((group, i) => (<Fragment key={i}>{group.map((action) => {if (action.hidden) {return null;}++ let body = (+ <div className="flex items-center flex-1">+ {action.icon && (+ <div className="mr-2 w-5 text-muted-foreground">+ {action.icon}+ </div>+ )}+ <div className="flex-1">{action.label}</div>+ <div className="flex-shrink-0 text-sm">+ {action.hotkey && renderMinimalShortcut(action.hotkey)}+ {action.rightElement}+ </div>+ </div>+ );++ if (action.tooltip) {+ body = (+ <Tooltip delayDuration={100} content={action.tooltip}>+ {body}+ </Tooltip>+ );+ }+return (<ContextMenuItemkey={action.label}+ className={action.disabled ? "!opacity-50" : ""}onSelect={(evt) => {+ if (action.disableClick || action.disabled) {+ return;+ }action.handle(evt);}}variant={action.variant}>- <div className="flex items-center flex-1">- {action.icon && (- <div className="mr-2 w-5 text-muted-foreground">- {action.icon}- </div>- )}- <div className="flex-1">{action.label}</div>- <div className="flex-shrink-0 text-sm">- {action.hotkey && renderMinimalShortcut(action.hotkey)}- {action.rightElement}- </div>- </div>+ {body}</ContextMenuItem>);})}- {i < group.length - 1 && <ContextMenuSeparator />}+ {i < allActions.length - 1 && <ContextMenuSeparator />}</Fragment>))}</ContextMenuContent>diff --git a/frontend/src/components/editor/renderers/vertical-layout/__tests__/useDelayVisibility.test.ts b/frontend/src/components/editor/renderers/vertical-layout/__tests__/useDelayVisibility.test.tsnew file mode 100644index 0000000000..80319e17fd--- /dev/null+++ b/frontend/src/components/editor/renderers/vertical-layout/__tests__/useDelayVisibility.test.ts@@ -0,0 +1,117 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { renderHook, act } from "@testing-library/react";+import { useDelayVisibility } from "../useDelayVisibility";+import * as cellsModule from "@/core/cells/cells";++describe("useDelayVisibility", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {+ cb(0);+ return 0;+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("should start with invisible state", () => {+ const { result } = renderHook(() => useDelayVisibility(5, "edit"));+ expect(result.current.invisible).toBe(true);+ });++ it("should become visible after delay", () => {+ const { result } = renderHook(() => useDelayVisibility(5, "edit"));++ expect(result.current.invisible).toBe(true);++ // Advance timers by the calculated delay (5-1)*15 = 60ms+ act(() => {+ vi.advanceTimersByTime(60);+ });++ expect(result.current.invisible).toBe(false);+ });++ it("should cap delay at 100ms for large number of cells", () => {+ const { result } = renderHook(() => useDelayVisibility(20, "edit"));++ expect(result.current.invisible).toBe(true);++ // Advance timers by 99ms (not enough)+ act(() => {+ vi.advanceTimersByTime(99);+ });+ expect(result.current.invisible).toBe(true);++ // Advance remaining 1ms to reach 100ms cap+ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(result.current.invisible).toBe(false);+ });++ it("should not focus any cell in read mode", () => {+ const focusSpy = vi.spyOn(cellsModule, "getNotebook");++ renderHook(() => useDelayVisibility(5, "read"));++ act(() => {+ vi.advanceTimersByTime(100);+ });++ expect(focusSpy).not.toHaveBeenCalled();+ });++ it("should focus cell from URL if scrollTo parameter exists", () => {+ // Mock location.hash+ const originalHash = window.location.hash;+ Object.defineProperty(window, "location", {+ value: { hash: "#scrollTo=testCell" },+ writable: true,+ });++ // Mock document.querySelector+ const mockElement = document.createElement("div");+ mockElement.scrollIntoView = vi.fn();+ mockElement.focus = vi.fn();+ mockElement.dataset.cellId = "cell-123";++ const querySelectorSpy = vi+ .spyOn(document, "querySelector")+ .mockReturnValue(mockElement as unknown as HTMLElement);++ // Mock getNotebook+ const mockEditor = { focus: vi.fn() };+ vi.spyOn(cellsModule, "getNotebook").mockReturnValue({+ cellIds: { iterateTopLevelIds: [] },+ cellData: {},+ cellHandles: {+ "cell-123": { current: { editorView: mockEditor } },+ },+ } as unknown as cellsModule.NotebookState);++ renderHook(() => useDelayVisibility(5, "edit"));++ act(() => {+ vi.advanceTimersByTime(100);+ });++ expect(querySelectorSpy).toHaveBeenCalledWith(+ '[data-cell-name="testCell"]',+ );+ // eslint-disable-next-line @typescript-eslint/unbound-method+ expect(mockElement.scrollIntoView).toHaveBeenCalled();+ // eslint-disable-next-line @typescript-eslint/unbound-method+ expect(mockElement.focus).toHaveBeenCalled();+ expect(mockEditor.focus).toHaveBeenCalled();++ // Restore original hash+ Object.defineProperty(window, "location", {+ value: { hash: originalHash },+ writable: true,+ });+ });+});diff --git a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.tsindex b49f0b5250..01c7c5224a 100644--- a/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts+++ b/frontend/src/components/editor/renderers/vertical-layout/useDelayVisibility.ts@@ -1,28 +1,41 @@/* Copyright 2024 Marimo. All rights reserved. */import type { AppMode } from "@/core/mode";import { getNotebook } from "@/core/cells/cells";-import { useState, useEffect } from "react";+import { useState } from "react";+import { Logger } from "@/utils/Logger";+import type { CellId } from "@/core/cells/ids";+import { useOnMount } from "@/hooks/useLifecycle";+import { extractCellNameFromHash } from "@/utils/cell-urls";export function useDelayVisibility(numCells: number, mode: AppMode) {// Start the app as invisible and delay proportional to the number of cells,// to avoid most of the flickering when the app is loaded (b/c it is// streamed). Delaying also helps prevent cell editors from stealing focus.const [invisible, setInvisible] = useState(true);- useEffect(() => {+ useOnMount(() => {const delay = Math.max(Math.min((numCells - 1) * 15, 100), 0);const timeout = setTimeout(() => {setInvisible(false);- // After 1 frame, focus on the first cell if it's been mounted+ // After 1 frame, either focus on the cell from URL or the first cellif (mode !== "read") {requestAnimationFrame(() => {- focusFirstEditor();+ // Check if the URL contains a scrollTo parameter+ const hash = window.location.hash;+ const cellName = extractCellNameFromHash(hash);++ if (cellName) {+ // If we have a scrollTo parameter, focus on that cell+ focusCellByName(cellName);+ } else {+ // Otherwise focus on the first cell+ focusFirstEditor();+ }});}}, delay);return () => clearTimeout(timeout);// Delay only when app is first loaded- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);+ });return { invisible };}@@ -39,3 +52,53 @@ function focusFirstEditor() {}}}++let hasScrolledToCell = false;++/**+ * Focus the cell with the given name+ */+function focusCellByName(cellName: string) {+ // Only do this once per page load+ if (hasScrolledToCell) {+ return;+ }++ // Find the cell div with data-cell-name attribute matching the cellName+ const cellElement = document.querySelector(`[data-cell-name="${cellName}"]`);++ if (cellElement) {+ // Scroll the element into view+ cellElement.scrollIntoView({+ behavior: "smooth",+ block: "start",+ });++ hasScrolledToCell = true;++ // Try to focus the cell+ if (cellElement instanceof HTMLElement) {+ cellElement.focus();++ // Look for an editor to focus+ const { cellHandles } = getNotebook();+ const cellId = cellElement.dataset.cellId as CellId | undefined;++ if (!cellId) {+ Logger.error(`Missing cellId for cell with name ${cellName}`);+ return;+ }++ const editor = cellHandles[cellId]?.current?.editorView;+ if (editor) {+ editor.focus();+ }+ }+ } else {+ Logger.warn(+ `Cannot focus cell with name ${cellName} because it was not found`,+ );+ // Fall back to focusing the first editor if cell not found+ focusFirstEditor();+ }+}diff --git a/frontend/src/utils/__tests__/cell-urls.test.ts b/frontend/src/utils/__tests__/cell-urls.test.tsnew file mode 100644index 0000000000..73dfbea377--- /dev/null+++ b/frontend/src/utils/__tests__/cell-urls.test.ts@@ -0,0 +1,92 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { describe, expect, it, beforeEach, afterEach } from "vitest";+import {+ createCellLink,+ extractCellNameFromHash,+ canLinkToCell,+} from "../cell-urls";++describe("cell-urls utilities", () => {+ const originalLocation = window.location;++ beforeEach(() => {+ // Mock window.location for testing+ Object.defineProperty(window, "location", {+ value: {+ href: "https://example.com/notebook?file=test.py",+ hash: "",+ },+ writable: true,+ });+ });++ afterEach(() => {+ // Restore original location+ Object.defineProperty(window, "location", {+ value: originalLocation,+ writable: true,+ });+ });++ describe("createCellLink", () => {+ it("should create a URL with the cell name in the hash", () => {+ const url = createCellLink("myCellName");+ expect(url).toBe(+ "https://example.com/notebook?file=test.py#scrollTo=myCellName",+ );+ });++ it("should encode special characters in cell name", () => {+ const url = createCellLink("cell name with spaces & symbols");+ expect(url).toBe(+ "https://example.com/notebook?file=test.py#scrollTo=cell%20name%20with%20spaces%20%26%20symbols",+ );+ });+ });++ describe("extractCellNameFromHash", () => {+ it("should extract cell name from hash", () => {+ expect(extractCellNameFromHash("#scrollTo=cell1")).toBe("cell1");+ expect(extractCellNameFromHash("#scrollTo=cell1&other=param")).toBe(+ "cell1",+ );+ expect(extractCellNameFromHash("#other=param&scrollTo=cell1")).toBe(+ "cell1",+ );+ });++ it("should return null if no cell name is found", () => {+ expect(extractCellNameFromHash("")).toBeNull();+ expect(extractCellNameFromHash("#other=param")).toBeNull();+ });++ it("should decode special characters in cell name", () => {+ const cellName = extractCellNameFromHash(+ "#scrollTo=cell%20name%20with%20spaces%20%26%20symbols",+ );+ expect(cellName).toBe("cell name with spaces & symbols");+ });+ });++ describe("canLinkToCell", () => {+ it("should return true for valid cell name", () => {+ expect(canLinkToCell("myCellName")).toBe(true);+ });++ it("should return false for empty cell name", () => {+ expect(canLinkToCell("")).toBe(false);+ });++ it("should return false for undefined cell name", () => {+ expect(canLinkToCell(undefined)).toBe(false);+ });++ it("should return false for whitespace-only cell name", () => {+ expect(canLinkToCell(" ")).toBe(false);+ });++ it("should return false for default cell name", () => {+ expect(canLinkToCell("_")).toBe(false);+ });+ });+});diff --git a/frontend/src/utils/cell-urls.ts b/frontend/src/utils/cell-urls.tsnew file mode 100644index 0000000000..1ec94bf326--- /dev/null+++ b/frontend/src/utils/cell-urls.ts@@ -0,0 +1,31 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { DEFAULT_CELL_NAME } from "@/core/cells/names";++export function createCellLink(cellName: string): string {+ const url = new URL(window.location.href);+ // Add the cell name to the hash parameter+ url.hash = `scrollTo=${encodeURIComponent(cellName)}`;+ return url.toString();+}++/**+ * Extract cell name from URL hash+ */+export function extractCellNameFromHash(hash: string): string | null {+ const scrollToMatch = hash.match(/scrollTo=([^&]+)/);+ const cellName = scrollToMatch?.[1];+ if (cellName) {+ return decodeURIComponent(cellName.split("&")[0]);+ }+ return null;+}++/**+ * Check if a cell can be linked to (requires a name)+ */+export function canLinkToCell(cellName: string | undefined): boolean {+ if (cellName === DEFAULT_CELL_NAME) {+ return false;+ }+ return Boolean(cellName && cellName.trim().length > 0);+}