Cat and cat.
concatenate
"); + expect(texts(e)).toEqual(["Cat", "cat", "cat"]); + expect(findMatches(e.state.doc, "Cat", true)).toHaveLength(1); + }); + + it("does not run from one block into the next", () => { + const e = setup("ca
t
"); + expect(findMatches(e.state.doc, "cat")).toEqual([]); + }); +}); + +describe("FindReplace", () => { + it("steps through matches and wraps around", () => { + const e = setup("one cat, two cat, three cat
"); + e.commands.setFind("cat"); + const state = () => findKey.getState(e.state)!; + expect(state().matches).toHaveLength(3); + expect(state().current).toBe(0); + e.commands.findStep(-1); + expect(state().current).toBe(2); + e.commands.findStep(1); + expect(state().current).toBe(0); + }); + + it("replaces one match, then all, as ordinary edits", () => { + const e = setup("cat cat cat
"); + e.commands.setFind("cat"); + e.commands.replaceCurrent("dog"); + expect(e.getText()).toBe("dog cat cat"); + expect(findKey.getState(e.state)!.matches).toHaveLength(2); + e.commands.replaceAll("cow"); + expect(e.getText()).toBe("dog cow cow"); + expect(findKey.getState(e.state)!.matches).toHaveLength(0); + e.commands.undo(); + expect(e.getText()).toBe("dog cat cat"); + }); + + it("searches again after other edits and clears", () => { + const e = setup("cat
"); + e.commands.setFind("cat"); + e.commands.insertContentAt(e.state.doc.content.size, "another cat
"); + expect(findKey.getState(e.state)!.matches).toHaveLength(2); + e.commands.clearFind(); + expect(findKey.getState(e.state)!.term).toBe(""); + }); +}); diff --git a/Packages/editor/src/find.ts b/Packages/editor/src/find.ts new file mode 100644 index 0000000..3239f3b --- /dev/null +++ b/Packages/editor/src/find.ts @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { Extension } from "@tiptap/core"; +import type { Node as PMNode } from "@tiptap/pm/model"; +import { Plugin, PluginKey, TextSelection, type Transaction } from "@tiptap/pm/state"; +import { Decoration, DecorationSet } from "@tiptap/pm/view"; + +export type FindMatch = { from: number; to: number }; + +export type FindState = { + term: string; + caseSensitive: boolean; + matches: FindMatch[]; + /** Index of the current match, -1 when there is none. */ + current: number; +}; + +export const findKey = new PluginKey