Skip to content

Build your personal knowledge base with Trilium Notes

feat(search): pick a note with @ in the search string

Elian Doran6c9557ab6674
diff --git a/apps/client/src/widgets/ribbon/search_completions.spec.ts b/apps/client/src/widgets/ribbon/search_completions.spec.ts
index 2cbdfda01d..d39d330a9f 100644
--- a/apps/client/src/widgets/ribbon/search_completions.spec.ts
+++ b/apps/client/src/widgets/ribbon/search_completions.spec.ts
@@ -342,6 +342,78 @@ function iconFor(result: CompletionResult | null, label: string) {
return option ? searchCompletionIcon(option) : "no such option";
}
+describe("note mentions", () => {
+ const NOTES = [
+ { notePath: "root/abc123", noteTitle: "Foo", notePathTitle: "Root / Foo", icon: "bx bx-file" },
+ { notePath: "root/proj/def456", noteTitle: "Foobar", notePathTitle: "Root / Projects / Foobar", icon: "bx bx-note" }
+ ];
+
+ beforeEach(() => vi.mocked(server.get).mockResolvedValue(NOTES));
+
+ it("offers the notes an @ names and inserts the id, taking the marker with it", async () => {
+ const result = await complete("~template.noteId = @Fo");
+
+ expect(server.get).toHaveBeenCalledWith("autocomplete?query=Fo&activeNoteId=none&fastSearch=true");
+ // Offered from past the `@`, so "Fo" is matched against the titles.
+ expect(result?.from).toBe(20);
+ expect(labelsOf(result)).toEqual([ "Foo", "Foobar" ]);
+ expect(optionFor(result, "Foo")?.detail).toBe("Root / Foo");
+ expect(optionFor(result, "Foobar")?.boost).toBeLessThan(optionFor(result, "Foo")?.boost ?? 0);
+
+ // The `@` at 19 is rewritten along with the "Fo" after it.
+ expect(dispatchOf(result, "Foo", 22)).toEqual({
+ changes: { from: 19, to: 22, insert: "abc123" },
+ selection: { anchor: 25 }
+ });
+ });
+
+ it("draws each note with its own icon", async () => {
+ const result = await complete("@Fo");
+
+ expect(result?.from).toBe(1);
+ expect(searchCompletionIcon(optionFor(result, "Foo") ?? { label: "" })).toBe("bx bx-file");
+ expect(searchCompletionIcon(optionFor(result, "Foobar") ?? { label: "" })).toBe("bx bx-note");
+ });
+
+ it("answers with the recently visited notes before anything is typed", async () => {
+ const result = await complete("#book AND @");
+
+ expect(server.get).toHaveBeenCalledWith("autocomplete?query=&activeNoteId=none&fastSearch=true");
+ expect(labelsOf(result)).toEqual([ "Foo", "Foobar" ]);
+ });
+
+ it("opens on a standalone @ but not on one inside an attribute name", async () => {
+ const inName = await complete("#foo@");
+
+ expect(server.get).not.toHaveBeenCalledWith(expect.stringContaining("autocomplete?"));
+ expect(labelsOf(inName)).toEqual([ "book", "archived" ]);
+
+ // The same text with the marker standing on its own does reach the notes.
+ expect(labelsOf(await complete("#foo @"))).toEqual([ "Foo", "Foobar" ]);
+ });
+
+ it("skips a suggestion carrying no note", async () => {
+ vi.mocked(server.get).mockResolvedValue([ { noteTitle: "External", externalLink: "https://example.com" }, ...NOTES ]);
+
+ expect(labelsOf(await complete("@Fo"))).toEqual([ "Foo", "Foobar" ]);
+ });
+});
+
+/** Runs an option's rewrite against a stand-in editor and hands back what it dispatched. */
+function dispatchOf(result: CompletionResult | null, label: string, to: number) {
+ const option = optionFor(result, label);
+ const apply = option?.apply;
+
+ if (typeof apply !== "function" || !option) {
+ throw new Error(`The '${label}' option inserts a fixed string rather than rewriting.`);
+ }
+
+ let dispatched: unknown;
+ apply({ dispatch: (spec: unknown) => { dispatched = spec; } } as never, option, 0, to);
+
+ return dispatched;
+}
+
async function complete(text: string, opts?: { explicit?: boolean }) {
return await searchCompletionSource(contextAt(text, opts));
}
diff --git a/apps/client/src/widgets/ribbon/search_completions.ts b/apps/client/src/widgets/ribbon/search_completions.ts
index 0746936a78..0412927c20 100644
--- a/apps/client/src/widgets/ribbon/search_completions.ts
+++ b/apps/client/src/widgets/ribbon/search_completions.ts
@@ -2,6 +2,7 @@ import type { Completion, CompletionContext, CompletionResult } from "@triliumne
import { ALLOWED_NOTE_TYPES, allowedSearchOperators, MIME_TYPES_DICT, SEARCH_NOTE_PATH, SEARCH_NOTE_PATH_SEGMENTS } from "@triliumnext/commons";
import { isBuiltinAttribute } from "../../services/attributes";
+import type { Suggestion } from "../../services/note_autocomplete";
import { t } from "../../services/i18n";
import server from "../../services/server";
import { fetchAttributeNames } from "../attribute_widgets/attribute_detail";
@@ -16,6 +17,15 @@ type CompletionOutcome = CompletionResult | Promise<CompletionResult | null> | n
* values a label is compared against.
*/
export function searchCompletionSource(context: CompletionContext): CompletionOutcome {
+ // Read before the rest: `@` is a name character to the lexer, so the branches below would
+ // answer for one typed inside an attribute name.
+ const mention = context.matchBefore(NOTE_MENTION);
+ if (mention) {
+ const typedAt = mention.text.indexOf("@");
+
+ return noteCompletions(mention.text.slice(typedAt + 1), mention.from + typedAt);
+ }
+
const path = context.matchBefore(PROPERTY_PATH);
if (path) {
return pathCompletions(path.text, context.pos);
@@ -71,6 +81,12 @@ export function searchCompletionSource(context: CompletionContext): CompletionOu
return null;
}
+/**
+ * A note picked with `@`, which opens only where a value can stand — at the start, or after
+ * whitespace, an opening bracket or an operator. `@` is a name character to the lexer, so one
+ * typed inside an attribute name is left alone.
+ */
+const NOTE_MENTION = /(?:^|[\s(=!*<>%~])@[^\s#~()'"`@]*/;
/** The characters an operator is spelled with, so typing any of them starts offering them. */
const OPERATOR_PREFIX = /[=!*<>%~]+/;
const WORD_PREFIX = /[a-zA-Z]+/;
@@ -115,6 +131,55 @@ const VALUE_NEEDS_QUOTES = /[\s"'`\\#~().=*<>!%+,-]/;
*/
const RESERVED_VALUES = new Set([ "note", "now", "today", "month", "year" ]);
+/** A completion drawn with an icon of its own, which {@link COMPLETION_ICONS} cannot supply. */
+interface NoteCompletion extends Completion {
+ noteIcon?: string;
+}
+
+/**
+ * Offers the notes matching what follows an `@`, through the call the jump-to dialog reads, and
+ * inserts the id of the one picked. The id is what the query keeps, so it goes on matching the
+ * note after a rename; with nothing typed yet the call answers with the recently visited notes.
+ */
+async function noteCompletions(term: string, atPos: number): Promise<CompletionResult | null> {
+ let suggestions: Suggestion[];
+ try {
+ suggestions = await server.get<Suggestion[]>(
+ `autocomplete?query=${encodeURIComponent(term)}&activeNoteId=none&fastSearch=true`
+ );
+ } catch {
+ return null;
+ }
+
+ const options: NoteCompletion[] = [];
+
+ for (const [ index, suggestion ] of suggestions.entries()) {
+ const noteId = suggestion.notePath?.split("/").filter(Boolean).pop();
+ if (!noteId || !suggestion.noteTitle) {
+ continue;
+ }
+
+ options.push({
+ label: suggestion.noteTitle,
+ detail: suggestion.notePathTitle,
+ noteIcon: suggestion.icon,
+ // The call ranks the notes; this keeps that order among the ones matching as well as
+ // each other, while leaving a distinctly better match free to rise past them.
+ boost: -index,
+ // Rewrites the `@` along with what was typed after it. CodeMirror would replace only
+ // what it matched against, which starts past the `@`.
+ apply: (view, _completion, _from, to) => view.dispatch({
+ changes: { from: atPos, to, insert: noteId },
+ selection: { anchor: atPos + noteId.length }
+ })
+ });
+ }
+
+ // Offered from past the `@`, so what was typed is matched against the titles rather than
+ // against a marker no title carries.
+ return options.length ? { from: atPos + 1, options } : null;
+}
+
/**
* Fetches the label or relation names the database holds, through the same call the sidebar's
* attribute picker makes, and marks the built-in ones as that picker does. The whole set is asked
@@ -169,6 +234,10 @@ const COMPLETION_ICONS: Record<string, string> = {
/** The icon an option is drawn with. Only the attribute names carry one. */
export function searchCompletionIcon(completion: Completion): string | undefined {
+ if ("noteIcon" in completion && typeof completion.noteIcon === "string") {
+ return completion.noteIcon;
+ }
+
return completion.type ? COMPLETION_ICONS[completion.type] : undefined;
}