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(search): draw the note ids in a query as chips
Elian Doranccdf71714b94
diff --git a/apps/client/src/widgets/search_field_editor.ts b/apps/client/src/widgets/search_field_editor.tsindex 09e2af6a7b..4731e659e5 100644--- a/apps/client/src/widgets/search_field_editor.ts+++ b/apps/client/src/widgets/search_field_editor.ts@@ -1,10 +1,12 @@import "./search_field_editor.css";+import { type NoteChip, triliumNoteChips } from "@triliumnext/codemirror/src/extensions/trilium_note_chips";import { triliumSearchHighlighter } from "@triliumnext/codemirror/src/extensions/trilium_search_highlighter";import { type SearchLintMessages, triliumSearchLinter } from "@triliumnext/codemirror/src/extensions/trilium_search_lint";import { createFieldEditor, type FieldEditor, type FieldEditorConfig } from "@triliumnext/codemirror/src/field_editor";import type { SearchLintResponse } from "@triliumnext/commons";+import froca from "../services/froca";import { t } from "../services/i18n";import server from "../services/server";import { searchCompletionIcon, searchCompletionReactivates, searchCompletionSource } from "./ribbon/search_completions";@@ -25,13 +27,30 @@ export type SearchFieldEditorConfig = Omit<FieldEditorConfig, "extensions" | "coexport function createSearchFieldEditor(config: SearchFieldEditorConfig): FieldEditor {return createFieldEditor({...config,- extensions: [ triliumSearchHighlighter, triliumSearchLinter(searchLintMessages(), validateOnServer) ],+ extensions: [+ triliumSearchHighlighter,+ triliumSearchLinter(searchLintMessages(), validateOnServer),+ triliumNoteChips(resolveNoteChip)+ ],completionSource: searchCompletionSource,completionIcon: searchCompletionIcon,activateOnCompletion: searchCompletionReactivates});}+/**+ * Names the note an id in the query stands for. Froca answers for one it already holds without a+ * round trip, so a chip for a note on screen is drawn in the same pass the id appears in.+ */+function resolveNoteChip(noteId: string): NoteChip | Promise<NoteChip | null> | null {+ const cached = froca.getNoteFromCache(noteId);+ if (cached) {+ return { title: cached.title, icon: cached.getIcon() };+ }++ return froca.getNote(noteId, true).then((note) => note && { title: note.title, icon: note.getIcon() });+}+/*** Asks the engine to read the query without running it, for the faults the rules in the editor do* not cover. Only reached once those rules are satisfied, so a query they already object to costsdiff --git a/packages/codemirror/src/extensions/trilium_note_chips.spec.ts b/packages/codemirror/src/extensions/trilium_note_chips.spec.tsnew file mode 100644index 0000000000..8ab7e626f1--- /dev/null+++ b/packages/codemirror/src/extensions/trilium_note_chips.spec.ts@@ -0,0 +1,89 @@+import { EditorSelection } from "@codemirror/state";+import { afterEach, describe, expect, it, vi } from "vitest";++import { createFieldEditor, type FieldEditor } from "../field_editor.js";+import { type NoteChip, type NoteChipResolver, triliumNoteChips } from "./trilium_note_chips.js";++let editor: FieldEditor | undefined;++afterEach(() => {+ editor?.destroy();+ editor = undefined;+});++const TOLKIEN: NoteChip = { title: "Tolkien", icon: "bx bx-user" };++describe("triliumNoteChips", () => {+ it("draws a resolved id as a chip without changing what the query holds", () => {+ const parent = build("~author.noteId = abc123", () => TOLKIEN);++ const chip = parent.querySelector(".cm-note-chip");+ expect(chip?.textContent).toBe("Tolkien");+ expect(chip?.getAttribute("title")).toBe("abc123");+ expect(chip?.querySelector(".cm-note-chip-icon")?.className).toContain("bx bx-user");++ // The chip stands over the id; the query is still run with the id itself.+ expect(editor?.state.doc.toString()).toBe("~author.noteId = abc123");+ expect(parent.textContent).not.toContain("abc123");+ });++ it("steps the caret over a chip rather than into it", () => {+ const view = editorFor(build("~author.noteId = abc123", () => TOLKIEN));+ const idStart = "~author.noteId = ".length;++ view.dispatch({ selection: EditorSelection.cursor(idStart) });+ view.dispatch({ selection: view.moveByChar(view.state.selection.main, true) });++ // A character step from the chip's near edge lands past its far edge, not inside it.+ expect(view.state.selection.main.head).toBe(view.state.doc.length);+ });++ it("leaves the id as text when it names no note, and asks only once", () => {+ const resolve = vi.fn<NoteChipResolver>(() => null);+ const parent = build("~author.noteId = gone", resolve);++ expect(parent.querySelector(".cm-note-chip")).toBe(null);+ expect(parent.textContent).toContain("gone");++ editorFor(parent).dispatch({ changes: { from: 0, insert: "#book " } });+ expect(resolve).toHaveBeenCalledTimes(1);+ });++ it("draws the chip once a note asked for asynchronously arrives", async () => {+ const parent = build("~author.noteId = abc123", () => Promise.resolve(TOLKIEN));++ expect(parent.querySelector(".cm-note-chip")).toBe(null);++ await vi.waitFor(() => expect(parent.querySelector(".cm-note-chip")?.textContent).toBe("Tolkien"));+ expect(editor?.state.doc.toString()).toBe("~author.noteId = abc123");+ });++ it("reads only a noteId comparison, leaving id-shaped words of the query alone", () => {+ const resolve = vi.fn<NoteChipResolver>(() => TOLKIEN);+ const parent = build("abc123 #book = abc123 ~author.title = abc123", resolve);++ expect(parent.querySelectorAll(".cm-note-chip").length).toBe(0);+ expect(resolve).not.toHaveBeenCalled();++ // Quoted or not, the value of a `noteId` comparison is one.+ expect(build(`note.noteId = "abc123"`, resolve).querySelectorAll(".cm-note-chip").length).toBe(1);+ });+});++function build(doc: string, resolve: NoteChipResolver) {+ editor?.destroy();++ const parent = document.createElement("div");+ document.body.appendChild(parent);+ editor = createFieldEditor({ parent, doc, extensions: [ triliumNoteChips(resolve) ] });++ return parent;+}++function editorFor(parent: HTMLElement): FieldEditor {+ if (!editor || !parent.contains(editor.dom)) {+ throw new Error("The editor was not built into this element.");+ }++ return editor;+}diff --git a/packages/codemirror/src/extensions/trilium_note_chips.ts b/packages/codemirror/src/extensions/trilium_note_chips.tsnew file mode 100644index 0000000000..e253423482--- /dev/null+++ b/packages/codemirror/src/extensions/trilium_note_chips.ts@@ -0,0 +1,181 @@+import { type EditorState, type Extension, RangeSetBuilder, StateEffect } from "@codemirror/state";+import { Decoration, type DecorationSet, EditorView, ViewPlugin, type ViewUpdate, WidgetType } from "@codemirror/view";++/** What a note id is drawn as, once the consumer has looked the note up. */+export interface NoteChip {+ title: string;+ /** The icon's classes, such as `bx bx-file`. */+ icon: string;+}++/**+ * Answers what a note is called. Returning a value rather than a promise draws the chip in the+ * same pass, so a note already to hand never flickers through its id; `null` means no such note,+ * and leaves the id standing as text.+ */+export type NoteChipResolver = (noteId: string) => NoteChip | Promise<NoteChip | null> | null;++/**+ * Draws the note ids in a search query as chips carrying the note's icon and title.+ *+ * A query stores the id, so it goes on matching a note that has since been renamed — which leaves+ * the field showing a string that says nothing about which note it is. The chip is presentation+ * over that id and never changes it: the text behind a chip is what the query is run with.+ *+ * Each chip is atomic, so the caret steps over it and a backspace beside it takes the whole id+ * rather than a character of it. To point a clause at another note, delete the chip and mention+ * one again.+ *+ * The decorations live in a view plugin rather than a {@link StateField}, unlike+ * `triliumSearchHighlighter`: a note that has to be fetched arrives after the update that asked+ * for it, and the plugin holds the view it dispatches the answer to.+ */+export function triliumNoteChips(resolve: NoteChipResolver): Extension {+ const plugin = ViewPlugin.define(+ (view) => new NoteChipsPlugin(view, resolve),+ {+ decorations: (value) => value.decorations,+ provide: (plugin) => EditorView.atomicRanges.of(+ (view) => view.plugin(plugin)?.decorations ?? Decoration.none+ )+ }+ );++ return [ plugin, noteChipTheme ];+}++/** Dispatched once a note asked for asynchronously arrives, to draw the chip waiting on it. */+const noteChipResolved = StateEffect.define<void>();++class NoteChipsPlugin {+ decorations: DecorationSet;+ /** What each id resolved to, `null` for an id naming no note. Read on every rebuild. */+ private readonly resolved = new Map<string, NoteChip | null>();+ private readonly pending = new Set<string>();++ constructor(private readonly view: EditorView, private readonly resolve: NoteChipResolver) {+ this.decorations = this.build(view.state);+ }++ update(update: ViewUpdate) {+ const arrived = update.transactions.some(+ (tr) => tr.effects.some((effect) => effect.is(noteChipResolved))+ );++ if (update.docChanged || arrived) {+ this.decorations = this.build(update.state);+ }+ }++ private build(state: EditorState): DecorationSet {+ const builder = new RangeSetBuilder<Decoration>();++ for (const { from, to, noteId } of findNoteIds(state.doc.toString())) {+ const chip = this.chipFor(noteId);++ if (chip) {+ builder.add(from, to, Decoration.replace({ widget: new NoteChipWidget(noteId, chip) }));+ }+ }++ return builder.finish();+ }++ /** The chip for an id, asking for one that has not been looked up yet. */+ private chipFor(noteId: string): NoteChip | null {+ const known = this.resolved.get(noteId);+ if (known !== undefined) {+ return known;+ }++ if (this.pending.has(noteId)) {+ return null;+ }++ const answer = this.resolve(noteId);+ if (!(answer instanceof Promise)) {+ this.resolved.set(noteId, answer);+ return answer;+ }++ this.pending.add(noteId);+ void answer+ .catch(() => null)+ .then((chip) => {+ this.pending.delete(noteId);+ this.resolved.set(noteId, chip);+ // Outside the update that asked for it, so dispatching here is safe.+ this.view.dispatch({ effects: noteChipResolved.of() });+ });++ return null;+ }+}++class NoteChipWidget extends WidgetType {+ constructor(private readonly noteId: string, private readonly chip: NoteChip) {+ super();+ }++ override eq(other: NoteChipWidget) {+ return other.noteId === this.noteId+ && other.chip.title === this.chip.title+ && other.chip.icon === this.chip.icon;+ }++ override toDOM() {+ const element = document.createElement("span");+ element.className = "cm-note-chip";+ // Names the id the chip stands for, which is what the query is actually run with.+ element.title = this.noteId;++ const icon = document.createElement("span");+ icon.className = `cm-note-chip-icon ${this.chip.icon}`;+ icon.setAttribute("aria-hidden", "true");++ element.append(icon, this.chip.title);++ return element;+ }+}++/**+ * A note id standing as the value of a `noteId` comparison. Only that position is read, rather+ * than every word shaped like an id, so an ordinary word of the full-text query is never drawn as+ * a note. The leading group runs to the value so its length places the value in the query.+ */+const NOTE_ID_COMPARISON = /(\.noteId\s*(?:!?=|\*=\*|=\*|\*=)\s*["'`]?)([A-Za-z0-9_]+)/g;++/** The ranges holding a note id, left to right, as `RangeSetBuilder` needs them. */+function findNoteIds(text: string) {+ const found: { from: number; to: number; noteId: string }[] = [];++ for (const match of text.matchAll(NOTE_ID_COMPARISON)) {+ const from = match.index + match[1].length;++ found.push({ from, to: from + match[2].length, noteId: match[2] });+ }++ return found;+}++/**+ * Named beside the `--search-*` palette the Next themes define. The fallback mixes the chip out of+ * the text colour, so it holds up on a light and a dark background alike where nothing defines it.+ */+const noteChipTheme = EditorView.baseTheme({+ ".cm-note-chip": {+ display: "inline-flex",+ alignItems: "center",+ gap: "0.25em",+ padding: "0 0.4em",+ borderRadius: "0.75em",+ background: "var(--search-chip-background-color, color-mix(in srgb, currentColor 12%, transparent))",+ color: "var(--search-chip-color, inherit)",+ whiteSpace: "nowrap",+ verticalAlign: "baseline"+ },+ ".cm-note-chip-icon": {+ opacity: "0.7"+ }+});