Skip to content

Build your personal knowledge base with Trilium Notes

feat(search): draw attribute names in the completion with their own icons

Elian Doran7d53f35b308e
diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.css b/apps/client/src/widgets/ribbon/SearchStringEditor.css
index 835fa3c1ad..fdc97df8af 100644
--- a/apps/client/src/widgets/ribbon/SearchStringEditor.css
+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.css
@@ -42,12 +42,21 @@
max-height: 18em;
}
+ /* The description carries a full row's width, so it wraps onto its own line while the icon
+ and the label stay centred against each other on the first. */
& > ul > li {
- display: block;
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
padding: 0.5em 1em;
line-height: 1.2;
}
+ .cm-completion-glyph {
+ margin-inline-end: 0.4em;
+ opacity: 0.7;
+ }
+
.cm-completionLabel {
/* Bold like the slash-command palette's, and monospace because it is query syntax. */
font-family: monospace;
@@ -55,7 +64,7 @@
}
.cm-completionDetail {
- display: block;
+ flex-basis: 100%;
margin-left: 0;
font-size: 0.75em;
font-style: normal;
@@ -70,13 +79,6 @@
background: var(--active-item-background-color, color-mix(in srgb, var(--main-text-color) 15%, transparent));
color: var(--active-item-text-color, inherit);
}
-
- /* The stock icons are a key for every operator and a square for `note`, which say less
- than the descriptions beside them. */
- .cm-completionIcon {
- display: none;
- }
-
}
.cm-placeholder {
diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
index 06ce06fb0e..12fa6e1593 100644
--- a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx
@@ -4,7 +4,7 @@ import type { SingleLineEditor } from "@triliumnext/codemirror/src/single_line";
import clsx from "clsx";
import { useEffect, useRef } from "preact/hooks";
-import { searchCompletionSource } from "./search_completions";
+import { searchCompletionIcon, searchCompletionSource } from "./search_completions";
interface SearchStringEditorProps {
currentValue: string;
@@ -48,6 +48,7 @@ export default function SearchStringEditor({ currentValue, placeholder, classNam
placeholder,
extensions: [ triliumSearchHighlighter ],
completionSource: searchCompletionSource,
+ completionIcon: searchCompletionIcon,
onChange: (value) => propsRef.current.onChange(value),
onEnter: () => propsRef.current.onEnter()
});
diff --git a/apps/client/src/widgets/ribbon/search_completions.spec.ts b/apps/client/src/widgets/ribbon/search_completions.spec.ts
index c3cdfeedf5..444e1760bd 100644
--- a/apps/client/src/widgets/ribbon/search_completions.spec.ts
+++ b/apps/client/src/widgets/ribbon/search_completions.spec.ts
@@ -1,15 +1,18 @@
import type { CompletionContext, CompletionResult } from "@triliumnext/codemirror/src/single_line";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import server from "../../services/server";
-import { searchCompletionSource } from "./search_completions";
+import { fetchAttributeNames } from "../attribute_widgets/attribute_detail";
+import { searchCompletionIcon, 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() } }));
+// Stubbed at the same seam the sidebar's picker fetches through, so the spec needs no server and
+// none of the attribute popup behind it. `isBuiltinAttribute` is left real: what it marks is the
+// point of these tests.
+vi.mock("../attribute_widgets/attribute_detail", () => ({ fetchAttributeNames: vi.fn() }));
beforeEach(() => {
- vi.mocked(server.get).mockReset().mockResolvedValue([ "book", "publicationYear" ]);
+ vi.mocked(fetchAttributeNames).mockReset().mockResolvedValue([ "book", "archived" ]);
});
describe("searchCompletionSource", () => {
@@ -82,9 +85,9 @@ describe("searchCompletionSource", () => {
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(fetchAttributeNames).toHaveBeenCalledWith("label", "");
expect(result?.from).toBe(8);
- expect(labelsOf(result)).toEqual([ "book", "publicationYear" ]);
+ expect(labelsOf(result)).toEqual([ "book", "archived" ]);
expect((await complete("#!bo"))?.from).toBe(2);
});
@@ -92,35 +95,66 @@ describe("searchCompletionSource", () => {
it("fetches relations for ~, and for the segment after note.relations.", async () => {
await complete("~aut");
- expect(server.get).toHaveBeenCalledWith("attribute-names/?type=relation&query=");
+ expect(fetchAttributeNames).toHaveBeenCalledWith("relation", "");
const inPath = await complete("note.relations.aut");
- expect(server.get).toHaveBeenLastCalledWith("attribute-names/?type=relation&query=");
+ expect(fetchAttributeNames).toHaveBeenLastCalledWith("relation", "");
expect(inPath?.from).toBe(15);
- expect(labelsOf(inPath)).toEqual([ "book", "publicationYear" ]);
+ expect(labelsOf(inPath)).toEqual([ "book", "archived" ]);
});
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(fetchAttributeNames).toHaveBeenCalledWith("label", "");
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();
+ expect(fetchAttributeNames).not.toHaveBeenCalled();
});
it("offers nothing when the request fails", async () => {
- vi.mocked(server.get).mockRejectedValue(new Error("offline"));
+ vi.mocked(fetchAttributeNames).mockRejectedValue(new Error("offline"));
expect(await complete("#bo")).toBeNull();
});
});
});
+describe("searchCompletionIcon", () => {
+ it("draws attribute names, the system ones with a cog rather than their own kind", async () => {
+ vi.mocked(fetchAttributeNames).mockResolvedValue([ "book", "archived" ]);
+ const labels = await complete("#a");
+
+ expect(iconFor(labels, "book")).toBe("bx bx-hash");
+ expect(iconFor(labels, "archived")).toBe("bx bx-cog");
+
+ vi.mocked(fetchAttributeNames).mockResolvedValue([ "author", "template", "archived" ]);
+ const relations = await complete("~a");
+
+ expect(iconFor(relations, "author")).toBe("bx bx-transfer");
+ expect(iconFor(relations, "template")).toBe("bx bx-cog");
+ // Built-in as a label, an ordinary name as a relation.
+ expect(iconFor(relations, "archived")).toBe("bx bx-transfer");
+ });
+
+ it("leaves everything else undrawn", async () => {
+ expect(iconFor(await complete("no"), "note")).toBeUndefined();
+ expect(iconFor(await complete("or"), "orderBy")).toBeUndefined();
+ expect(iconFor(await complete("note."), "title")).toBeUndefined();
+ expect(iconFor(await complete("#year >"), ">=")).toBeUndefined();
+ });
+});
+
+function iconFor(result: CompletionResult | null, label: string) {
+ const option = optionFor(result, label);
+
+ return option ? searchCompletionIcon(option) : "no such option";
+}
+
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 5e20da60aa..0b72e00ce3 100644
--- a/apps/client/src/widgets/ribbon/search_completions.ts
+++ b/apps/client/src/widgets/ribbon/search_completions.ts
@@ -1,8 +1,9 @@
import type { Completion, CompletionContext, CompletionResult } from "@triliumnext/codemirror/src/single_line";
import { SEARCH_NOTE_PATH, SEARCH_NOTE_PATH_SEGMENTS } from "@triliumnext/commons";
+import { isBuiltinAttribute } from "../../services/attributes";
import { t } from "../../services/i18n";
-import server from "../../services/server";
+import { fetchAttributeNames } from "../attribute_widgets/attribute_detail";
/** A branch answers at once, or after the attribute names have been fetched. */
type CompletionOutcome = CompletionResult | Promise<CompletionResult | null> | null;
@@ -67,25 +68,42 @@ const ORDER_BY_BEFORE = /orderby[^]*/i;
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.
+ * 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
+ * for once and narrowed by `validFor` as more of the name is typed, rather than 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=`);
+ names = await fetchAttributeNames(type, "");
} catch {
return null;
}
return {
from,
- options: names.map((name) => ({ label: name, type: type === "label" ? "property" : "class" })),
+ options: names.map((name) => ({
+ label: name,
+ type: isBuiltinAttribute(type, name) ? SYSTEM_ATTRIBUTE : type
+ })),
validFor: SEGMENT_TYPED
};
}
+/** Stands in for a completion's own type, a name Trilium attaches a meaning to being marked first. */
+const SYSTEM_ATTRIBUTE = "system-attribute";
+
+const COMPLETION_ICONS: Record<string, string> = {
+ [SYSTEM_ATTRIBUTE]: "bx bx-cog",
+ label: "bx bx-hash",
+ relation: "bx bx-transfer"
+};
+
+/** The icon an option is drawn with. Only the attribute names carry one. */
+export function searchCompletionIcon(completion: Completion): string | undefined {
+ return completion.type ? COMPLETION_ICONS[completion.type] : undefined;
+}
+
/**
* 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
diff --git a/packages/codemirror/src/single_line.ts b/packages/codemirror/src/single_line.ts
index b16286dc01..3cf1438bb7 100644
--- a/packages/codemirror/src/single_line.ts
+++ b/packages/codemirror/src/single_line.ts
@@ -1,4 +1,4 @@
-import { autocompletion, type CompletionSource } from "@codemirror/autocomplete";
+import { autocompletion, type Completion, type CompletionSource } from "@codemirror/autocomplete";
import { history, historyKeymap, standardKeymap } from "@codemirror/commands";
import { EditorState, type Extension } from "@codemirror/state";
import { EditorView, keymap, placeholder } from "@codemirror/view";
@@ -18,6 +18,11 @@ export interface SingleLineEditorConfig {
extensions?: Extension[];
/** Completions to offer as the value is typed. Without one, the editor has no autocompletion. */
completionSource?: CompletionSource;
+ /**
+ * The icon classes a completion is drawn with, such as `bx bx-hash`. Completions it answers
+ * nothing for are drawn without one; supplying it at all replaces CodeMirror's own icons.
+ */
+ completionIcon?(completion: Completion): string | undefined;
/** Runs after every document change, with the whole text. */
onChange?(value: string): void;
/** Runs when Enter is pressed; the key never inserts a line break. */
@@ -65,9 +70,16 @@ export function createSingleLineEditor(config: SingleLineEditorConfig): SingleLi
}
if (config.completionSource) {
+ const icon = config.completionIcon;
+
// The completion keymap is registered at the highest precedence, so Enter picks the
// selected option while the popup is open and reaches `onEnter` the rest of the time.
- extensions.push(autocompletion({ override: [ config.completionSource ], activateOnTyping: true }));
+ extensions.push(autocompletion({
+ override: [ config.completionSource ],
+ activateOnTyping: true,
+ icons: !icon,
+ addToOptions: icon ? [ { position: ICON_POSITION, render: (completion) => renderIcon(icon(completion)) } ] : []
+ }));
}
return new EditorView({
@@ -77,6 +89,22 @@ export function createSingleLineEditor(config: SingleLineEditorConfig): SingleLi
});
}
+/** Where CodeMirror draws its own icons, which {@link SingleLineEditorConfig.completionIcon} takes over. */
+const ICON_POSITION = 20;
+
+function renderIcon(classes: string | undefined) {
+ if (!classes) {
+ return null;
+ }
+
+ const element = document.createElement("span");
+ element.className = `cm-completion-glyph ${classes}`;
+ // The label beside it already says what the icon repeats.
+ element.setAttribute("aria-hidden", "true");
+
+ return element;
+}
+
/**
* Keeps the document on one line. Typing a line break is already impossible because Enter is
* bound, so this covers text arriving by paste or drop: every run of whitespace holding a line