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
fix(columns): scroll horizontally when navigating to an off-screen column (#10354)
Dhruv Diwakirti20ab3b3ad3c6
diff --git a/frontend/e2e-tests/columns-scroll.spec.ts b/frontend/e2e-tests/columns-scroll.spec.tsnew file mode 100644index 0000000000..7792084d36--- /dev/null+++ b/frontend/e2e-tests/columns-scroll.spec.ts@@ -0,0 +1,159 @@+/* Copyright 2026 Marimo. All rights reserved. */+import type { Locator, Page } from "@playwright/test";+import { expect, test } from "@playwright/test";+import { getAppUrl } from "../playwright.config";+import { maybeRestartKernel, pressShortcut } from "./helper";++const appUrl = getAppUrl("columns.py");++/**+ * Asserts whether scrolling horizontally and vertically into view works as expected.+ */++test.beforeEach(async ({ page }, info) => {+ await page.goto(appUrl);+ if (info.retry) {+ await page.reload();+ await maybeRestartKernel(page);+ }+});++async function waitForCellsToRun(page: Page): Promise<void> {+ await page.waitForLoadState("networkidle");++ const app = page.locator("#App");+ await expect(app).toHaveAttribute("data-config-width", "columns");++ // Go-to-definition resolves through the kernel's variable registry, so the+ // cells have to have run before the jump can find anything.+ await pressShortcut(page, "global.runStale");+ await expect(page.locator(".marimo-cell.needs-run")).toHaveCount(0, {+ timeout: 30_000,+ });+}++/**+ * Locates the cell containing `text` and asserts it starts outside the+ * initial viewport along `axis`, so a later `toBeInViewport` assertion can't+ * pass vacuously.+ */+async function offScreenCell(+ page: Page,+ text: string,+ axis: "x" | "both",+): Promise<Locator> {+ const cell = page.locator(".marimo-cell").filter({ hasText: text });+ await expect(cell).toHaveCount(1);+ await expect(cell).not.toBeInViewport();++ const viewport = page.viewportSize();+ const box = await cell.boundingBox();+ if (!viewport || !box) {+ throw new Error(`could not measure the "${text}" cell`);+ }+ expect(box.x).toBeGreaterThanOrEqual(viewport.width);+ if (axis === "both") {+ expect(box.y).toBeGreaterThanOrEqual(viewport.height);+ }++ return cell;+}++/**+ * Returns the column 3 cell holding `far_away_variable = 42`, which starts+ * off-screen horizontally only.+ */+async function setUpColumnsNotebook(page: Page): Promise<Locator> {+ await waitForCellsToRun(page);+ return offScreenCell(page, "far_away_variable = 42", "x");+}++/**+ * Cmd/Ctrl + click a usage to jump to its definition. Go-to-definition only+ * arms on a modifier keydown, and only resolves a target once a mousemove+ * while the modifier is held has marked the token -- so drive+ * keydown -> hover -> click explicitly.+ *+ * Cross-cell jumps resolve through the kernel's variable registry. Waiting+ * for `.mo-cm-reactive-reference` (not the AST `.underline` fallback) is what+ * proves that registry is ready; without it the click arms but cannot find+ * the defining cell.+ */+async function jumpToDefinition(+ page: Page,+ variableName: string,+): Promise<void> {+ const usage = page+ .locator(".cm-content")+ .first()+ .locator(".mo-cm-reactive-reference")+ .getByText(variableName, { exact: true })+ .first();+ await expect(usage).toBeVisible({ timeout: 30_000 });++ const modifier = process.platform === "darwin" ? "Meta" : "Control";+ await page.keyboard.down(modifier);+ await usage.hover();++ // Guard: if the token never marks, the click below is a no-op and the+ // test would fail for reasons unrelated to scrolling.+ await expect(+ page.locator(".mo-cm-reactive-reference-hover").first(),+ ).toBeVisible();++ await usage.click();+ await page.keyboard.up(modifier);+}++test("jump to definition scrolls horizontally to an off-screen column", async ({+ page,+}) => {+ const definitionCell = await setUpColumnsNotebook(page);++ // Cmd/Ctrl + click the usage in column 0; its definition is in column 3.+ await jumpToDefinition(page, "far_away_variable");++ await expect(definitionCell).toBeInViewport({ ratio: 0.5 });+});++test("jump to definition scrolls both vertically and horizontally to an off-screen cell", async ({+ page,+}) => {+ await waitForCellsToRun(page);+ // Column 4 has a tall filler cell above this one, so it starts off-screen+ // below the fold as well as to the right -- unlike far_away_variable,+ // which only needs a horizontal scroll.+ const definitionCell = await offScreenCell(+ page,+ "deep_and_far_variable = 99",+ "both",+ );++ await jumpToDefinition(page, "deep_and_far_variable");++ await expect(definitionCell).toBeInViewport({ ratio: 0.5 });+});++test("find next scrolls horizontally to a match in an off-screen column", async ({+ page,+}) => {+ const definitionCell = await setUpColumnsNotebook(page);++ // Focus a cell so the cell-scoped find/replace shortcut applies.+ await page.locator(".cm-content").first().click();+ await pressShortcut(page, "cell.findAndReplace");++ const findInput = page.getByTestId("find-input");+ await expect(findInput).toBeVisible();+ await findInput.fill("far_away_variable");++ // Two matches in column 0, then the definition in column 3. Stepping+ // through the in-cell matches first is what looked like search being+ // "stuck": the selection advanced, but the viewport never followed.+ const findNext = page.getByTestId("find-next-button");+ await findNext.click();+ await findNext.click();+ await findNext.click();++ await expect(definitionCell).toBeInViewport({ ratio: 0.5 });+});diff --git a/frontend/e2e-tests/py/columns.py b/frontend/e2e-tests/py/columns.pynew file mode 100644index 0000000000..ceba2a9b19--- /dev/null+++ b/frontend/e2e-tests/py/columns.py@@ -0,0 +1,62 @@+# /// script+# [tool.marimo.runtime]+# auto_instantiate = true+# ///+import marimo++__generated_with = "0.0.5"+app = marimo.App(width="columns")++[email protected](column=0)+def __(deep_and_far_variable, far_away_variable):+ # Two matches in this cell, so find-next must step through both before+ # leaving the column.+ usage_of_far_away = far_away_variable + 1+ another_usage = far_away_variable * 2+ usage_of_deep_and_far = deep_and_far_variable + 1+ return (another_usage, usage_of_deep_and_far, usage_of_far_away)++[email protected](column=1)+def __():+ filler_one = "filler"+ return (filler_one,)++[email protected](column=2)+def __():+ filler_two = "filler"+ return (filler_two,)++[email protected](column=3)+def __():+ far_away_variable = 42+ return (far_away_variable,)++[email protected](column=4)+def __():+ import marimo as mo++ return (mo,)++[email protected](column=4)+def __(mo):+ # Tall enough to push the cell below into needing a vertical scroll too+ # (viewport height is 720px), unlike far_away_variable, which only ever+ # needs a horizontal scroll.+ mo.ui.text_area(value="filler", rows=80, full_width=True)+ return++[email protected](column=4)+def __():+ deep_and_far_variable = 99+ return (deep_and_far_variable,)+++if __name__ == "__main__":+ app.run()diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.tsindex 63f549e2a5..3e74e22d30 100644--- a/frontend/playwright.config.ts+++ b/frontend/playwright.config.ts@@ -37,6 +37,7 @@ const appToOptions = {"bad_button.py": { command: "edit" },"bugs.py": { command: "edit" },"cells.py": { command: "edit" },+ "columns.py": { command: "edit" },"disabled_cells.py": { command: "edit" },"disabled_ancestor_error.py": { command: "edit" },"kitchen_sink.py": { command: "edit" },diff --git a/frontend/src/core/codemirror/find-replace/__tests__/navigate.test.ts b/frontend/src/core/codemirror/find-replace/__tests__/navigate.test.tsindex 598d49c8e2..1720552d22 100644--- a/frontend/src/core/codemirror/find-replace/__tests__/navigate.test.ts+++ b/frontend/src/core/codemirror/find-replace/__tests__/navigate.test.ts@@ -20,6 +20,26 @@ vi.mock("@/core/cells/cells", () => ({getAllEditorViews: () => mockGetAllEditorViews(),}));+/**+ * A view stub that only carries what navigate needs+ */+function createMockView(state: EditorState): EditorView {+ const cell = document.createElement("div");+ cell.className = "marimo-cell";+ // jsdom doesn't implement scrollIntoView.+ cell.scrollIntoView = vi.fn();+ const dom = document.createElement("div");+ cell.append(dom);++ return {+ state,+ dom,+ // Don't actually apply changes; it's complex to mock properly and the+ // assertions only care that dispatch was called.+ dispatch: vi.fn(),+ } as unknown as EditorView;+}+describe("navigate", () => {let view1: EditorView;let view2: EditorView;@@ -36,20 +56,8 @@ describe("navigate", () => {});// Create mock views that track dispatch calls- view1 = {- state: state1,- dispatch: vi.fn(() => {- // Mock dispatch - in real tests we just need to verify it was called- // Don't actually apply changes as it's complex to mock properly- }),- } as unknown as EditorView;-- view2 = {- state: state2,- dispatch: vi.fn(() => {- // Mock dispatch - in real tests we just need to verify it was called- }),- } as unknown as EditorView;+ view1 = createMockView(state1);+ view2 = createMockView(state2);mockViews = [view1, view2];mockGetAllEditorViews.mockReturnValue(mockViews);@@ -234,6 +242,22 @@ describe("navigate", () => {expect(result).toBe(false);});++ it("should scroll the cell owning the match into view", async () => {+ const cell = view1.dom.closest(".marimo-cell");+ invariant(cell, "mock view should be inside a cell");++ expect(findNext()).toBeTruthy();++ // The scroll is deferred a frame.+ await new Promise((resolve) => requestAnimationFrame(resolve));++ expect(cell.scrollIntoView).toHaveBeenCalledWith({+ behavior: "instant",+ block: "nearest",+ inline: "nearest",+ });+ });});describe("findPrev", () => {@@ -319,10 +343,7 @@ describe("navigate", () => {extensions: [EditorState.readOnly.of(true)],});- const readOnlyView = {- state: readOnlyState,- dispatch: vi.fn(),- } as unknown as EditorView;+ const readOnlyView = createMockView(readOnlyState);// Replace view1 with read-only view temporarilymockGetAllEditorViews.mockReturnValueOnce([readOnlyView, view2]);@@ -568,10 +589,7 @@ describe("navigate", () => {doc: Text.of(["hello world hello there hello"]),});- const testView = {- state: testDoc,- dispatch: vi.fn(),- } as unknown as EditorView;+ const testView = createMockView(testDoc);mockGetAllEditorViews.mockReturnValue([testView]);@@ -613,10 +631,7 @@ describe("navigate", () => {doc: Text.of([""]),});- const emptyView = {- state: emptyState,- dispatch: vi.fn(),- } as unknown as EditorView;+ const emptyView = createMockView(emptyState);mockGetAllEditorViews.mockReturnValue([emptyView]);@@ -629,10 +644,7 @@ describe("navigate", () => {doc: Text.of(["orphan content"]),});- const orphanView = {- state: orphanState,- dispatch: vi.fn(),- } as unknown as EditorView;+ const orphanView = createMockView(orphanState);store.set(findReplaceAtom, {type: "setCurrentView",diff --git a/frontend/src/core/codemirror/find-replace/navigate.ts b/frontend/src/core/codemirror/find-replace/navigate.tsindex 4e39f7c050..7b8d90f82e 100644--- a/frontend/src/core/codemirror/find-replace/navigate.ts+++ b/frontend/src/core/codemirror/find-replace/navigate.ts@@ -6,6 +6,7 @@ import { EditorView } from "@codemirror/view";import { getAllEditorViews } from "@/core/cells/cells";import { replaceEditorContent } from "@/core/codemirror/replace-editor-content";import { store } from "@/core/state/jotai";+import { scrollOwnerCell } from "../utils";import { asQueryCreator, type QueryType } from "./query";import { findReplaceAtom } from "./state";@@ -85,6 +86,7 @@ const findInDirection = (direction: "next" | "prev") =>effects: [EditorView.scrollIntoView(selection.main, { y: "center" })],userEvent: "select.search",});+ scrollOwnerCell(view);store.set(findReplaceAtom, {type: "setCurrentView",view,diff --git a/frontend/src/core/codemirror/go-to-definition/__tests__/commands.test.ts b/frontend/src/core/codemirror/go-to-definition/__tests__/commands.test.tsindex 8dbf2b0193..b6f41eec7e 100644--- a/frontend/src/core/codemirror/go-to-definition/__tests__/commands.test.ts+++ b/frontend/src/core/codemirror/go-to-definition/__tests__/commands.test.ts@@ -3,14 +3,14 @@import { python } from "@codemirror/lang-python";import { EditorState } from "@codemirror/state";import { EditorView } from "@codemirror/view";-import { afterEach, describe, expect, test } from "vitest";+import { afterEach, describe, expect, test, vi } from "vitest";import { goToVariableDefinition } from "../commands";async function tick(): Promise<void> {await new Promise((resolve) => requestAnimationFrame(resolve));}-function createEditor(content: string) {+function createEditor(content: string, parent: HTMLElement = document.body) {const state = EditorState.create({doc: content,extensions: [python()],@@ -18,7 +18,7 @@ function createEditor(content: string) {const view = new EditorView({state,- parent: document.body,+ parent,});return view;@@ -383,6 +383,27 @@ print('myVar')`);"`);});++ test("scrolls the cell owning the definition into view", async () => {+ const cell = document.createElement("div");+ cell.className = "marimo-cell";+ // jsdom doesn't implement scrollIntoView.+ cell.scrollIntoView = vi.fn();+ document.body.append(cell);++ view = createEditor("myVar = 10\nprint(myVar)", cell);+ expect(goToVariableDefinition(view, "myVar")).toBe(true);+ // The jump and the scroll are both deferred to the next frame.+ await tick();++ expect(cell.scrollIntoView).toHaveBeenCalledWith({+ behavior: "instant",+ block: "nearest",+ inline: "nearest",+ });++ cell.remove();+ });});/**diff --git a/frontend/src/core/codemirror/go-to-definition/commands.ts b/frontend/src/core/codemirror/go-to-definition/commands.tsindex f329c402db..1a435d67b3 100644--- a/frontend/src/core/codemirror/go-to-definition/commands.ts+++ b/frontend/src/core/codemirror/go-to-definition/commands.ts@@ -4,6 +4,7 @@ import { syntaxTree } from "@codemirror/language";import type { EditorState } from "@codemirror/state";import { EditorView } from "@codemirror/view";import type { SyntaxNode, Tree, TreeCursor } from "@lezer/common";+import { scrollOwnerCell } from "../utils";const SCOPE_CREATING_NODES = new Set(["FunctionDefinition",@@ -45,6 +46,8 @@ function goToPosition(view: EditorView, from: number): void {}),});});++ scrollOwnerCell(view);}function findFirstMatchingVariable(diff --git a/frontend/src/core/codemirror/utils.ts b/frontend/src/core/codemirror/utils.tsindex 5818b23332..3c34b5f2b7 100644--- a/frontend/src/core/codemirror/utils.ts+++ b/frontend/src/core/codemirror/utils.ts@@ -52,6 +52,34 @@ export function focusInputAndMoveToEnd(});}+/**+ * Scrolls the `.marimo-cell` that owns `view` into view.+ *+ * `EditorView.scrollIntoView` doesn't work in columns mode: it stops at the+ * first overflowing ancestor even if that ancestor doesn't actually scroll,+ * so it never reaches the real horizontally-scrolling container. The+ * browser's native `Element.scrollIntoView` doesn't have that problem.+ *+ * Deferred a frame so CodeMirror's own scroll settles first; otherwise it+ * clamps this scroll right back.+ *+ * https://github.com/marimo-team/marimo/issues/10222+ */+export function scrollOwnerCell(view: EditorView): void {+ const cell = view.dom.closest(".marimo-cell");+ if (!cell) {+ return;+ }++ requestAnimationFrame(() => {+ cell.scrollIntoView({+ behavior: "instant",+ block: "nearest",+ inline: "nearest",+ });+ });+}+export function isInVimMode(ev: EditorView): boolean {return getCM(ev)?.state.vim != null;}