Skip to content

Build your personal knowledge base with Trilium Notes

fix(codemirror): wrap find around to the first match

Elian Doran4f7cd0a15d78
diff --git a/packages/codemirror/src/find_replace.spec.ts b/packages/codemirror/src/find_replace.spec.ts
index 1f7545b18b..f378233edf 100644
--- a/packages/codemirror/src/find_replace.spec.ts
+++ b/packages/codemirror/src/find_replace.spec.ts
@@ -70,14 +70,12 @@ describe("SearchHighlighter", () => {
expect(search.currentFound).toBe(2);
});
- it("leaves no active match when every occurrence is before the cursor", () => {
- // Searching with the caret past the last hit finds matches but activates none, so
- // "find next" starts from the top rather than jumping backwards.
+ it("activates the first match when every occurrence is before the cursor", () => {
const search = highlighterFor("foo foo", 7);
search.searchFor("foo", false, false);
expect(search.totalFound).toBe(2);
- expect(search.currentFound).toBe(0);
+ expect(search.currentFound).toBe(1);
});
it("exposes the match set through the plugin's decoration accessor", () => {
diff --git a/packages/codemirror/src/find_replace.ts b/packages/codemirror/src/find_replace.ts
index 9d9f6d042e..cb68217bdc 100644
--- a/packages/codemirror/src/find_replace.ts
+++ b/packages/codemirror/src/find_replace.ts
@@ -138,17 +138,11 @@ export class SearchHighlighter {
this.totalFound = this.parsedMatches.length;
}
+ /** Activates the first match at or after the cursor, wrapping around to the first match. */
#scrollToMatchNearestSelection() {
const cursorPos = this.view.state.selection.main.head;
- let index = 0;
- for (const match of this.parsedMatches) {
- if (match.from >= cursorPos) {
- this.scrollToMatch(index);
- return;
- }
-
- index++;
- }
+ const index = this.parsedMatches.findIndex((match) => match.from >= cursorPos);
+ this.scrollToMatch(Math.max(index, 0));
}
static deco = (v: SearchHighlighter) => v.matches;
diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.ts
index 41f044fec1..5b0eb9dcec 100644
--- a/packages/codemirror/src/index.spec.ts
+++ b/packages/codemirror/src/index.spec.ts
@@ -377,6 +377,20 @@ describe("CodeMirror", () => {
expect(result.totalFound).toBe(2);
});
+ it("wraps around to the first match when every match is before the cursor", async () => {
+ editor = build();
+ editor.setText("foo bar foo");
+ editor.dispatch({ selection: EditorSelection.cursor(11) });
+
+ const result = await editor.performFind("foo", false, false);
+ expect(result).toEqual({ totalFound: 2, currentFound: 1 });
+ expect(editor.contentDOM.querySelectorAll(".cm-searchMatch")).toHaveLength(2);
+ expect(editor.contentDOM.querySelectorAll(".cm-activeMatch")).toHaveLength(1);
+
+ await editor.replace("baz");
+ expect(editor.getText()).toBe("baz bar foo");
+ });
+
it("replaces the active match and then all of them", async () => {
editor = build();
editor.setText("foo bar foo");