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: focus on editors and buttons after layout shift from hidden code (#7489)
Myles Scolnick9afb9288ca77
diff --git a/frontend/src/components/editor/cell/cell-actions.tsx b/frontend/src/components/editor/cell/cell-actions.tsxindex 2f9750ace9..c0f6f3095d 100644--- a/frontend/src/components/editor/cell/cell-actions.tsx+++ b/frontend/src/components/editor/cell/cell-actions.tsx@@ -8,8 +8,10 @@ import React, {type PropsWithChildren,useImperativeHandle,useMemo,+ useRef,useState,} from "react";+import useEvent from "react-use-event-hook";import {renderMinimalShortcut,renderShortcut,@@ -41,6 +43,7 @@ import {type CellActionButtonProps,useCellActionButtons,} from "../actions/useCellActionButton";+import { raf2 } from "../navigation/focus-utils";interface Props extends CellActionButtonProps {children: React.ReactNode;@@ -57,13 +60,41 @@ const CellActionsDropdownInternal = () => {const [open, setOpen] = useState(false);const closePopover = () => setOpen(false);+ const buttonRef = useRef<HTMLButtonElement>(null);const actions = useCellActionButtons({ cell: props, closePopover });// store the last focused element so we can restore it when the popover closesconst restoreFocus = useRestoreFocus();+ const handleScrollIntoView = useEvent(() => {+ raf2(() => {+ if (buttonRef.current) {+ buttonRef.current.scrollIntoView({+ behavior: "auto",+ block: "nearest",+ });+ }+ });+ });++ const handleOpenChange: typeof setOpen = useEvent((nextOpenOrCallback) => {+ // Scroll the button into view when opening the popover+ // This can be out of view if the popover and a cell's code is+ // hidden at the same time.+ setOpen((prevOpen) => {+ const nextOpen =+ typeof nextOpenOrCallback === "function"+ ? nextOpenOrCallback(prevOpen)+ : nextOpenOrCallback;+ if (nextOpen) {+ handleScrollIntoView();+ }+ return nextOpen;+ });+ });+useImperativeHandle(ref, () => ({- toggle: () => setOpen((prev) => !prev),+ toggle: () => handleOpenChange((prev) => !prev),}));const content = (@@ -136,7 +167,7 @@ const CellActionsDropdownInternal = (if (!showTooltip) {return (- <Popover open={open} onOpenChange={setOpen}>+ <Popover open={open} onOpenChange={handleOpenChange}><PopoverTrigger asChild={true}>{children}</PopoverTrigger>{content}</Popover>@@ -150,13 +181,13 @@ const CellActionsDropdownInternal = ();return (- <Popover open={open} onOpenChange={setOpen}>+ <Popover open={open} onOpenChange={handleOpenChange}><TooltipRoot delayDuration={200} disableHoverableContent={true}>{!open && tooltipContent}{/* This creates a warning in React due to nested <button> elements.Adding asChild could fix this, but it also changes the styling (is hidden) of the button whenthe Popover is open. */}- <TooltipTrigger>+ <TooltipTrigger ref={buttonRef}><PopoverTrigger className="flex">{children}</PopoverTrigger></TooltipTrigger></TooltipRoot>diff --git a/frontend/src/components/editor/navigation/__tests__/focus-utils.test.ts b/frontend/src/components/editor/navigation/__tests__/focus-utils.test.tsnew file mode 100644index 0000000000..978bce8bdc--- /dev/null+++ b/frontend/src/components/editor/navigation/__tests__/focus-utils.test.ts@@ -0,0 +1,20 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, expect, it, vi } from "vitest";+import { raf2 } from "../focus-utils";++describe("raf2", () => {+ it("should call callback after two animation frames", async () => {+ const callback = vi.fn();++ raf2(callback);++ expect(callback).not.toHaveBeenCalled();++ await new Promise((resolve) => requestAnimationFrame(resolve));+ expect(callback).not.toHaveBeenCalled();++ await new Promise((resolve) => requestAnimationFrame(resolve));+ expect(callback).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts b/frontend/src/components/editor/navigation/__tests__/navigation.test.tsindex 37872e57da..357baf079e 100644--- a/frontend/src/components/editor/navigation/__tests__/navigation.test.ts+++ b/frontend/src/components/editor/navigation/__tests__/navigation.test.ts@@ -51,6 +51,8 @@ vi.mock("../clipboard", () => ({vi.mock("../focus-utils", () => ({focusCellEditor: vi.fn(),focusCell: vi.fn(),+ scrollCellIntoView: vi.fn(),+ raf2: vi.fn((callback: () => void) => callback()),}));// Mock simplifySelection from @codemirror/commandsdiff --git a/frontend/src/components/editor/navigation/__tests__/state.test.ts b/frontend/src/components/editor/navigation/__tests__/state.test.tsnew file mode 100644index 0000000000..1824ed90b3--- /dev/null+++ b/frontend/src/components/editor/navigation/__tests__/state.test.ts@@ -0,0 +1,80 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { type CellId, HTMLCellId } from "@/core/cells/ids";++const mockScrollCellIntoView = vi.fn();+const mockRaf2 = vi.fn((callback: () => void) => callback());++vi.mock("../focus-utils", () => ({+ scrollCellIntoView: mockScrollCellIntoView,+ raf2: mockRaf2,+}));++type TemporarilyShownCodeState = Set<CellId>;++describe("temporarilyShownCodeActions", () => {+ const cellId = "cell-1" as CellId;+ let cellElement: HTMLElement;++ beforeEach(() => {+ cellElement = document.createElement("div");+ cellElement.id = HTMLCellId.create(cellId);+ document.body.append(cellElement);+ cellElement.focus();++ vi.spyOn(HTMLCellId, "findElementThroughShadowDOMs").mockReturnValue(+ cellElement as HTMLElement & { id: HTMLCellId },+ );++ mockScrollCellIntoView.mockClear();+ mockRaf2.mockClear();+ });++ afterEach(() => {+ cellElement.remove();+ vi.restoreAllMocks();+ });++ it("should scroll cell into view when removing cell causes layout shift", () => {+ const state = new Set<CellId>([cellId]);+ removeCell(state, cellId);++ expect(mockScrollCellIntoView).toHaveBeenCalledWith(cellId);+ });++ it("should not scroll when focused cell is not found", () => {+ vi.spyOn(HTMLCellId, "findElementThroughShadowDOMs").mockReturnValue(null);++ const state = new Set<CellId>([cellId]);+ removeCell(state, cellId);++ expect(mockScrollCellIntoView).not.toHaveBeenCalled();+ });+});++// Helper function that replicates the remove reducer logic+function removeCell(+ state: TemporarilyShownCodeState,+ cellId: CellId,+): TemporarilyShownCodeState {+ if (!state.has(cellId)) {+ return state;+ }+ const newState = new Set(state);+ newState.delete(cellId);++ mockRaf2(() => {+ const activeElement = document.activeElement;+ if (!activeElement) {+ return;+ }+ const focusedCell = HTMLCellId.findElementThroughShadowDOMs(activeElement);+ if (!focusedCell) {+ return;+ }+ mockScrollCellIntoView(HTMLCellId.parse(focusedCell.id));+ });++ return newState;+}diff --git a/frontend/src/components/editor/navigation/focus-utils.ts b/frontend/src/components/editor/navigation/focus-utils.tsindex 4e9f7c07e4..0ea036ad25 100644--- a/frontend/src/components/editor/navigation/focus-utils.ts+++ b/frontend/src/components/editor/navigation/focus-utils.ts@@ -1,7 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import type { createStore } from "jotai";-import { notebookAtom } from "@/core/cells/cells";+import { getCellEditorView } from "@/core/cells/cells";import { type CellId, HTMLCellId } from "@/core/cells/ids";import { Logger } from "@/utils/Logger";@@ -9,8 +9,7 @@ export function focusCellEditor(store: ReturnType<typeof createStore>,cellId: CellId,): void {- const editor =- store.get(notebookAtom).cellHandles[cellId]?.current?.editorView;+ const editor = getCellEditorView(cellId);if (editor) {editor.focus();} else {@@ -29,6 +28,16 @@ export function focusCell(cellId: CellId): void {}}+/**+ * Run a callback after two frames.+ * It is somewhat common/safer to run code after two frames to ensure the DOM is fully rendered.+ */+export function raf2(callback: () => void): void {+ requestAnimationFrame(() => {+ requestAnimationFrame(callback);+ });+}+/*** Checks if the cell is focused at the top level.*/diff --git a/frontend/src/components/editor/navigation/navigation.ts b/frontend/src/components/editor/navigation/navigation.tsindex 4541cbd833..ff9026ae53 100644--- a/frontend/src/components/editor/navigation/navigation.ts+++ b/frontend/src/components/editor/navigation/navigation.ts@@ -12,6 +12,7 @@ import { useCellFocusActions } from "@/core/cells/focus";import type { CellId } from "@/core/cells/ids";import { HTMLCellId } from "@/core/cells/ids";import { usePendingDeleteService } from "@/core/cells/pending-delete-service";+import { scrollCellIntoView } from "@/core/cells/scrollCellIntoView";import {hotkeysAtom,keymapPresetAtom,@@ -27,7 +28,7 @@ import type { CellActionsDropdownHandle } from "../cell/cell-actions";import { useDeleteManyCellsCallback } from "../cell/useDeleteCell";import { useRunCells } from "../cell/useRunCells";import { useCellClipboard } from "./clipboard";-import { focusCell, focusCellEditor } from "./focus-utils";+import { focusCell, focusCellEditor, raf2 } from "./focus-utils";import {getSelectedCells,useCellSelectionActions,@@ -620,6 +621,10 @@ export function useCellEditorNavigationProps(const exitToCommandMode = () => {temporarilyShownCodeActions.remove(cellId);focusCell(cellId);+ // Scroll to cell in case it is not in view because of layout shifts.+ raf2(() => {+ scrollCellIntoView(cellId);+ });};const handleEscape = () => {diff --git a/frontend/src/components/editor/navigation/state.ts b/frontend/src/components/editor/navigation/state.tsindex d2f2e94756..dec8d7cd18 100644--- a/frontend/src/components/editor/navigation/state.ts+++ b/frontend/src/components/editor/navigation/state.ts@@ -2,8 +2,10 @@import { atom, useAtomValue } from "jotai";import { useMemo } from "react";-import type { CellId } from "@/core/cells/ids";+import { type CellId, HTMLCellId } from "@/core/cells/ids";+import { scrollCellIntoView } from "@/core/cells/scrollCellIntoView";import { createReducerAndAtoms } from "@/utils/createReducer";+import { raf2 } from "./focus-utils";type TemporarilyShownCodeState = Set<CellId>;@@ -15,13 +17,39 @@ const {useActions: useTemporarilyShownCodeActions,} = createReducerAndAtoms(() => new Set<CellId>(), {add: (state: TemporarilyShownCodeState, cellId: CellId) => {+ if (state.has(cellId)) {+ // no-op+ return state;+ }const newState = new Set(state);newState.add(cellId);return newState;},remove: (state: TemporarilyShownCodeState, cellId: CellId) => {+ if (!state.has(cellId)) {+ // no-op+ return state;+ }const newState = new Set(state);newState.delete(cellId);++ // If we are hiding the code, this will cause a layout shift+ // so we need to scroll cursor/activeElement into view.+ raf2(() => {+ // Get the active+ const activeElement = document.activeElement;+ if (!activeElement) {+ return;+ }+ // Get the current focused cell id+ const focusedCell =+ HTMLCellId.findElementThroughShadowDOMs(activeElement);+ if (!focusedCell) {+ return;+ }+ scrollCellIntoView(HTMLCellId.parse(focusedCell.id));+ });+return newState;},});diff --git a/frontend/src/core/cells/__tests__/scrollCellIntoView.test.ts b/frontend/src/core/cells/__tests__/scrollCellIntoView.test.tsnew file mode 100644index 0000000000..a7616b8cc1--- /dev/null+++ b/frontend/src/core/cells/__tests__/scrollCellIntoView.test.ts@@ -0,0 +1,74 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { type CellId, HTMLCellId } from "@/core/cells/ids";+import { Logger } from "@/utils/Logger";++// Mock the getCellEditorView function+const mockGetCellEditorView = vi.fn();+vi.mock("@/core/cells/cells", () => ({+ getCellEditorView: mockGetCellEditorView,+}));++// Mock the scrollActiveLineIntoView function+const mockScrollActiveLineIntoView = vi.fn();+vi.mock("@/core/codemirror/extensions", () => ({+ scrollActiveLineIntoView: mockScrollActiveLineIntoView,+}));++// Import after mocking+const { scrollCellIntoView } = await import("@/core/cells/scrollCellIntoView");++describe("scrollCellIntoView", () => {+ const cellId = "test-cell-id" as CellId;+ let cellElement: HTMLElement;++ beforeEach(() => {+ cellElement = document.createElement("div");+ cellElement.id = HTMLCellId.create(cellId);+ cellElement.scrollIntoView = vi.fn();+ document.body.append(cellElement);++ mockGetCellEditorView.mockReturnValue(undefined);+ mockScrollActiveLineIntoView.mockClear();+ });++ afterEach(() => {+ cellElement.remove();+ });++ it("should scroll active line when editor has focus", () => {+ const mockEditor = { hasFocus: true };+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ mockGetCellEditorView.mockReturnValue(mockEditor as any);++ scrollCellIntoView(cellId);++ expect(mockScrollActiveLineIntoView).toHaveBeenCalledWith(mockEditor, {+ behavior: "instant",+ });+ expect(cellElement.scrollIntoView).not.toHaveBeenCalled();+ });++ it("should scroll cell element when editor is not focused", () => {+ scrollCellIntoView(cellId);++ expect(mockScrollActiveLineIntoView).not.toHaveBeenCalled();+ expect(cellElement.scrollIntoView).toHaveBeenCalledWith({+ behavior: "instant",+ block: "nearest",+ });+ });++ it("should log warning when cell element is not found", () => {+ const warnSpy = vi.spyOn(Logger, "warn").mockImplementation(vi.fn());+ cellElement.remove();++ scrollCellIntoView(cellId);++ expect(warnSpy).toHaveBeenCalledWith(+ `[CellFocusManager] scrollCellIntoView: element not found: ${cellId}`,+ );+ warnSpy.mockRestore();+ });+});diff --git a/frontend/src/core/cells/scrollCellIntoView.ts b/frontend/src/core/cells/scrollCellIntoView.tsindex 121023290b..527ce7b803 100644--- a/frontend/src/core/cells/scrollCellIntoView.ts+++ b/frontend/src/core/cells/scrollCellIntoView.ts@@ -7,7 +7,9 @@ import {import type { CellHandle } from "@/components/editor/notebook-cell";import { retryWithTimeout } from "@/utils/timeout";import { Logger } from "../../utils/Logger";+import { scrollActiveLineIntoView } from "../codemirror/extensions";import { goToVariableDefinition } from "../codemirror/go-to-definition/commands";+import { getCellEditorView } from "./cells";import { type CellId, HTMLCellId } from "./ids";export function focusAndScrollCellIntoView({@@ -131,3 +133,25 @@ export function scrollToTop() {const app = document.getElementById("App");app?.scrollTo({ top: 0, behavior: "smooth" });}++/**+ * First tries to scroll the active line into view, if the cell is focused.+ * If not, it scrolls the cell container into view.+ */+export function scrollCellIntoView(cellId: CellId): void {+ // Get cell editor element+ const editor = getCellEditorView(cellId);+ if (editor?.hasFocus) {+ scrollActiveLineIntoView(editor, { behavior: "instant" });+ return;+ }++ const element = document.getElementById(HTMLCellId.create(cellId));+ if (element) {+ element.scrollIntoView({ behavior: "instant", block: "nearest" });+ } else {+ Logger.warn(+ `[CellFocusManager] scrollCellIntoView: element not found: ${cellId}`,+ );+ }+}diff --git a/frontend/src/core/codemirror/__tests__/extensions.test.ts b/frontend/src/core/codemirror/__tests__/extensions.test.tsindex 4ee2bdf55d..cc06989aa2 100644--- a/frontend/src/core/codemirror/__tests__/extensions.test.ts+++ b/frontend/src/core/codemirror/__tests__/extensions.test.ts@@ -4,7 +4,10 @@ import { EditorState } from "@codemirror/state";import { EditorView } from "@codemirror/view";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import * as scrollUtils from "../../../utils/scroll";-import { scrollActiveLineIntoView } from "../extensions";+import {+ scrollActiveLineIntoView,+ scrollActiveLineIntoViewExtension,+} from "../extensions";import { formattingChangeEffect } from "../format";// Mock the smartScrollIntoView function@@ -12,7 +15,7 @@ vi.mock("../../../utils/scroll", () => ({smartScrollIntoView: vi.fn(),}));-describe("scrollActiveLineIntoView", () => {+describe("scrollActiveLineIntoViewExtension", () => {let view: EditorView;let mockAppElement: HTMLElement;@@ -26,7 +29,7 @@ describe("scrollActiveLineIntoView", () => {view = new EditorView({state: EditorState.create({doc: "line 1\nline 2\nline 3",- extensions: [scrollActiveLineIntoView()],+ extensions: [scrollActiveLineIntoViewExtension()],}),});@@ -76,6 +79,7 @@ describe("scrollActiveLineIntoView", () => {{offset: { top: 30, bottom: 150 },body: mockAppElement,+ behavior: "smooth",},);});@@ -115,3 +119,89 @@ describe("scrollActiveLineIntoView", () => {expect(vi.mocked(scrollUtils.smartScrollIntoView)).not.toHaveBeenCalled();});});++describe("scrollActiveLineIntoView function", () => {+ let view: EditorView;+ let mockAppElement: HTMLElement;++ beforeEach(() => {+ // Create a mock App element+ mockAppElement = document.createElement("div");+ mockAppElement.id = "App";+ document.body.append(mockAppElement);++ // Create an editor view without the extension+ view = new EditorView({+ state: EditorState.create({+ doc: "line 1\nline 2\nline 3",+ }),+ });++ document.body.append(view.dom);++ // Reset the mock+ vi.mocked(scrollUtils.smartScrollIntoView).mockClear();+ });++ afterEach(() => {+ view.destroy();+ mockAppElement.remove();+ if (document.body.contains(view.dom)) {+ view.dom.remove();+ }+ });++ it("should scroll with smooth behavior", () => {+ const activeLine = document.createElement("div");+ activeLine.className = "cm-activeLine cm-line";+ view.dom.append(activeLine);++ scrollActiveLineIntoView(view, { behavior: "smooth" });++ expect(vi.mocked(scrollUtils.smartScrollIntoView)).toHaveBeenCalledWith(+ activeLine,+ {+ offset: { top: 30, bottom: 150 },+ body: mockAppElement,+ behavior: "smooth",+ },+ );+ });++ it("should scroll with instant behavior", () => {+ const activeLine = document.createElement("div");+ activeLine.className = "cm-activeLine cm-line";+ view.dom.append(activeLine);++ scrollActiveLineIntoView(view, { behavior: "instant" });++ expect(vi.mocked(scrollUtils.smartScrollIntoView)).toHaveBeenCalledWith(+ activeLine,+ {+ offset: { top: 30, bottom: 150 },+ body: mockAppElement,+ behavior: "instant",+ },+ );+ });++ it("should not scroll when there is no active line", () => {+ scrollActiveLineIntoView(view, { behavior: "instant" });++ expect(vi.mocked(scrollUtils.smartScrollIntoView)).not.toHaveBeenCalled();+ });++ it("should not scroll when there are multiple active lines", () => {+ const activeLine1 = document.createElement("div");+ activeLine1.className = "cm-activeLine cm-line";+ view.dom.append(activeLine1);++ const activeLine2 = document.createElement("div");+ activeLine2.className = "cm-activeLine cm-line";+ view.dom.append(activeLine2);++ scrollActiveLineIntoView(view, { behavior: "instant" });++ expect(vi.mocked(scrollUtils.smartScrollIntoView)).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/core/codemirror/cm.ts b/frontend/src/core/codemirror/cm.tsindex 664d4d35d2..702261ba64 100644--- a/frontend/src/core/codemirror/cm.ts+++ b/frontend/src/core/codemirror/cm.ts@@ -57,7 +57,7 @@ import { completionKeymap } from "./completion/keymap";import { cellConfigExtension } from "./config/extension";import { copilotBundle } from "./copilot/extension";import { historyCompartment } from "./editing/extensions";-import { scrollActiveLineIntoView } from "./extensions";+import { scrollActiveLineIntoViewExtension } from "./extensions";import { findReplaceBundle } from "./find-replace/extension";import { goToDefinitionBundle } from "./go-to-definition/extension";import { keymapBundle } from "./keymaps/keymaps";@@ -201,7 +201,7 @@ export const basicBundle = (opts: CodeMirrorSetupOpts): Extension[] => {// For example, if we have a hover tooltip and a completion tooltipparent: document.querySelector<HTMLElement>("#App") ?? undefined,}),- scrollActiveLineIntoView(),+ scrollActiveLineIntoViewExtension(),theme === "dark" ? darkTheme : lightTheme,hintTooltip(lspConfig),diff --git a/frontend/src/core/codemirror/extensions.ts b/frontend/src/core/codemirror/extensions.tsindex 6f5f94cabd..fa17b7f0f3 100644--- a/frontend/src/core/codemirror/extensions.ts+++ b/frontend/src/core/codemirror/extensions.ts@@ -60,7 +60,7 @@ export function formatKeymapExtension(hotkeys: HotkeyProvider) {* This is necessary when typings at the edges of the editor* and the user is blocked by the hovering action bar.*/-export function scrollActiveLineIntoView() {+export function scrollActiveLineIntoViewExtension() {return EditorView.updateListener.of((update) => {// Ignore if the editor does not have focus, ignoreif (!update.view.hasFocus) {@@ -77,19 +77,29 @@ export function scrollActiveLineIntoView() {return;}- const activeLines = update.view.dom.getElementsByClassName(- "cm-activeLine cm-line",- );- // Only scroll if there is an active line- if (activeLines.length === 1) {- const activeLine = activeLines[0] as HTMLElement;- const appEl = document.getElementById("App");- invariant(appEl, "App not found");- smartScrollIntoView(activeLine, {- offset: { top: 30, bottom: 150 },- body: appEl,- });- }+ scrollActiveLineIntoView(update.view, { behavior: "smooth" });}});}++export function scrollActiveLineIntoView(+ editor: EditorView,+ opts: {+ behavior: "smooth" | "instant";+ },+) {+ const activeLines = editor.dom.getElementsByClassName(+ "cm-activeLine cm-line",+ );+ // Only scroll if there is an active line+ if (activeLines.length === 1) {+ const activeLine = activeLines[0] as HTMLElement;+ const appEl = document.getElementById("App");+ invariant(appEl, "App not found");+ smartScrollIntoView(activeLine, {+ offset: { top: 30, bottom: 150 },+ body: appEl,+ behavior: opts.behavior,+ });+ }+}diff --git a/frontend/src/utils/__tests__/scroll.test.ts b/frontend/src/utils/__tests__/scroll.test.tsnew file mode 100644index 0000000000..70b868b2ab--- /dev/null+++ b/frontend/src/utils/__tests__/scroll.test.ts@@ -0,0 +1,114 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { beforeEach, describe, expect, it, vi } from "vitest";+import { smartScrollIntoView } from "../scroll";++describe("smartScrollIntoView", () => {+ let element: HTMLElement;+ let mockScrollBy: ReturnType<typeof vi.fn>;++ const mockRect = (top: number, bottom: number): DOMRect => ({+ top,+ bottom,+ left: 0,+ right: 100,+ width: 100,+ height: 100,+ x: 0,+ y: top,+ toJSON: () => ({}),+ });++ beforeEach(() => {+ element = document.createElement("div");+ document.body.append(element);++ mockScrollBy = vi.fn();+ window.scrollBy = mockScrollBy;++ Object.defineProperty(window, "innerHeight", {+ writable: true,+ configurable: true,+ value: 1000,+ });+ });++ it("should scroll when element is above viewport", () => {+ vi.spyOn(element, "getBoundingClientRect").mockReturnValue(+ mockRect(-50, 50),+ );++ smartScrollIntoView(element, {+ offset: { top: 10, bottom: 20 },+ });++ expect(mockScrollBy).toHaveBeenCalledWith({+ top: -60,+ behavior: "smooth",+ });+ });++ it("should scroll when element is below viewport", () => {+ vi.spyOn(element, "getBoundingClientRect").mockReturnValue(+ mockRect(950, 1050),+ );++ smartScrollIntoView(element, {+ offset: { top: 10, bottom: 20 },+ });++ expect(mockScrollBy).toHaveBeenCalledWith({+ top: 70,+ behavior: "smooth",+ });+ });++ it("should not scroll when element is in view", () => {+ vi.spyOn(element, "getBoundingClientRect").mockReturnValue(+ mockRect(100, 200),+ );++ smartScrollIntoView(element, {+ offset: { top: 10, bottom: 20 },+ });++ expect(mockScrollBy).not.toHaveBeenCalled();+ });++ it("should respect behavior parameter", () => {+ vi.spyOn(element, "getBoundingClientRect").mockReturnValue(+ mockRect(-50, 50),+ );++ smartScrollIntoView(element, {+ offset: { top: 10, bottom: 20 },+ behavior: "instant",+ });++ expect(mockScrollBy).toHaveBeenCalledWith({+ top: -60,+ behavior: "instant",+ });+ });++ it("should scroll custom body element", () => {+ const customBody = document.createElement("div");+ const mockCustomScrollBy = vi.fn();+ customBody.scrollBy = mockCustomScrollBy;++ vi.spyOn(element, "getBoundingClientRect").mockReturnValue(+ mockRect(-50, 50),+ );++ smartScrollIntoView(element, {+ offset: { top: 10, bottom: 20 },+ body: customBody,+ });++ expect(mockCustomScrollBy).toHaveBeenCalledWith({+ top: -60,+ behavior: "smooth",+ });+ expect(mockScrollBy).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/utils/scroll.ts b/frontend/src/utils/scroll.tsindex 609b0ca446..df572b7951 100644--- a/frontend/src/utils/scroll.ts+++ b/frontend/src/utils/scroll.ts@@ -8,9 +8,11 @@ export function smartScrollIntoView({offset,body = window,+ behavior = "smooth",}: {offset?: { top: number; bottom: number };body?: HTMLElement | typeof window;+ behavior?: "smooth" | "instant";},) {const topOffset = offset?.top ?? 0;@@ -21,7 +23,7 @@ export function smartScrollIntoView(// Element is above the viewport, scroll to its topbody.scrollBy({top: rect.top - topOffset,- behavior: "smooth",+ behavior,});return;}@@ -29,7 +31,7 @@ export function smartScrollIntoView(// Element is below the viewport, scroll to its bottombody.scrollBy({top: rect.bottom - window.innerHeight + bottomOffset,- behavior: "smooth",+ behavior,});return;}