Skip to content

Build your personal knowledge base with Trilium Notes

feat(markdown): draw note links as chips with the note's icon and title

Elian Dorana224c6a74f7c
diff --git a/apps/client/src/widgets/search_field_editor.tsx b/apps/client/src/widgets/search_field_editor.tsx
index 8a69e640f0..08cfd38d1b 100644
--- a/apps/client/src/widgets/search_field_editor.tsx
+++ b/apps/client/src/widgets/search_field_editor.tsx
@@ -120,10 +120,11 @@ function createSearchCompletionList() {
}
/**
- * 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.
+ * Names the note an id stands for, for the chips of the search field and of a Markdown note's links.
+ * 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 {
+export function resolveNoteChip(noteId: string): NoteChip | Promise<NoteChip | null> | null {
const cached = froca.getNoteFromCache(noteId);
if (cached) {
return { title: cached.title, icon: cached.getIcon() };
diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
index af215cbfdb..fd8174379e 100644
--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
@@ -2,6 +2,7 @@ import "./Markdown.css";
import "./MarkdownCommons.css";
import VanillaCodeMirror from "@triliumnext/codemirror";
+import { findWikilinkNoteIds, triliumNoteChips } from "@triliumnext/codemirror/src/extensions/trilium_note_chips";
import { CustomMarkdownRenderer, renderToHtml } from "@triliumnext/commons/src/lib/markdown_renderer";
import { createLiteralTildeExtension } from "@triliumnext/commons/src/lib/marked_extensions";
import DOMPurify from "dompurify";
@@ -20,6 +21,7 @@ import { removeIndividualBinding } from "../../../services/shortcuts";
import tree from "../../../services/tree";
import utils, { isDesktop } from "../../../services/utils";
import { useLegacyImperativeHandlers, useTriliumEvent } from "../../react/hooks";
+import { resolveNoteChip } from "../../search_field_editor";
import { extractHighlightsFromStaticHtml, type RawHighlight } from "../../sidebar/highlights_extract";
import SplitEditor from "../helpers/SplitEditor";
import { ReadOnlyTextContent } from "../text/ReadOnlyText";
@@ -103,6 +105,7 @@ export default function Markdown(props: TypeWidgetProps) {
usePublishHighlights(props.noteContext, editorView, highlights, props.note);
useImageDrop(props.note, editorView);
useTextCommands(props.parentComponent, editorView);
+ useNoteLinkChips(editorView);
useMarkdownCompletions(props.parentComponent, editorView, props.note, () => props.noteContext?.notePath);
useMarkdownKeymap(editorView);
@@ -433,6 +436,22 @@ function useTextCommands(parentComponent: TypeWidgetProps["parentComponent"], ed
* Adds markdown-specific formatting shortcuts (bold, italic, strikethrough, math).
* Toggles the wrapper around the selection, or inserts it at the cursor.
*/
+/**
+ * Draws the `[[noteId]]` links as chips with the note's icon and title, as the search field draws
+ * its note ids, showing a link's text while the selection touches it so it stays editable.
+ */
+function useNoteLinkChips(editorView: VanillaCodeMirror | null) {
+ useEffect(() => {
+ if (!editorView) return;
+
+ editorView.setNamedExtension("noteLinkChips", triliumNoteChips(resolveNoteChip, {
+ find: findWikilinkNoteIds,
+ revealAtSelection: true
+ }));
+ return () => editorView.setNamedExtension("noteLinkChips", []);
+ }, [editorView]);
+}
+
function useMarkdownKeymap(editorView: VanillaCodeMirror | null) {
useEffect(() => {
if (!editorView) return;
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html
index 42167e23a9..e48e9b0fe1 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html
@@ -228,6 +228,11 @@
existing link points, place the cursor inside it and pick another note.</p>
<p>Like slash commands, <code>@</code> and <code>[[</code> do nothing inside
code blocks and inline code.</p>
+<p>In the editor, a <code>[[noteId]]</code> link shows as the note's icon and
+ title, so you can tell which note it points to without looking up its ID.
+ Clicking it, or moving the cursor next to it, shows the link as written
+ so it can be edited. Links inside code blocks and inline code are left
+ as they are.</p>
<h4>Code block language auto-completion</h4>
<p>Starting with v0.104.0, typing ``` to insert a code block will automatically
open a list of suggested language types which have syntax highlighting.</p>
diff --git a/docs/User Guide/User Guide/Note Types/Markdown.md b/docs/User Guide/User Guide/Note Types/Markdown.md
index fc54d8066d..f22742c367 100644
--- a/docs/User Guide/User Guide/Note Types/Markdown.md
+++ b/docs/User Guide/User Guide/Note Types/Markdown.md
@@ -185,6 +185,8 @@ You can also start typing the link directly: `[[` opens the same list, and closi
Like slash commands, `@` and `[[` do nothing inside code blocks and inline code.
+In the editor, a `[[noteId]]` link shows as the note's icon and title, so you can tell which note it points to without looking up its ID. Clicking it, or moving the cursor next to it, shows the link as written so it can be edited. Links inside code blocks and inline code are left as they are.
+
#### Code block language auto-completion
Starting with v0.104.0, typing \`\`\` to insert a code block will automatically open a list of suggested language types which have syntax highlighting.
diff --git a/packages/codemirror/src/extensions/trilium_note_chips.spec.ts b/packages/codemirror/src/extensions/trilium_note_chips.spec.ts
index 2a1adb3a13..b0e641e64b 100644
--- a/packages/codemirror/src/extensions/trilium_note_chips.spec.ts
+++ b/packages/codemirror/src/extensions/trilium_note_chips.spec.ts
@@ -1,9 +1,11 @@
+import { markdown } from "@codemirror/lang-markdown";
+import { ensureSyntaxTree } from "@codemirror/language";
import { EditorSelection, type Extension } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
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";
+import { findWikilinkNoteIds, type NoteChip, type NoteChipOptions, type NoteChipResolver, triliumNoteChips } from "./trilium_note_chips.js";
let editor: FieldEditor | undefined;
@@ -125,12 +127,54 @@ describe("triliumNoteChips", () => {
});
});
-function build(doc: string, resolve: NoteChipResolver, extensions: Extension[] = []) {
+describe("triliumNoteChips over Markdown's note links", () => {
+ const WIKILINKS: NoteChipOptions = { find: findWikilinkNoteIds, revealAtSelection: true };
+
+ /** A Markdown editor over `doc`, its syntax tree parsed, the caret at `caret`. */
+ function buildMarkdown(doc: string, caret = 0) {
+ const parent = build(doc, () => TOLKIEN, [ markdown() ], WIKILINKS);
+ const view = editorFor(parent);
+ ensureSyntaxTree(view.state, doc.length);
+ view.dispatch({ selection: EditorSelection.cursor(caret) });
+ return { parent, view };
+ }
+
+ it("draws each link as one chip, leaving the text and the links in code alone", () => {
+ const { parent, view } = buildMarkdown("See [[abc123]] and `[[code1]]`, or [[ bad ]].\n\n```\n[[block1]]\n```");
+
+ const chips = [ ...parent.querySelectorAll(".cm-note-chip") ];
+ expect(chips.map((chip) => chip.getAttribute("title"))).toEqual([ "abc123" ]);
+ expect(parent.textContent).toContain("See Tolkien and");
+ expect(parent.textContent).not.toContain("[[abc123]]");
+ expect(parent.textContent).toContain("[[code1]]");
+ expect(parent.textContent).toContain("[[block1]]");
+ expect(view.state.doc.toString()).toContain("[[abc123]]");
+ });
+
+ it("shows the link's text while the selection touches it, and lets the caret into it", () => {
+ const { parent, view } = buildMarkdown("See [[abc123]] here", 0);
+ expect(parent.querySelector(".cm-note-chip")).not.toBe(null);
+
+ // At its edge, the link shows as text, and a step goes into it rather than over it.
+ view.dispatch({ selection: EditorSelection.cursor(4) });
+ expect(parent.querySelector(".cm-note-chip")).toBe(null);
+ expect(parent.textContent).toContain("[[abc123]]");
+ expect(view.moveByChar(view.state.selection.main, true).head).toBe(5);
+
+ // A selection across it shows it too, and one away from it draws the chip again.
+ view.dispatch({ selection: EditorSelection.range(0, 17) });
+ expect(parent.querySelector(".cm-note-chip")).toBe(null);
+ view.dispatch({ selection: EditorSelection.cursor(18) });
+ expect(parent.querySelector(".cm-note-chip")?.textContent).toBe("Tolkien");
+ });
+});
+
+function build(doc: string, resolve: NoteChipResolver, extensions: Extension[] = [], options?: NoteChipOptions) {
editor?.destroy();
const parent = document.createElement("div");
document.body.appendChild(parent);
- editor = createFieldEditor({ parent, doc, extensions: [ triliumNoteChips(resolve), ...extensions ] });
+ editor = createFieldEditor({ parent, doc, extensions: [ ...extensions, triliumNoteChips(resolve, options) ] });
return parent;
}
diff --git a/packages/codemirror/src/extensions/trilium_note_chips.ts b/packages/codemirror/src/extensions/trilium_note_chips.ts
index e253423482..96e9738efd 100644
--- a/packages/codemirror/src/extensions/trilium_note_chips.ts
+++ b/packages/codemirror/src/extensions/trilium_note_chips.ts
@@ -1,3 +1,4 @@
+import { syntaxTree } from "@codemirror/language";
import { type EditorState, type Extension, RangeSetBuilder, StateEffect } from "@codemirror/state";
import { Decoration, type DecorationSet, EditorView, ViewPlugin, type ViewUpdate, WidgetType } from "@codemirror/view";
@@ -15,6 +16,26 @@ export interface NoteChip {
*/
export type NoteChipResolver = (noteId: string) => NoteChip | Promise<NoteChip | null> | null;
+/** A note id found in the text, and the range its chip is drawn over. */
+export interface NoteIdRange {
+ from: number;
+ to: number;
+ noteId: string;
+}
+
+/** Finds the note ids in the document between `from` and `to`, left to right. */
+export type NoteIdFinder = (state: EditorState, from: number, to: number) => NoteIdRange[];
+
+export interface NoteChipOptions {
+ /** Where the note ids stand. Defaults to the value of a search query's `noteId` comparison. */
+ find?: NoteIdFinder;
+ /**
+ * Shows the text behind a chip while the selection touches it, so the caret goes into it as into
+ * any text. Without it, each chip is atomic.
+ */
+ revealAtSelection?: boolean;
+}
+
/**
* Draws the note ids in a search query as chips carrying the note's icon and title.
*
@@ -24,18 +45,21 @@ export type NoteChipResolver = (noteId: string) => NoteChip | Promise<NoteChip |
*
* 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.
+ * one again. With `revealAtSelection`, as for a Markdown note's `[[noteId]]` links found by
+ * {@link findWikilinkNoteIds}, the text shows instead while the selection touches it.
+ *
+ * Only the visible part of the document is read, so a long one costs no more than a screenful.
*
* 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 {
+export function triliumNoteChips(resolve: NoteChipResolver, { find = findSearchNoteIds, revealAtSelection = false }: NoteChipOptions = {}): Extension {
const plugin = ViewPlugin.define(
- (view) => new NoteChipsPlugin(view, resolve),
+ (view) => new NoteChipsPlugin(view, resolve, find, revealAtSelection),
{
decorations: (value) => value.decorations,
- provide: (plugin) => EditorView.atomicRanges.of(
+ provide: revealAtSelection ? undefined : (plugin) => EditorView.atomicRanges.of(
(view) => view.plugin(plugin)?.decorations ?? Decoration.none
)
}
@@ -53,28 +77,42 @@ class NoteChipsPlugin {
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);
+ constructor(
+ private readonly view: EditorView,
+ private readonly resolve: NoteChipResolver,
+ private readonly find: NoteIdFinder,
+ private readonly revealAtSelection: boolean
+ ) {
+ this.decorations = this.build();
}
update(update: ViewUpdate) {
const arrived = update.transactions.some(
(tr) => tr.effects.some((effect) => effect.is(noteChipResolved))
);
+ // A finder that reads the syntax tree sees more of it as the parser catches up.
+ const parsed = syntaxTree(update.startState) !== syntaxTree(update.state);
+ const revealed = this.revealAtSelection && update.selectionSet;
- if (update.docChanged || arrived) {
- this.decorations = this.build(update.state);
+ if (update.docChanged || update.viewportChanged || arrived || parsed || revealed) {
+ this.decorations = this.build();
}
}
- private build(state: EditorState): DecorationSet {
+ private build(): DecorationSet {
+ const { state } = this.view;
const builder = new RangeSetBuilder<Decoration>();
- for (const { from, to, noteId } of findNoteIds(state.doc.toString())) {
- const chip = this.chipFor(noteId);
+ for (const visible of this.view.visibleRanges) {
+ for (const { from, to, noteId } of this.find(state, visible.from, visible.to)) {
+ if (this.revealAtSelection && state.selection.ranges.some((range) => range.from <= to && range.to >= from)) {
+ continue;
+ }
- if (chip) {
- builder.add(from, to, Decoration.replace({ widget: new NoteChipWidget(noteId, chip) }));
+ const chip = this.chipFor(noteId);
+ if (chip) {
+ builder.add(from, to, Decoration.replace({ widget: new NoteChipWidget(noteId, chip) }));
+ }
}
}
@@ -146,14 +184,41 @@ class NoteChipWidget extends WidgetType {
*/
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 }[] = [];
+/** The values of a search query's `noteId` comparisons, left to right, as `RangeSetBuilder` needs them. */
+function findSearchNoteIds(state: EditorState, from: number, to: number) {
+ const found: NoteIdRange[] = [];
+
+ for (const match of state.sliceDoc(from, to).matchAll(NOTE_ID_COMPARISON)) {
+ const start = from + match.index + match[1].length;
+
+ found.push({ from: start, to: start + match[2].length, noteId: match[2] });
+ }
+
+ return found;
+}
+
+/** A Markdown note link, `[[noteId]]`, as Trilium writes one. */
+const WIKILINK = /\[\[([A-Za-z0-9_]+)\]\]/g;
- for (const match of text.matchAll(NOTE_ID_COMPARISON)) {
- const from = match.index + match[1].length;
+/**
+ * The `[[noteId]]` links of a Markdown note, each drawn whole, brackets included. A link in a code
+ * block or a code span is code, so it is left as text.
+ */
+export function findWikilinkNoteIds(state: EditorState, from: number, to: number) {
+ const found: NoteIdRange[] = [];
+ const tree = syntaxTree(state);
+
+ for (const match of state.sliceDoc(from, to).matchAll(WIKILINK)) {
+ const start = from + match.index;
+ const innermost = tree.resolveInner(start, 1);
+ let inCode = false;
+ for (let node: typeof innermost | null = innermost; node && !inCode; node = node.parent) {
+ inCode = node.name.includes("Code");
+ }
- found.push({ from, to: from + match[2].length, noteId: match[2] });
+ if (!inCode) {
+ found.push({ from: start, to: start + match[0].length, noteId: match[1] });
+ }
}
return found;