Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(client): seeded find command for jump-to-match
perfectra1nff69a81e7ea9
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex ee6e2913d4..52a07f5fb8 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -365,7 +365,7 @@ export type CommandMappings = {unhoist: CommandData;reloadFrontendApp: CommandData;openDevTools: CommandData;- findInText: CommandData;+ findInText: CommandData & { searchTerms?: string[] };toggleLeftPane: CommandData;toggleFullscreen: CommandData;zoomOut: CommandData;diff --git a/apps/client/src/widgets/find.spec.ts b/apps/client/src/widgets/find.spec.tsnew file mode 100644index 0000000000..540cb37562--- /dev/null+++ b/apps/client/src/widgets/find.spec.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest";++import { deriveSeededFind } from "./find.js";++describe("deriveSeededFind", () => {+ it("uses the first token as the seed and the rest as extra highlight tokens", () => {+ expect(deriveSeededFind([ "alpha", "beta", "gamma" ])).toEqual({+ seed: "alpha",+ extraTokens: [ "beta", "gamma" ]+ });+ });++ it("treats a single token as the seed with no extras", () => {+ expect(deriveSeededFind([ "alpha" ])).toEqual({ seed: "alpha", extraTokens: [] });+ });++ it("keeps a quoted phrase (already a single token) intact as the seed", () => {+ expect(deriveSeededFind([ "hello world" ])).toEqual({ seed: "hello world", extraTokens: [] });+ });++ it("degrades to an empty seed for an empty term list", () => {+ expect(deriveSeededFind([])).toEqual({ seed: "", extraTokens: [] });+ });+});diff --git a/apps/client/src/widgets/find.ts b/apps/client/src/widgets/find.tsindex 5b431e3c3d..fff01b7d66 100644--- a/apps/client/src/widgets/find.ts+++ b/apps/client/src/widgets/find.ts@@ -10,6 +10,7 @@ import FindInText from "./find_in_text.js";import FindInCode from "./find_in_code.js";import { isIMEComposing } from "../services/shortcuts.js";import FindInHtml from "./find_in_html.js";+import utils from "../services/utils.js";import type { EventData } from "../components/app_context.js";const findWidgetDelayMillis = 200;@@ -54,6 +55,15 @@ const TPL = /*html*/`.find-widget-spacer {flex-grow: 1;}++ /* Muted highlight for the non-seed tokens of a multi-token jump-to-match (see+ FindInHtml.highlightExtraTokens): a reduced-opacity variant of the primary+ .ck-find-result highlight, so extra matches are visible without competing with the+ seed match that Enter/F3 cycles. */+ .find-result-secondary {+ background-color: color-mix(in srgb, var(--ck-color-find-result-background, #66ff99) 40%, transparent);+ border-radius: 2px;+ }</style><div class="find-widget-box">@@ -191,8 +201,12 @@ export default class FindWidget extends NoteContextAwareWidget {return this.$widget;}- async findInTextEvent() {- if (!this.isActiveNoteContext()) {+ async findInTextEvent(data: EventData<"findInText"> = {}) {+ // Route by explicit ntxId when the command targets a specific context (the seeded+ // jump-to-match flow fired on note open carries it); otherwise fall back to the active+ // context, as manual Ctrl+F / toolbar invocations do.+ const isTargeted = data.ntxId ? this.isNoteContext(data.ntxId) : this.isActiveNoteContext();+ if (!isTargeted) {return;}@@ -205,6 +219,11 @@ export default class FindWidget extends NoteContextAwareWidget {this.handler = await this.getHandler();+ if (data.searchTerms?.length) {+ await this.seededFind(data.searchTerms);+ return;+ }+const isReadOnly = await this.noteContext?.isReadOnly();let selectedText = "";@@ -246,6 +265,41 @@ export default class FindWidget extends NoteContextAwareWidget {}}+ /**+ * Opens the find bar pre-seeded from search terms carried in on note open (jump-to-match),+ * scrolling to the first match so Enter/F3 immediately cycles the results.+ *+ * The bar is shown whenever there is at least one match — deliberately, even for non-Electron+ * users who have no Ctrl+F to summon it: (a) Enter/F3 cycling is bound on the input, (b) leaving+ * the bar open is the affordance that lets the user dismiss the highlights (closeSearch only+ * unmarks while the bar is visible). With zero matches nothing is shown and performFind leaves+ * no marks behind, so there is nothing to leak.+ *+ * Kept separate from the manual-open flow above, whose pre-existing show()/isAlreadyVisible+ * ordering is intentionally left untouched.+ */+ private async seededFind(searchTerms: string[]) {+ const { seed, extraTokens } = deriveSeededFind(searchTerms);+ this.$input.val(seed);++ const { totalFound } = await this.performFind();+ if (totalFound < 1) {+ return;+ }++ this.$widget.show();+ if (!utils.isMobile()) {+ this.$input.focus();+ this.$input.select();+ }++ // Multi-token highlight-all is only supported by the read-only HTML handler; the editable+ // CKEditor and CodeMirror find engines highlight the single seed term only.+ if (extraTokens.length && this.handler instanceof FindInHtml) {+ await this.handler.highlightExtraTokens(extraTokens);+ }+ }+async readOnlyTemporarilyDisabledEvent({ noteContext }: EventData<"readOnlyTemporarilyDisabled">) {if (this.isNoteContext(noteContext.ntxId)) {await this.closeSearch();@@ -329,14 +383,14 @@ export default class FindWidget extends NoteContextAwareWidget {}}- /** Perform the find and highlight the find results. */- async performFind() {+ /** Perform the find and highlight the find results. Returns the resulting match counts. */+ async performFind(): Promise<FindResult> {const searchTerm = String(this.$input.val());const matchCase = this.$caseSensitiveCheckbox.prop("checked");const wholeWord = this.$matchWordsCheckbox.prop("checked");if (!this.handler) {- return;+ return { totalFound: 0, currentFound: 0 };}const { totalFound, currentFound } = await this.handler.performFind(searchTerm, matchCase, wholeWord);@@ -344,6 +398,8 @@ export default class FindWidget extends NoteContextAwareWidget {this.$currentFound.text(currentFound);this.searchTerm = searchTerm;++ return { totalFound, currentFound };}async closeSearch() {@@ -392,3 +448,13 @@ export default class FindWidget extends NoteContextAwareWidget {}}}++/**+ * Splits the search terms carried in on note open into the seed (first token — a quoted phrase+ * arrives as a single token) that drives the find counter and Enter/F3 cycling, and the remaining+ * tokens that get a muted highlight-all pass (HTML handler only). Extracted and kept pure so the+ * seed/extras split is unit-testable without instantiating the jQuery widget.+ */+export function deriveSeededFind(searchTerms: string[]): { seed: string; extraTokens: string[] } {+ return { seed: searchTerms[0] ?? "", extraTokens: searchTerms.slice(1) };+}diff --git a/apps/client/src/widgets/find_in_html.spec.ts b/apps/client/src/widgets/find_in_html.spec.tsnew file mode 100644index 0000000000..bf8d16364b--- /dev/null+++ b/apps/client/src/widgets/find_in_html.spec.ts@@ -0,0 +1,92 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import FindInHtml from "./find_in_html.js";++/**+ * Builds a FindInHtml wired to a real (happy-dom) content element, so mark.js can mutate it.+ */+function setup(html: string) {+ const container = document.createElement("div");+ container.className = "ck-content";+ container.innerHTML = html;+ document.body.appendChild(container);++ const parent = {+ noteContext: {+ getContentElement: async () => $(container)+ }+ } as any;++ return { finder: new FindInHtml(parent), container };+}++describe("FindInHtml", () => {+ beforeEach(() => {+ // happy-dom doesn't implement scrollIntoView; jumpTo() calls it.+ (Element.prototype as any).scrollIntoView = vi.fn();+ });++ afterEach(() => {+ document.body.innerHTML = "";+ });++ it("marks the seed term with the primary find-result class and counts matches", async () => {+ const { finder, container } = setup("<p>alpha beta alpha gamma</p>");++ const result = await finder.performFind("alpha", false, false);++ expect(result.totalFound).toBe(2);+ expect(result.currentFound).toBe(1);+ expect(container.querySelectorAll(".ck-find-result").length).toBe(2);+ expect(container.querySelectorAll(".find-result-secondary").length).toBe(0);+ });++ it("highlightExtraTokens marks non-seed tokens with the muted secondary class only", async () => {+ const { finder, container } = setup("<p>alpha beta gamma</p>");++ await finder.performFind("alpha", false, false);+ await finder.highlightExtraTokens([ "beta", "gamma" ]);++ // Seed count is unaffected — Enter/F3 still cycles only the primary matches.+ expect(container.querySelectorAll(".ck-find-result").length).toBe(1);+ expect(container.querySelectorAll(".find-result-secondary").length).toBe(2);+ });++ it("findBoxClosed unmarks the shared instance once, clearing primary + secondary together", async () => {+ const { finder, container } = setup("<p>alpha beta gamma</p>");++ await finder.performFind("alpha", false, false);+ await finder.highlightExtraTokens([ "beta" ]);+ expect(container.querySelectorAll(".ck-find-result, .find-result-secondary").length).toBe(2);++ // Secondary marks reuse the same mark.js instance as the seed pass, so a single unmark()+ // in findBoxClosed clears both. (happy-dom can't actually unwrap mark.js spans, so the+ // cleanup is asserted at the call level rather than via the DOM.)+ const markInstance = (finder as unknown as { mark: { unmark: () => void } }).mark;+ const unmarkSpy = vi.spyOn(markInstance, "unmark");++ await finder.findBoxClosed(1, 0);++ expect(unmarkSpy).toHaveBeenCalledTimes(1);+ });++ it("highlightExtraTokens is a no-op before a find has run (no mark instance yet)", async () => {+ const { finder, container } = setup("<p>alpha beta</p>");++ await finder.highlightExtraTokens([ "beta" ]);++ expect(container.querySelectorAll(".find-result-secondary").length).toBe(0);+ });++ it("highlightExtraTokens safely handles tokens containing regex metacharacters", async () => {+ const { finder, container } = setup("<p>a.c a+c value</p>");++ await finder.performFind("value", false, false);+ await finder.highlightExtraTokens([ "a.c", "a+c" ]);++ // Literal matches only — no regex injection (both literal tokens exist once each).+ const secondary = Array.from(container.querySelectorAll(".find-result-secondary")).map((el) => el.textContent);+ expect(secondary).toContain("a.c");+ expect(secondary).toContain("a+c");+ });+});diff --git a/apps/client/src/widgets/find_in_html.ts b/apps/client/src/widgets/find_in_html.tsindex 5c4d88be54..3ba5b89203 100644--- a/apps/client/src/widgets/find_in_html.ts+++ b/apps/client/src/widgets/find_in_html.ts@@ -9,6 +9,10 @@ import type { FindResult } from "./find.js";const FIND_RESULT_SELECTED_CSS_CLASSNAME = "ck-find-result_selected";const FIND_RESULT_CSS_CLASSNAME = "ck-find-result";+// Muted highlight for the non-seed tokens of a multi-token search (jump-to-match). Styled in the+// FindWidget's style block. Deliberately distinct from FIND_RESULT_CSS_CLASSNAME so these marks are+// not counted as primary matches and Enter/F3 keeps cycling only the seed.+const FIND_RESULT_SECONDARY_CSS_CLASSNAME = "find-result-secondary";export default class FindInHtml {@@ -78,7 +82,37 @@ export default class FindInHtml {}}+ /**+ * Highlights additional (non-seed) search tokens with a muted secondary style, so opening a+ * multi-token search result shows every matched term at a glance while Enter/F3 keep cycling+ * only the primary (seed) matches counted by {@link performFind}.+ *+ * Only this read-only HTML handler supports the multi-token pass; the editable CKEditor and+ * CodeMirror handlers stay seed-only (their find engines highlight a single term). These marks+ * reuse the same mark.js instance created by {@link performFind}, so {@link findBoxClosed}'s+ * `unmark()` — and any subsequent manual re-search's `unmark()` — clears them too. mark.js+ * escapes each keyword internally, so regex metacharacters in a token can't inject.+ */+ async highlightExtraTokens(tokens: string[]) {+ const mark = this.mark;+ const cleaned = tokens.filter((token) => token.length > 0);+ if (!mark || cleaned.length === 0) {+ return;+ }++ return new Promise<void>((res) => {+ mark.mark(cleaned, {+ element: "span",+ className: FIND_RESULT_SECONDARY_CSS_CLASSNAME,+ separateWordSearch: false,+ done: () => res()+ });+ });+ }+async findBoxClosed(totalFound: number, currentFound: number) {+ // A single unmark() clears both the primary (seed) marks and any secondary marks from+ // highlightExtraTokens, since they share this mark.js instance.this.mark?.unmark();}