Skip to content

Build your personal knowledge base with Trilium Notes

feat(search): complete label and relation names from the database

Elian Doran7bdbb723304f
diff --git a/apps/client/src/widgets/ribbon/search_completions.spec.ts b/apps/client/src/widgets/ribbon/search_completions.spec.ts
index 74b2f8aeb5..c3cdfeedf5 100644
--- a/apps/client/src/widgets/ribbon/search_completions.spec.ts
+++ b/apps/client/src/widgets/ribbon/search_completions.spec.ts
@@ -1,14 +1,20 @@
import type { CompletionContext, CompletionResult } from "@triliumnext/codemirror/src/single_line";
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import server from "../../services/server";
import { searchCompletionSource } from "./search_completions";
// The descriptions are catalogue lookups, which specs don't initialize; the keys identify them.
vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));
+vi.mock("../../services/server", () => ({ default: { get: vi.fn() } }));
+
+beforeEach(() => {
+ vi.mocked(server.get).mockReset().mockResolvedValue([ "book", "publicationYear" ]);
+});
describe("searchCompletionSource", () => {
- it("offers the note object and the keywords while a word is being typed, anchored at its start", () => {
- const result = searchCompletionSource(contextAt("#book AND no"));
+ it("offers the note object and the keywords while a word is being typed, anchored at its start", async () => {
+ const result = await complete("#book AND no");
expect(result?.from).toBe(10);
expect(labelsOf(result)).toEqual([ "note", "and", "or", "not", "orderBy", "limit" ]);
@@ -18,65 +24,107 @@ describe("searchCompletionSource", () => {
expect(optionFor(result, "note")?.detail).toBe("search_completion.note");
});
- it("offers the sort directions only once an orderBy is open", () => {
- expect(labelsOf(searchCompletionSource(contextAt("#book de")))).not.toContain("desc");
+ it("offers the sort directions only once an orderBy is open", async () => {
+ expect(labelsOf(await complete("#book de"))).not.toContain("desc");
- const ordering = searchCompletionSource(contextAt("#book orderBy #year de"));
+ const ordering = await complete("#book orderBy #year de");
expect(labelsOf(ordering)).toContain("desc");
expect(optionFor(ordering, "asc")?.detail).toBe("order_by.asc");
});
- it("offers every operator once one of their characters is typed", () => {
- const result = searchCompletionSource(contextAt("#year >"));
+ it("offers every operator once one of their characters is typed", async () => {
+ const result = await complete("#year >");
expect(result?.from).toBe(6);
- expect(result?.options.map((option) => option.label)).toEqual([
+ expect(labelsOf(result)).toEqual([
"=", "!=", "*=*", "=*", "*=", ">", ">=", "<", "<=", "%=", "~=", "~*"
]);
expect(result?.options.every((option) => option.detail)).toBe(true);
});
- it("offers path segments after a dot, anchored at the segment being typed", () => {
- const root = searchCompletionSource(contextAt("note."));
+ it("offers path segments after a dot, anchored at the segment being typed", async () => {
+ const root = await complete("note.");
expect(root?.from).toBe(5);
expect(labelsOf(root)).toContain("title");
expect(labelsOf(root)).toContain("parents");
expect(labelsOf(root)).toContain("content");
- const partial = searchCompletionSource(contextAt("#book AND note.date"));
+ const partial = await complete("#book AND note.date");
expect(partial?.from).toBe(15);
expect(labelsOf(partial)).toEqual(labelsOf(root));
});
- it("walks a path through a relation and through a traversal", () => {
- expect(labelsOf(searchCompletionSource(contextAt("~author.")))).toContain("title");
- expect(labelsOf(searchCompletionSource(contextAt("note.parents.")))).toContain("title");
- expect(labelsOf(searchCompletionSource(contextAt("~author.relations.son.")))).toContain("title");
+ it("walks a path through a relation and through a traversal", async () => {
+ expect(labelsOf(await complete("~author."))).toContain("title");
+ expect(labelsOf(await complete("note.parents."))).toContain("title");
+ expect(labelsOf(await complete("~author.relations.son."))).toContain("title");
});
- it("stops where the grammar expects a name or ends the path", () => {
- // Both take an attribute name, which nothing can enumerate ahead of time.
- expect(searchCompletionSource(contextAt("note.labels."))).toBeNull();
- expect(searchCompletionSource(contextAt("note.relations."))).toBeNull();
- // A terminal property has nothing to walk onto.
- expect(searchCompletionSource(contextAt("note.title."))).toBeNull();
- expect(searchCompletionSource(contextAt("note.labels.publicationYear."))).toBeNull();
+ it("stops where a terminal property ends the path", async () => {
+ expect(await complete("note.title.")).toBeNull();
+ expect(await complete("note.labels.publicationYear.")).toBeNull();
});
- it("stays quiet on empty space, and offers everything when asked explicitly", () => {
- expect(searchCompletionSource(contextAt("#book "))).toBeNull();
+ it("stays quiet on empty space, and offers everything when asked explicitly", async () => {
+ expect(await complete("#book ")).toBeNull();
- const explicit = searchCompletionSource(contextAt("#book ", { explicit: true }));
+ const explicit = await complete("#book ", { explicit: true });
expect(explicit?.from).toBe(6);
// The six words, then every operator.
expect(explicit?.options).toHaveLength(18);
});
+
+ describe("attribute names", () => {
+ it("fetches labels for #, anchored past the prefix and past a negation", async () => {
+ const result = await complete("towers #bo");
+
+ expect(server.get).toHaveBeenCalledWith("attribute-names/?type=label&query=");
+ expect(result?.from).toBe(8);
+ expect(labelsOf(result)).toEqual([ "book", "publicationYear" ]);
+
+ expect((await complete("#!bo"))?.from).toBe(2);
+ });
+
+ it("fetches relations for ~, and for the segment after note.relations.", async () => {
+ await complete("~aut");
+
+ expect(server.get).toHaveBeenCalledWith("attribute-names/?type=relation&query=");
+
+ const inPath = await complete("note.relations.aut");
+
+ expect(server.get).toHaveBeenLastCalledWith("attribute-names/?type=relation&query=");
+ expect(inPath?.from).toBe(15);
+ expect(labelsOf(inPath)).toEqual([ "book", "publicationYear" ]);
+ });
+
+ it("fetches labels for the segment after note.labels.", async () => {
+ const result = await complete("note.labels.");
+
+ expect(server.get).toHaveBeenCalledWith("attribute-names/?type=label&query=");
+ expect(result?.from).toBe(12);
+ });
+
+ it("leaves the fuzzy operators to the operator branch", async () => {
+ expect(labelsOf(await complete("note.title ~="))).toContain("~=");
+ expect(server.get).not.toHaveBeenCalled();
+ });
+
+ it("offers nothing when the request fails", async () => {
+ vi.mocked(server.get).mockRejectedValue(new Error("offline"));
+
+ expect(await complete("#bo")).toBeNull();
+ });
+ });
});
+async function complete(text: string, opts?: { explicit?: boolean }) {
+ return await searchCompletionSource(contextAt(text, opts));
+}
+
function labelsOf(result: CompletionResult | null): string[] {
return (result?.options ?? []).map((option) => option.label);
}
diff --git a/apps/client/src/widgets/ribbon/search_completions.ts b/apps/client/src/widgets/ribbon/search_completions.ts
index 3d7113e381..5e20da60aa 100644
--- a/apps/client/src/widgets/ribbon/search_completions.ts
+++ b/apps/client/src/widgets/ribbon/search_completions.ts
@@ -1,22 +1,37 @@
-import { SEARCH_NOTE_PATH, SEARCH_NOTE_PATH_SEGMENTS } from "@triliumnext/commons";
import type { Completion, CompletionContext, CompletionResult } from "@triliumnext/codemirror/src/single_line";
+import { SEARCH_NOTE_PATH, SEARCH_NOTE_PATH_SEGMENTS } from "@triliumnext/commons";
import { t } from "../../services/i18n";
+import server from "../../services/server";
+
+/** A branch answers at once, or after the attribute names have been fetched. */
+type CompletionOutcome = CompletionResult | Promise<CompletionResult | null> | null;
/**
- * Offers Trilium's search syntax: the `note` object, the property path that hangs off it or off a
- * relation, and the comparison operators, whose spellings (`*=*`, `=*`, `~=`) are the part of the
- * syntax hardest to recall.
+ * Offers Trilium's search syntax: the `note` object, the keywords, the property path that hangs off
+ * `note` or off a relation, the comparison operators — whose spellings (`*=*`, `=*`, `~=`) are the
+ * part of the syntax hardest to recall — and the label and relation names in the database.
*
- * Attribute names and values are not offered — reading those needs the notes being searched, which
- * a source built from static text cannot see.
+ * Attribute values are not offered yet.
*/
-export function searchCompletionSource(context: CompletionContext): CompletionResult | null {
+export function searchCompletionSource(context: CompletionContext): CompletionOutcome {
const path = context.matchBefore(PROPERTY_PATH);
if (path) {
return pathCompletions(path.text, context.pos);
}
+ // `~=` and `~*` reach the operators below instead: an attribute name cannot be spelled with
+ // either character, so the pattern finds nothing ending at the cursor.
+ const attribute = context.matchBefore(ATTRIBUTE_PREFIX);
+ if (attribute) {
+ const isNegated = attribute.text[1] === "!";
+
+ return attributeCompletions(
+ attribute.text[0] === "#" ? "label" : "relation",
+ attribute.from + (isNegated ? 2 : 1)
+ );
+ }
+
const operator = context.matchBefore(OPERATOR_PREFIX);
if (operator) {
return { from: operator.from, options: operatorOptions(), validFor: OPERATOR_PREFIX };
@@ -48,17 +63,44 @@ const PROPERTY_PATH = new RegExp(`(?:^|[\\s(])(?:note|~${SEGMENT}+)(?:\\.${SEGME
const SEGMENT_TYPED = new RegExp(`${SEGMENT}*`);
/** Matches once an `orderBy` has been opened anywhere before the cursor. */
const ORDER_BY_BEFORE = /orderby[^]*/i;
+/** A `#label` or `~relation`, either optionally negated with `!`. */
+const ATTRIBUTE_PREFIX = new RegExp(`[#~]!?${SEGMENT}*`);
+
+/**
+ * Fetches the label or relation names the database holds, from the endpoint the attribute editor's
+ * own autocomplete reads. The whole set is asked for once and narrowed by `validFor` as more of the
+ * name is typed, rather than a request per keystroke.
+ */
+async function attributeCompletions(type: "label" | "relation", from: number): Promise<CompletionResult | null> {
+ let names: string[];
+ try {
+ names = await server.get<string[]>(`attribute-names/?type=${type}&query=`);
+ } catch {
+ return null;
+ }
+
+ return {
+ from,
+ options: names.map((name) => ({ label: name, type: type === "label" ? "property" : "class" })),
+ validFor: SEGMENT_TYPED
+ };
+}
/**
- * Completes the segment being typed at the end of `path`, where the grammar allows one. Nothing is
- * offered after `note.labels.`, which expects a label name, or after `note.title.`, which is the
- * end of the path — a terminal property has nothing to walk onto.
+ * Completes the segment being typed at the end of `path`. After `note.labels.` or
+ * `note.relations.` that is an attribute name; after `note.title.` it is nothing at all, a
+ * terminal property having nothing to walk onto.
*/
-function pathCompletions(path: string, pos: number): CompletionResult | null {
+function pathCompletions(path: string, pos: number): CompletionOutcome {
const segments = path.split(".");
const typed = segments[segments.length - 1];
const previous = segments[segments.length - 2];
const beforeThat = segments[segments.length - 3];
+ const from = pos - typed.length;
+
+ if (previous === "labels" || previous === "relations") {
+ return attributeCompletions(previous === "labels" ? "label" : "relation", from);
+ }
// A segment follows the root, a traversal, or the relation name reached through `relations`.
const isAllowed = segments.length === 2
@@ -69,7 +111,7 @@ function pathCompletions(path: string, pos: number): CompletionResult | null {
return null;
}
- return { from: pos - typed.length, options: segmentOptions(), validFor: SEGMENT_TYPED };
+ return { from, options: segmentOptions(), validFor: SEGMENT_TYPED };
}
/**