Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): jump to first match when opening search results

perfectra1n3799d5c33e17
diff --git a/apps/client/src/services/search_jump.spec.ts b/apps/client/src/services/search_jump.spec.ts
new file mode 100644
index 0000000000..a64ceb5c02
--- /dev/null
+++ b/apps/client/src/services/search_jump.spec.ts
@@ -0,0 +1,87 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const triggerCommand = vi.fn();
+vi.mock("../components/app_context.js", () => ({
+ default: {
+ triggerCommand: (...args: unknown[]) => triggerCommand(...args)
+ }
+}));
+
+import { consumeSearchTerms } from "./search_jump.js";
+
+function makeContext(searchTerms?: string[]) {
+ return {
+ viewScope: searchTerms === undefined ? {} : { searchTerms }
+ } as any;
+}
+
+describe("consumeSearchTerms", () => {
+ let rafCallbacks: FrameRequestCallback[];
+
+ beforeEach(() => {
+ triggerCommand.mockClear();
+ rafCallbacks = [];
+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {
+ rafCallbacks.push(cb);
+ return rafCallbacks.length;
+ });
+ });
+
+ afterEach(() => vi.unstubAllGlobals());
+
+ function flushRaf() {
+ const pending = rafCallbacks.splice(0);
+ for (const cb of pending) {
+ cb(0);
+ }
+ }
+
+ it("clears searchTerms synchronously and triggers a seeded findInText after a frame", () => {
+ const ctx = makeContext([ "foo", "bar" ]);
+
+ consumeSearchTerms(ctx, "ntx1");
+
+ // Cleared immediately so a concurrent same-note re-check sees the consumed state.
+ expect(ctx.viewScope.searchTerms).toBeUndefined();
+ // Deferred: the command must not fire during the noteSwitched dispatch (would race
+ // FindWidget's noteSwitched -> closeSearch and close the freshly opened bar).
+ expect(triggerCommand).not.toHaveBeenCalled();
+
+ flushRaf();
+
+ expect(triggerCommand).toHaveBeenCalledTimes(1);
+ expect(triggerCommand).toHaveBeenCalledWith("findInText", { ntxId: "ntx1", searchTerms: [ "foo", "bar" ] });
+ });
+
+ it("no-ops when searchTerms is absent or empty", () => {
+ consumeSearchTerms(makeContext(), "ntx1");
+ consumeSearchTerms(makeContext([]), "ntx1");
+
+ flushRaf();
+
+ expect(triggerCommand).not.toHaveBeenCalled();
+ });
+
+ it("no-ops when the note context is missing", () => {
+ consumeSearchTerms(null, "ntx1");
+ consumeSearchTerms(undefined, null);
+
+ flushRaf();
+
+ expect(triggerCommand).not.toHaveBeenCalled();
+ });
+
+ it("is idempotent: a second call after consumption does nothing", () => {
+ const ctx = makeContext([ "foo" ]);
+
+ consumeSearchTerms(ctx, "ntx1");
+ flushRaf();
+ expect(triggerCommand).toHaveBeenCalledTimes(1);
+
+ // Simulates the belt-and-suspenders double trigger (content-ready effect + noteSwitched
+ // listener) — the terms are gone, so nothing fires again.
+ consumeSearchTerms(ctx, "ntx1");
+ flushRaf();
+ expect(triggerCommand).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/client/src/services/search_jump.ts b/apps/client/src/services/search_jump.ts
new file mode 100644
index 0000000000..c1446c028b
--- /dev/null
+++ b/apps/client/src/services/search_jump.ts
@@ -0,0 +1,28 @@
+import appContext from "../components/app_context.js";
+import type NoteContext from "../components/note_context.js";
+
+/**
+ * One-shot consumer of `viewScope.searchTerms`: when a note is opened from search results the terms
+ * ride along in the view scope (see `link.ts`); this reads them, clears them, and fires a seeded
+ * `findInText` so the find bar opens on the first match. Mirrors how `viewScope.bookmark` is
+ * consumed by the type widgets.
+ *
+ * The terms are cleared synchronously (before the deferred trigger) so the belt-and-suspenders
+ * double invocation — the content-ready effect plus the same-note re-click `noteSwitched` listener —
+ * only opens the bar once.
+ *
+ * The trigger itself is deferred to the next animation frame so it runs *after* the `noteSwitched`
+ * dispatch that led here has fully drained. FindWidget also handles `noteSwitched` (by calling
+ * `closeSearch`); without the defer, a synchronous trigger from within the same dispatch could open
+ * the bar only for FindWidget's own `noteSwitched -> closeSearch` to immediately close it again.
+ */
+export function consumeSearchTerms(noteContext: NoteContext | undefined | null, ntxId: string | null | undefined): void {
+ const viewScope = noteContext?.viewScope;
+ const searchTerms = viewScope?.searchTerms;
+ if (!viewScope || !searchTerms?.length) {
+ return;
+ }
+
+ viewScope.searchTerms = undefined;
+ requestAnimationFrame(() => appContext.triggerCommand("findInText", { ntxId, searchTerms }));
+}
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index 0873fed9af..8dfbd9c6b7 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -18,6 +18,7 @@ import keyboard_actions from "../../services/keyboard_actions";
import { parseNavigationStateFromUrl, ViewScope } from "../../services/link";
import options, { type OptionValue } from "../../services/options";
import protected_session_holder from "../../services/protected_session_holder";
+import { consumeSearchTerms } from "../../services/search_jump";
import server from "../../services/server";
import type { ShortcutHintDefinition, ShortcutHintProvider } from "../../services/shortcut_hints";
import shortcuts, { Handler, removeIndividualBinding } from "../../services/shortcuts";
@@ -829,6 +830,28 @@ export function useNoteBlob(note: FNote | null | undefined, componentId?: string
return blob;
}
+/**
+ * Handles the same-note re-click half of jump-to-match consumption (see `search_jump.ts`), shared
+ * by the text and code type widgets. The other half — consuming when a note's content first loads
+ * — is done directly at each widget's content-ready point (`[blob]` effect / `onContentChange`),
+ * because that signal differs between the read-only and editable variants.
+ *
+ * Re-clicking the same search result re-runs `setNote` (it proceeds because the viewScope now
+ * carries new `searchTerms` and so differs from the current one) and fires `noteSwitched` without
+ * changing the blob — so the content-ready path doesn't re-run. We consume here instead, but only
+ * when the switch targets the note this widget already shows: a genuine switch to a *different*
+ * note is handled by the newly mounted widget's content-ready path, and consuming it here (against
+ * this widget's stale, about-to-unmount content) would clear the terms before the real content is
+ * ready, so we skip it.
+ */
+export function useSearchTermsConsumer(note: FNote | null | undefined, noteContext: NoteContext | undefined, ntxId: string | null | undefined) {
+ useTriliumEvent("noteSwitched", ({ noteContext: switchedContext }) => {
+ if (switchedContext.ntxId !== ntxId) return;
+ if (switchedContext.note?.noteId !== note?.noteId) return;
+ consumeSearchTerms(noteContext, ntxId);
+ });
+}
+
export function useLegacyWidget<T extends BasicWidget>(widgetFactory: () => T, { noteContext, containerClassName, containerStyle }: {
noteContext?: NoteContext;
containerClassName?: string;
diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsx
index 72cd651355..3740493d15 100644
--- a/apps/client/src/widgets/type_widgets/code/Code.tsx
+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx
@@ -8,8 +8,9 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { CommandListenerData } from "../../../components/app_context";
import FNote from "../../../entities/fnote";
import { t } from "../../../services/i18n";
+import { consumeSearchTerms } from "../../../services/search_jump";
import utils from "../../../services/utils";
-import { useColorScheme, useEditorSpacedUpdate, useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteBlob, useNoteLabel, useNoteLabelInt, useNoteLabelOptionalBool, useNoteProperty, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import { useColorScheme, useEditorSpacedUpdate, useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteBlob, useNoteLabel, useNoteLabelInt, useNoteLabelOptionalBool, useNoteProperty, useSearchTermsConsumer, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
import { refToJQuerySelector } from "../../react/react_utils";
import { CODE_THEME_DEFAULT_PREFIX as DEFAULT_PREFIX } from "../constants";
import { TypeWidgetProps } from "../type_widget";
@@ -36,7 +37,7 @@ export interface EditableCodeProps extends TypeWidgetProps, Omit<CodeEditorProps
editorRef?: Ref<VanillaCodeMirror>;
}
-export function ReadOnlyCode({ note, viewScope, ntxId, parentComponent, editorRef }: TypeWidgetProps & { editorRef?: Ref<VanillaCodeMirror> }) {
+export function ReadOnlyCode({ note, viewScope, ntxId, noteContext, parentComponent, editorRef }: TypeWidgetProps & { editorRef?: Ref<VanillaCodeMirror> }) {
const [ content, setContent ] = useState("");
const blob = useNoteBlob(note);
// Read reactively so switching the language from the dropdown re-highlights live, rather than
@@ -55,7 +56,12 @@ export function ReadOnlyCode({ note, viewScope, ntxId, parentComponent, editorRe
}
setContent(newContent);
+
+ // Jump to the first search match (and pre-fill the find bar) when navigated from search
+ // results; the same-note re-click case is covered by useSearchTermsConsumer below.
+ consumeSearchTerms(noteContext, ntxId);
}, [ blob ]);
+ useSearchTermsConsumer(note, noteContext, ntxId);
return (
<CodeEditor
@@ -115,11 +121,18 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentC
codeEditor.setText(content ?? "");
codeEditor.setMimeType(note.mime);
codeEditor.clearHistory();
+
+ // Jump to the first search match (and pre-fill the find bar) when navigated from search
+ // results. Runs once the content has loaded into the editor; the same-note re-click case
+ // is covered by useSearchTermsConsumer below.
+ consumeSearchTerms(noteContext, ntxId);
},
dataSaved,
updateInterval
});
+ useSearchTermsConsumer(note, noteContext, ntxId);
+
// make sure that script is saved before running it #4028
useLegacyImperativeHandlers({
async runActiveNoteCommand(params: CommandListenerData<"runActiveNote">) {
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index f722ead23c..f28e2b9bec 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -12,9 +12,10 @@ import { t } from "../../../services/i18n";
import link, { parseNavigationStateFromUrl } from "../../../services/link";
import note_create from "../../../services/note_create";
import options from "../../../services/options";
+import { consumeSearchTerms } from "../../../services/search_jump";
import toast from "../../../services/toast";
import utils, { isMobile } from "../../../services/utils";
-import { useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import { useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useSearchTermsConsumer, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
import { TypeWidgetProps } from "../type_widget";
import CKEditorWithWatchdog, { CKEditorApi } from "./CKEditorWithWatchdog";
import getTemplates, { updateTemplateCache } from "./snippets.js";
@@ -61,6 +62,11 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
contentRef.current = newContent;
watchdogRef.current?.editor?.setData(newContent);
+ // Jump to the first search match (and pre-fill the find bar) when navigated from search
+ // results. Runs once the content has loaded into the editor; the same-note re-click case
+ // is covered by useSearchTermsConsumer below.
+ consumeSearchTerms(noteContext, ntxId);
+
// Scroll to bookmark anchor if navigated with ?bookmark=...
const viewScope = noteContext?.viewScope;
if (viewScope?.bookmark) {
@@ -83,6 +89,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
});
const templates = useTemplates();
+ useSearchTermsConsumer(note, noteContext, ntxId);
+
useTriliumEvent("scrollToEnd", () => {
const editor = watchdogRef.current?.editor;
if (!editor) return;
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index d687b3a215..6f5c46db9a 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -16,8 +16,9 @@ import { getLocaleById } from "../../../services/i18n";
import { applyLinkEmbeds } from "../../../services/link_embed";
import { renderMathInElement } from "../../../services/math";
import { trackPendingRender } from "../../../services/pending_renders";
+import { consumeSearchTerms } from "../../../services/search_jump";
import { formatCodeBlocks } from "../../../services/syntax_highlight";
-import { useNoteBlob, useNoteLabel, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import { useNoteBlob, useNoteLabel, useSearchTermsConsumer, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
import { RawHtmlBlock } from "../../react/RawHtml";
import { TypeWidgetProps } from "../type_widget";
import { applyReferenceLinks } from "./read_only_helper";
@@ -41,6 +42,13 @@ export default function ReadOnlyText({ note, noteContext, ntxId }: TypeWidgetPro
viewScope.bookmark = undefined;
}, [blob]);
+ // Jump to the first search match (and pre-fill the find bar) when navigated from search results.
+ // Runs once the content has loaded; the same-note re-click case is covered by the hook below.
+ useEffect(() => {
+ if (blob) consumeSearchTerms(noteContext, ntxId);
+ }, [blob]);
+ useSearchTermsConsumer(note, noteContext, ntxId);
+
return (
<>
<ReadOnlyTextContent