Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions frontend/src/__mocks__/intersection-observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,16 @@ export function mockIntersectionObservers() {
unobserve: vi.fn(),
disconnect: vi.fn(),
takeRecords: () => [],
emit(target: Element, visible: boolean) {
observer.emitBatch([[target, visible]]);
emit(target: Element, visible: boolean, intersectionRatio?: number) {
observer.emitBatch([[target, visible, intersectionRatio]]);
},
emitBatch(changes: [Element, boolean][]) {
emitBatch(changes: [Element, boolean, number?][]) {
const rect = new DOMRect();
callback(
changes.map(([target, isIntersecting]) => ({
changes.map(([target, isIntersecting, ratio]) => ({
target,
isIntersecting,
intersectionRatio: isIntersecting ? 1 : 0,
intersectionRatio: ratio ?? (isIntersecting ? 1 : 0),
time: 0,
boundingClientRect: rect,
intersectionRect: rect,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,33 @@ describe("PairWithAgentModal", () => {
expect(screen.getByRole("button", { name: "Copy command" })).toBeDisabled();
});

it("cancels the copy confirmation reset when the modal unmounts", async () => {
vi.useFakeTimers();
const schedule = vi.spyOn(globalThis, "setTimeout");
const cancel = vi.spyOn(globalThis, "clearTimeout");
try {
const { unmount } = await act(async () =>
render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper }),
);
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Copy command" }));
});
expect(copyToClipboard).toHaveBeenCalledOnce();
const resetIndex = schedule.mock.calls.findIndex(
([, delay]) => delay === 2000,
);
expect(resetIndex).toBeGreaterThanOrEqual(0);
const reset = schedule.mock.results[resetIndex].value;

unmount();
expect(cancel).toHaveBeenCalledWith(reset);
} finally {
schedule.mockRestore();
cancel.mockRestore();
vi.useRealTimers();
}
});

it("copies a host mode terminal command without the token and lets the user copy the token separately", async () => {
vi.mocked(fetch).mockImplementation((url) =>
responseFor(url, "secret-token"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,14 +252,21 @@ const CommandBlock: React.FC<{
}) => {
const [copied, setCopied] = useState(false);

useEffect(() => {
if (!copied) {
return;
}
const timeout = setTimeout(() => setCopied(false), 2000);
return () => clearTimeout(timeout);
}, [copied]);

const copy = Events.stopPropagation(async (e) => {
e.preventDefault();
if (disabled) {
return;
}
await copyToClipboard(command);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
});

if (multiline) {
Expand Down
8 changes: 1 addition & 7 deletions frontend/src/components/find-replace/find-replace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ import {
replaceAll,
replaceNext,
} from "@/core/codemirror/find-replace/navigate";
import {
clearGlobalSearchQuery,
setGlobalSearchQuery,
} from "@/core/codemirror/find-replace/search-highlight";
import {
findReplaceAtom,
openFindReplacePanel,
Expand Down Expand Up @@ -68,18 +64,15 @@ export const FindReplace: React.FC = () => {

useEffect(() => {
if (!state.isOpen) {
clearGlobalSearchQuery();
return;
}

if (state.findText === "") {
setMatches(undefined);
clearGlobalSearchQuery();
return;
}

resetMatches();
setGlobalSearchQuery();
}, [
// Re-search when any of these change
state.findText,
Expand Down Expand Up @@ -245,6 +238,7 @@ export const FindReplace: React.FC = () => {
data-testid="undo-replace-all-button"
onClick={() => {
undo();
resetMatches();
dismiss();
}}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */

import { EditorState, Text } from "@codemirror/state";
import { EditorSelection, EditorState, Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cellId } from "@/__tests__/branded";
Expand Down Expand Up @@ -138,23 +138,26 @@ describe("navigate", () => {
expect(state.currentView?.range).toEqual({ from: 0, to: 5 });
});

it("should find next match in different view when current view exhausted", () => {
// Set current position to after last match in view1
store.set(findReplaceAtom, {
type: "setCurrentView",
view: view1,
range: { from: 30, to: 35 },
});
it("skips a selection dispatch when the preceding editor is already reset", () => {
store.set(findReplaceAtom, { type: "setFind", find: "Different" });

const result = findNext();
expect(findNext()).toMatchObject({ from: 14, to: 23 });
expect(view1.dispatch).not.toHaveBeenCalled();
expect(view2.dispatch).toHaveBeenCalledOnce();
expect(store.get(findReplaceAtom).currentView?.cellId).toBe(cell2);
});

expect(result).toBeTruthy();
invariant(result, "findNext should return a result");
// Should find match somewhere (either view1 wraps or view2)
expect(view1.dispatch).toHaveBeenCalled();
it("clears the preceding editor's selection when moving to another editor", () => {
view1 = createMockView(
view1.state.update({ selection: EditorSelection.single(0, 5) }).state,
);
mockGetAllEditorViews.mockReturnValue([view1, view2]);
store.set(findReplaceAtom, { type: "setFind", find: "Different" });

const state = store.get(findReplaceAtom);
expect(state.currentView?.cellId).toBeDefined();
expect(findNext()).toMatchObject({ from: 14, to: 23 });
expect(view1.dispatch).toHaveBeenCalledExactlyOnceWith({
selection: EditorSelection.single(0),
});
});

it("should wrap around to beginning when reaching end", () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { EditorState } from "@codemirror/state";
import { afterEach, expect, it } from "vitest";
import { EditorView } from "@codemirror/view";
import { afterEach, expect, it, vi } from "vitest";
import { mockIntersectionObservers } from "@/__mocks__/intersection-observer";
import { store } from "@/core/state/jotai";
import { searchState } from "../search-highlight";
import { searchHighlighter, searchState } from "../search-highlight";
import { findReplaceAtom } from "../state";

const views: EditorView[] = [];

afterEach(() => {
for (const view of views.splice(0)) {
view.destroy();
}
vi.unstubAllGlobals();
store.set(findReplaceAtom, { type: "setRegex", regexp: false });
store.set(findReplaceAtom, { type: "setIsOpen", isOpen: false });
store.set(findReplaceAtom, { type: "setFind", find: "" });
});
Expand All @@ -28,3 +37,82 @@ it("does not highlight a previous search in an editor built after the panel clos

expect(searchOfNewEditor()).toBe("");
});

it("dispatches only to visible editors and applies the latest query on return", () => {
const observers = mockIntersectionObservers();
const createView = () => {
const view = new EditorView({
parent: document.body,
doc: "alpha beta gamma",
extensions: [searchState, searchHighlighter],
});
views.push(view);
return view;
};
const visible = createView();
const offscreen = Array.from({ length: 20 }, createView);
const [returning, touchingViewport] = offscreen;
const [viewport] = observers;
expect(viewport.observe).toHaveBeenCalledTimes(21);
viewport.emit(visible.dom, true);
viewport.emit(returning.dom, true);
viewport.emit(returning.dom, false);
viewport.emit(touchingViewport.dom, true, 0);
const visibleDispatch = vi.spyOn(visible, "dispatch");
const offscreenDispatches = offscreen.map((view) =>
vi.spyOn(view, "dispatch"),
);

store.set(findReplaceAtom, { type: "setIsOpen", isOpen: true });
for (const find of ["alpha", "beta", "g.mma"]) {
store.set(findReplaceAtom, { type: "setFind", find });
}
store.set(findReplaceAtom, { type: "setRegex", regexp: true });

expect(visibleDispatch).toHaveBeenCalledTimes(4);
expect(visible.dom.querySelector(".cm-searchMatch")?.textContent).toBe(
"gamma",
);
for (const dispatch of offscreenDispatches) {
expect(dispatch).not.toHaveBeenCalled();
}

viewport.emit(returning.dom, true);
expect(offscreenDispatches[0]).toHaveBeenCalledOnce();
expect(returning.dom.querySelector(".cm-searchMatch")?.textContent).toBe(
"gamma",
);
viewport.emit(returning.dom, false);

store.set(findReplaceAtom, { type: "setIsOpen", isOpen: false });
expect(visible.dom.querySelector(".cm-searchMatch")).toBeNull();
expect(offscreenDispatches[0]).toHaveBeenCalledOnce();
viewport.emit(returning.dom, true);
expect(offscreenDispatches[0]).toHaveBeenCalledTimes(2);
expect(returning.dom.querySelector(".cm-searchMatch")).toBeNull();

store.set(findReplaceAtom, { type: "setIsOpen", isOpen: true });
expect(returning.dom.querySelector(".cm-searchMatch")?.textContent).toBe(
"gamma",
);
expect(visible.dom.querySelector(".cm-searchMatch")?.textContent).toBe(
"gamma",
);
});

it("unsubscribes a destroyed visible editor from viewport and query updates", () => {
const observers = mockIntersectionObservers();
const view = new EditorView({ extensions: [searchState, searchHighlighter] });
const [viewport] = observers;
viewport.emit(view.dom, true);
const dispatch = vi.spyOn(view, "dispatch");

view.destroy();
viewport.emit(view.dom, true);
store.set(findReplaceAtom, { type: "setIsOpen", isOpen: true });
store.set(findReplaceAtom, { type: "setFind", find: "alpha" });

expect(dispatch).not.toHaveBeenCalled();
expect(viewport.unobserve).toHaveBeenCalledExactlyOnceWith(view.dom);
expect(viewport.disconnect).toHaveBeenCalledOnce();
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { createCell } from "@/core/cells/types";
import { store } from "@/core/state/jotai";
import { cellIdState } from "../../config/extension";
import { editorMountScheduler } from "../../editor-mount-scheduler";
import { findNext, getMatches, replaceAll } from "../navigate";
import { findNext, findPrev, getMatches, replaceAll } from "../navigate";
import { findReplaceAtom } from "../state";

const { writes } = vi.hoisted(() => ({ writes: vi.fn() }));
Expand Down Expand Up @@ -56,28 +56,59 @@ afterEach(() => {
writes.mockReset();
store.set(notebookAtom, initialNotebookState());
store.set(findReplaceAtom, { type: "clearCurrentView" });
store.set(findReplaceAtom, { type: "setRegex", regexp: false });
});

it("counts matches in cells without editors and builds only the navigation target", () => {
const [a, b] = [cellId("a"), cellId("b")];
const [a, b, c] = [cellId("a"), cellId("b"), cellId("c")];
setNotebook([
[a, "x = 1", withoutEditor],
[b, 'mo.md(r"""needle""")', withoutEditor],
[c, "needle = 2", withoutEditor],
]);
const view = new EditorView({ state: EditorState.create({ doc: "needle" }) });
const views = [
new EditorView({ doc: "needle", extensions: cellIdState.of(b) }),
new EditorView({ doc: "needle = 2", extensions: cellIdState.of(c) }),
];
const [view, otherView] = views;
const build = vi.fn(() => {
store.get(notebookAtom).cellHandles[b].current = {
editorView: view,
};
});
const buildOther = vi.fn(() => {
store.get(notebookAtom).cellHandles[c].current = {
editorView: otherView,
};
});
editorMountScheduler.register(b, build);
store.set(findReplaceAtom, { type: "setFind", find: "needle" });
editorMountScheduler.register(c, buildOther);
store.set(findReplaceAtom, { type: "setFind", find: "n[e]+dle" });
store.set(findReplaceAtom, { type: "setRegex", regexp: true });

expect(getMatches()).toMatchObject({ count: 1 });
expect(getMatches()).toEqual({
count: 2,
position: new Map([
[b, new Map([["0:6", 0]])],
[c, new Map([["0:6", 1]])],
]),
});
expect(build).not.toHaveBeenCalled();
expect(buildOther).not.toHaveBeenCalled();
expect(findNext()).toMatchObject({ from: 0, to: 6 });
expect(build).toHaveBeenCalledTimes(1);
view.destroy();
expect(store.get(findReplaceAtom).currentView?.cellId).toBe(b);
expect(build).toHaveBeenCalledOnce();
expect(buildOther).not.toHaveBeenCalled();

expect(findNext()).toMatchObject({ from: 0, to: 6 });
expect(store.get(findReplaceAtom).currentView?.cellId).toBe(c);
expect(buildOther).toHaveBeenCalledOnce();
expect(findPrev()).toMatchObject({ from: 0, to: 6 });
expect(store.get(findReplaceAtom).currentView?.cellId).toBe(b);
expect(build).toHaveBeenCalledOnce();
for (const editor of views) {
editor.destroy();
}
});

it("moves past a match whose editor cannot be built", () => {
Expand Down Expand Up @@ -127,19 +158,22 @@ it("replaces and undoes matches in markdown without building its editor", () =>
setNotebook([[id, code, withoutEditor]]);
const build = vi.fn();
const release = editorMountScheduler.register(id, build);
store.set(findReplaceAtom, { type: "setFind", find: "needle" });
store.set(findReplaceAtom, { type: "setReplace", replace: "updated" });
store.set(findReplaceAtom, { type: "setFind", find: "(need)le" });
store.set(findReplaceAtom, { type: "setRegex", regexp: true });
store.set(findReplaceAtom, { type: "setReplace", replace: "$1ed" });

const undo = replaceAll();
expect(writes).toHaveBeenLastCalledWith({
cellId: id,
code: expect.stringContaining("updated"),
code: expect.stringContaining("needed"),
});
expect(getMatches()).toMatchObject({ count: 0 });
expect(typeof undo).toBe("function");
if (undo) {
undo();
}
expect(writes).toHaveBeenLastCalledWith({ cellId: id, code });
expect(getMatches()).toMatchObject({ count: 1 });
expect(build).not.toHaveBeenCalled();
release();
});
5 changes: 4 additions & 1 deletion frontend/src/core/codemirror/find-replace/navigate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ function findMatch(
0,
documents.findIndex((doc) => doc.cellId === startingCellId),
);
const startOfDocument = EditorSelection.single(0);
for (const document of [...documents, ...documents].slice(start)) {
const { state } = document;
const match =
Expand All @@ -64,7 +65,9 @@ function findMatch(
return { view, match };
}
position = undefined;
document.view?.dispatch({ selection: EditorSelection.single(0) });
if (document.view && !state.selection.eq(startOfDocument, true)) {
document.view.dispatch({ selection: startOfDocument });
}
}
}

Expand Down
Loading
Loading