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(text): show the stored title of a reference link to a missing note
Elian Doranc4a142f7c87f
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex c6b3930af4..381da2663e 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -89,7 +89,8 @@ export async function postProcessRichContent(note: FNote | FAttachment, $rendereconst hostNoteId = note instanceof FNote ? note.noteId : undefined;await Promise.all(referenceLinks.toArray().map(async (el) => {const innerSpan = document.createElement("span");- await link.loadReferenceLinkTitle($(innerSpan), el.getAttribute("href"), hostNoteId);+ await link.loadReferenceLinkTitle($(innerSpan), el.getAttribute("href"), hostNoteId,+ el.textContent ?? undefined);el.replaceChildren(innerSpan);}));diff --git a/apps/client/src/services/glob.spec.ts b/apps/client/src/services/glob.spec.tsindex c00a74ea24..955a640fb6 100644--- a/apps/client/src/services/glob.spec.ts+++ b/apps/client/src/services/glob.spec.ts@@ -80,8 +80,8 @@ describe("setupGlobs", () => {await expect(window.glob.getReferenceLinkTitle("#root/abc")).resolves.toBe("async:#root/abc");expect(getReferenceLinkTitle).toHaveBeenCalledWith("#root/abc");- expect(window.glob.getReferenceLinkTitleSync("#root/def")).toBe("sync:#root/def");- expect(getReferenceLinkTitleSync).toHaveBeenCalledWith("#root/def");+ expect(window.glob.getReferenceLinkTitleSync("#root/def", "Stored")).toBe("sync:#root/def");+ expect(getReferenceLinkTitleSync).toHaveBeenCalledWith("#root/def", "Stored");});it("loads each configured app CSS note that isn't already present", () => {diff --git a/apps/client/src/services/glob.ts b/apps/client/src/services/glob.tsindex a4444afc93..85f149fb6a 100644--- a/apps/client/src/services/glob.ts+++ b/apps/client/src/services/glob.ts@@ -12,7 +12,8 @@ function setupGlobs() {window.glob.getComponentByEl = (el) => appContext.getComponentByEl(el);window.glob.getHeaders = server.getHeaders;window.glob.getReferenceLinkTitle = (href) => linkService.getReferenceLinkTitle(href);- window.glob.getReferenceLinkTitleSync = (href) => linkService.getReferenceLinkTitleSync(href);+ window.glob.getReferenceLinkTitleSync = (href, storedTitle) =>+ linkService.getReferenceLinkTitleSync(href, storedTitle);// required for ESLint plugin and CKEditorwindow.glob.getActiveContextNote = () => appContext.tabManager.getActiveContextNote();diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.tsindex 91014477f6..1026f4e89a 100644--- a/apps/client/src/services/link.spec.ts+++ b/apps/client/src/services/link.spec.ts@@ -920,11 +920,14 @@ describe("getReferenceLinkTitle / getReferenceLinkTitleSync", () => {.toBe("Paper - pdf.page_reference");});- it("getReferenceLinkTitleSync returns [missing note] when the note is not in cache", () => {- const orig = froca.getNoteFromCache;- froca.getNoteFromCache = vi.fn(() => null) as unknown as typeof froca.getNoteFromCache;- expect(linkService.getReferenceLinkTitleSync("#root/aaaaaaaaaaaa")).toBe("[missing note]");- froca.getNoteFromCache = orig;+ it("getReferenceLinkTitleSync returns the stored title or [missing note] when the note is not in cache", () => {+ const getNoteFromCache = vi.spyOn(froca, "getNoteFromCache").mockReturnValue(undefined);+ const unknownTitle = linkService.getReferenceLinkTitleSync("#root/aaaaaaaaaaaa");+ const storedTitle = linkService.getReferenceLinkTitleSync("#root/aaaaaaaaaaaa", "Stored");+ getNoteFromCache.mockRestore();++ expect(unknownTitle).toBe("[missing note]");+ expect(storedTitle).toBe("Stored");});});@@ -1040,17 +1043,22 @@ describe("loadReferenceLinkTitle", () => {expect($el.text()).toContain("Inner");});- it("renders the title without color class / icon when the note is not found", async () => {- const orig = froca.getNote;- // First lookup (for color/icon) returns null; getReferenceLinkTitle also returns missing note.- froca.getNote = vi.fn(async () => null) as typeof froca.getNote;- const $a = $("<a>").attr("href", "#root/aaaaaaaaaaaa");- const $el = $("<span>").append($a);- await linkService.loadReferenceLinkTitle($el, "#root/aaaaaaaaaaaa");- expect($el.text()).toBe("[missing note]");- // no color class span and no prepended icon since the note was absent- expect($el.find("small").length).toBe(0);- froca.getNote = orig;+ it("renders a missing note with the title stored in the content, an X icon and in red", async () => {+ const getNote = vi.spyOn(froca, "getNote").mockResolvedValue(null);+ const $stored = $("<span>");+ const $unknown = $("<span>");++ await linkService.loadReferenceLinkTitle($stored, "#root/aaaaaaaaaaaa?bookmark=Sec", undefined,+ "Deleted note");+ await linkService.loadReferenceLinkTitle($unknown, "#root/aaaaaaaaaaaa");+ getNote.mockRestore();++ expect($stored.text()).toBe("Deleted note");+ expect($stored.hasClass("reference-link-missing")).toBe(true);+ expect($stored.children("span").first().is(".tn-icon.bx.bx-x")).toBe(true);+ expect($stored.find("small").length).toBe(0);+ expect($unknown.text()).toBe("[missing note]");+ expect($unknown.hasClass("reference-link-missing")).toBe(true);});it("does not prepend an icon when the resolved note has no icon", async () => {diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.tsindex 1022eec600..f579db6ea6 100644--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@ -13,6 +13,7 @@ import utils from "./utils.js";/** The icon a column reference uses when the link carries no `columnIcon`. */const DEFAULT_COLUMN_REFERENCE_ICON = "bx bx-columns";+const MISSING_NOTE_TITLE = "[missing note]";function getNotePathFromUrl(url: string) {const notePathMatch = /#(root[A-Za-z0-9_/]*)$/.exec(url);@@ -149,7 +150,7 @@ async function createLink(notePath: string | undefined, options: CreateLinkOptioif (!notePath || !notePath.trim()) {logError("Missing note path");- return $("<span>").text("[missing note]");+ return $("<span>").text(MISSING_NOTE_TITLE);}if (!notePath.startsWith("root")) {@@ -168,7 +169,7 @@ async function createLink(notePath: string | undefined, options: CreateLinkOptioif (!noteId) {logError("Missing note ID");- return $("<span>").text("[missing note]");+ return $("<span>").text(MISSING_NOTE_TITLE);}const viewScope = options.viewScope || {};@@ -661,12 +662,14 @@ function linkContextMenu(e: PointerEvent) {/*** Fills `$el` with the label of the reference link to `href`. A link to blocks of `hostNoteId`, the- * note the link is in, shows only the text of the blocks.+ * note the link is in, shows only the text of the blocks. A link to a note that does not exist+ * shows `storedTitle`, the title the content holds for it.*/async function loadReferenceLinkTitle($el: JQuery<HTMLElement>,href: string | null | undefined = null,- hostNoteId?: string+ hostNoteId?: string,+ storedTitle?: string) {const $link = $el[0].tagName === "A" ? $el : $el.find("a");@@ -678,12 +681,8 @@ async function loadReferenceLinkTitle(const { noteId, viewScope } = parseNavigationStateFromUrl(href);if (!noteId) {- // Warned about but not returned on. The editing downcast creates an empty <span> and this- // call is the only thing that ever fills it, so bailing here left the widget rendering as- // nothing at all while the stored HTML — which resolves its title through- // getReferenceLinkTitleSync instead — said "[missing note]". An href that is not a hash- // note URL is ordinary enough to reach: an attachment image URL, an external link, or- // imported HTML carrying an <a class="reference-link">.+ // Not returned on: the editing downcast creates an empty <span> that only this call fills.+ // An attachment image URL, an external link or imported HTML can carry such an href.console.warn("Missing note ID.");}@@ -702,10 +701,15 @@ async function loadReferenceLinkTitle(}}- if (note) {- $el.addClass(note.getColorClass());+ if (!note) {+ $el.text(storedTitle || MISSING_NOTE_TITLE)+ .addClass("reference-link-missing")+ .prepend($("<span>").addClass("tn-icon bx bx-x"));+ return;}+ $el.addClass(note.getColorClass());+const title = await getReferenceLinkTitle(href);// A column reference renders as "<board>: <column>", the column in a `<small>` below.$el.text(viewScope?.columnTitle ? `${title}:` : title);@@ -717,7 +721,7 @@ async function loadReferenceLinkTitle());}- if (viewScope?.block && note) {+ if (viewScope?.block) {const label = await loadBlockReferenceLabel(note, viewScope.block);if (label) {$el.append($("<small>")@@ -745,25 +749,22 @@ async function loadReferenceLinkTitle());}- if (subjectId && note) {- const icon = await getLinkIcon(subjectId, viewScope?.viewMode);-- if (icon) {- $el.prepend($("<span>").addClass(icon));- }+ const icon = await getLinkIcon(note.noteId, viewScope?.viewMode);+ if (icon) {+ $el.prepend($("<span>").addClass(icon));}}async function getReferenceLinkTitle(href: string) {const { noteId, viewScope } = parseNavigationStateFromUrl(href);if (!noteId) {- return "[missing note]";+ return MISSING_NOTE_TITLE;}// A card reference is titled by the card, not by the board in its path.const note = await froca.getNote(viewScope?.card || noteId);if (!note) {- return "[missing note]";+ return MISSING_NOTE_TITLE;}if (viewScope?.viewMode === "attachments" && viewScope?.attachmentId) {@@ -776,15 +777,19 @@ async function getReferenceLinkTitle(href: string) {return note.title;}-function getReferenceLinkTitleSync(href: string) {+/**+ * The label of the reference link to `href`, from the notes already in froca. A link to a note that+ * is not there gets `storedTitle`, the title the content holds for it.+ */+function getReferenceLinkTitleSync(href: string, storedTitle?: string) {const { noteId, viewScope } = parseNavigationStateFromUrl(href);if (!noteId) {- return "[missing note]";+ return storedTitle || MISSING_NOTE_TITLE;}const note = froca.getNoteFromCache(viewScope?.card || noteId);if (!note) {- return "[missing note]";+ return storedTitle || MISSING_NOTE_TITLE;}if (viewScope?.viewMode === "attachments" && viewScope?.attachmentId) {diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex e793d08ebf..2f153da044 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -2283,6 +2283,11 @@ button.close:hover {display: inline-block;}+:root a.reference-link.reference-link-missing,+.ck-content a.reference-link > span.reference-link-missing {+ color: var(--bs-danger);+}+/* The board column a reference points at. `--custom-color` is set by the theme on`.use-note-color`. */.reference-link small.use-note-color {diff --git a/apps/client/src/types.d.ts b/apps/client/src/types.d.tsindex fa9b1282e8..8d65072d00 100644--- a/apps/client/src/types.d.ts+++ b/apps/client/src/types.d.ts@@ -21,7 +21,7 @@ interface CustomGlobals extends BootstrapDefinition {getComponentByEl: typeof appContext.getComponentByEl;getHeaders: typeof server.getHeaders;getReferenceLinkTitle: (href: string) => Promise<string>;- getReferenceLinkTitleSync: (href: string) => string;+ getReferenceLinkTitleSync: (href: string, storedTitle?: string) => string;getActiveContextNote: () => FNote | null;getThemeStyle: () => "auto" | "light" | "dark";ESLINT: Library;diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 3b218fc774..3e3437102b 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -115,8 +115,10 @@ export default function ChatInputBar({// CKEditor's ReferenceLink plugin calls back into the parent component to// resolve a note's title from its href.useLegacyImperativeHandlers({- async loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | null = null) {- await link.loadReferenceLinkTitle($el, href);+ async loadReferenceLinkTitle(+ $el: JQuery<HTMLElement>, href: string | null = null, storedTitle?: string+ ) {+ await link.loadReferenceLinkTitle($el, href, undefined, storedTitle);}});diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsxindex ccb9b0f108..dd73078cfe 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.spec.tsx@@ -133,9 +133,10 @@ describe("CKEditorWithWatchdog", () => {});const $el = $("<span>");- await mocks.handlers.loadReferenceLinkTitle($el, "#root/host1?block=b1");+ await mocks.handlers.loadReferenceLinkTitle($el, "#root/host1?block=b1", "Stored");- expect(loadReferenceLinkTitle).toHaveBeenCalledWith($el, "#root/host1?block=b1", "host1");+ expect(loadReferenceLinkTitle)+ .toHaveBeenCalledWith($el, "#root/host1?block=b1", "host1", "Stored");loadReferenceLinkTitle.mockRestore();});});diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsxindex 7d8b711c00..e238fbd2ed 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx@@ -223,8 +223,10 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRe}));useLegacyImperativeHandlers({- async loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | null = null) {- await link.loadReferenceLinkTitle($el, href, note?.noteId);+ async loadReferenceLinkTitle(+ $el: JQuery<HTMLElement>, href: string | null = null, storedTitle?: string+ ) {+ await link.loadReferenceLinkTitle($el, href, note?.noteId, storedTitle);},async fetchLinkMetadata(url: string) {// The preview's pictures are stored as attachments of the note being edited, so therediff --git a/apps/client/src/widgets/type_widgets/text/read_only_helper.ts b/apps/client/src/widgets/type_widgets/text/read_only_helper.tsindex b83f261021..543273be2a 100644--- a/apps/client/src/widgets/type_widgets/text/read_only_helper.ts+++ b/apps/client/src/widgets/type_widgets/text/read_only_helper.ts@@ -7,7 +7,8 @@ export async function applyReferenceLinks() {const referenceLinks = container.querySelectorAll<HTMLDivElement>("a.reference-link");for (const referenceLink of referenceLinks) {- await link.loadReferenceLinkTitle($(referenceLink), null, hostNoteId);+ await link.loadReferenceLinkTitle($(referenceLink), null, hostNoteId,+ referenceLink.textContent ?? undefined);// Wrap in a <span> to match the design while in CKEditor.const spanEl = document.createElement("span");diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 5526c792f4..aa010d256f 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -82,7 +82,9 @@ declare global {* `customDateTimeFormat` when none is given.*/formatDateTime(date: Date, format?: string): string;- loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string): Promise<void>;+ loadReferenceLinkTitle(+ $el: JQuery<HTMLElement>, href: string, storedTitle?: string+ ): Promise<void>;/*** Fills an embed with the note, or with the `block` of it, a `block` link parameter. An* editor of those blocks calls `onBlockChange()` once the blocks at its edges change.@@ -152,6 +154,6 @@ declare global {/** The headers of a request to the server, with `headers` added to them. */getHeaders(headers?: Record<string, string | undefined>): Promise<Record<string, string>>;getReferenceLinkTitle(href: string): Promise<string>;- getReferenceLinkTitleSync(href: string): string;+ getReferenceLinkTitleSync(href: string, storedTitle?: string): string;};}diff --git a/packages/ckeditor5/src/plugins/referencelink.spec.ts b/packages/ckeditor5/src/plugins/referencelink.spec.tsindex fdafe1d311..7bad5a6cbc 100644--- a/packages/ckeditor5/src/plugins/referencelink.spec.ts+++ b/packages/ckeditor5/src/plugins/referencelink.spec.ts@@ -168,6 +168,7 @@ describe("ReferenceLink", () => {const reference = findReference(editor);expect(reference).toBeDefined();expect(reference?.getAttribute("href")).toBe("#root/noteAbc");+ expect(reference?.getAttribute("storedTitle")).toBe("Some title");});it("renders the reference as an inline widget in the editing view and loads its title", () => {@@ -183,6 +184,7 @@ describe("ReferenceLink", () => {expect(anchor).not.toBeNull();expect(loadReferenceLinkTitle).toHaveBeenCalledTimes(1);expect(loadReferenceLinkTitle.mock.calls[0]?.[1]).toBe("#root/noteAbc");+ expect(loadReferenceLinkTitle.mock.calls[0]?.[2]).toBe("Some title");});it("shows a placeholder's file name, then redraws it as a titled link once uploaded", () => {@@ -210,7 +212,7 @@ describe("ReferenceLink", () => {expect(findAnchor()?.getAttribute("href")).toBe("#root/abc");expect(findAnchor()?.querySelector(".bx-spin")).toBeNull();- expect(loadReferenceLinkTitle).toHaveBeenCalledWith(expect.anything(), "#root/abc");+ expect(loadReferenceLinkTitle).toHaveBeenCalledWith(expect.anything(), "#root/abc", undefined);});it("redraws the links to a changed attachment and removes those to a deleted one", () => {@@ -232,9 +234,9 @@ describe("ReferenceLink", () => {const renamedHref = "#root/owner?viewMode=attachments&attachmentId=renamed";expect([ ...redrawnHrefs ]).toEqual([ renamedHref ]);expect(getModelData(editor.model, { withoutSelection: true })).toBe(- `<paragraph><reference href="${renamedHref}"></reference></paragraph>` ++ `<paragraph><reference href="${renamedHref}" storedTitle="a"></reference></paragraph>` +"<paragraph></paragraph>" +- "<paragraph><reference href=\"#root/noteAbc\"></reference></paragraph>"+ "<paragraph><reference href=\"#root/noteAbc\" storedTitle=\"c\"></reference></paragraph>");// The removal records a change made elsewhere, so undo cannot bring the link back.expect(editor.commands.get("undo")?.isEnabled).toBe(false);@@ -253,7 +255,7 @@ describe("ReferenceLink", () => {{ attachmentId: "renamed", isDeleted: false }]);- expect(loadReferenceLinkTitle).toHaveBeenCalledWith(expect.anything(), href);+ expect(loadReferenceLinkTitle).toHaveBeenCalledWith(expect.anything(), href, "a");expect(getModelData(editor.model)).toBe(before);});@@ -272,11 +274,11 @@ describe("ReferenceLink", () => {});it("dataDowncasts a reference back to an anchor, resolving the title synchronously", () => {- editor.setData('<p><a class="reference-link" href="#root/noteAbc">old</a></p>');+ editor.setData('<p><a class="reference-link" href="#root/noteAbc"><span>old</span></a></p>');const data = editor.getData();- expect(getReferenceLinkTitleSync).toHaveBeenCalledWith("#root/noteAbc");+ expect(getReferenceLinkTitleSync).toHaveBeenCalledWith("#root/noteAbc", "old");expect(data).toContain('class="reference-link"');expect(data).toContain('href="#root/noteAbc"');expect(data).toContain("Some title");diff --git a/packages/ckeditor5/src/plugins/referencelink.ts b/packages/ckeditor5/src/plugins/referencelink.tsindex 0d1f4d844a..2ca136a745 100644--- a/packages/ckeditor5/src/plugins/referencelink.ts+++ b/packages/ckeditor5/src/plugins/referencelink.ts@@ -1,4 +1,4 @@-import { Command, ModelElement, ModelLivePosition, LinkEditing, Plugin, toWidget, viewToModelPositionOutsideModelElement, Widget } from "ckeditor5";+import { Command, ModelElement, ModelLivePosition, LinkEditing, Plugin, toWidget, ViewElement, viewToModelPositionOutsideModelElement, Widget } from "ckeditor5";export default class ReferenceLink extends Plugin {static get requires() {@@ -152,7 +152,8 @@ export class ReferenceLinkEditing extends Plugin {// The inline widget is self-contained, so it cannot be split by the caret, and it can be selected:isObject: true,- allowAttributes: [ 'href', 'uploadId', 'uploadStatus', 'uploadFileName' ]+ // `storedTitle` is the title the loaded content holds, shown when the note is missing.+ allowAttributes: [ 'href', 'storedTitle', 'uploadId', 'uploadStatus', 'uploadFileName' ]} );}@@ -167,8 +168,10 @@ export class ReferenceLinkEditing extends Plugin {},model: ( viewElement, { writer: modelWriter } ) => {const href = viewElement.getAttribute('href');+ const storedTitle = getText( viewElement );- return modelWriter.createElement( 'reference', { href } );+ return modelWriter.createElement( 'reference',+ storedTitle ? { href, storedTitle } : { href } );}} );@@ -177,6 +180,7 @@ export class ReferenceLinkEditing extends Plugin {model: { name: 'reference', attributes: [ 'href', 'uploadFileName' ] },view: ( modelItem, { writer: viewWriter } ) => {const href = modelItem.getAttribute('href') as string;+ const storedTitle = modelItem.getAttribute('storedTitle') as string | undefined;const uploadFileName = String(modelItem.getAttribute('uploadFileName') ?? '');const referenceLinkView = viewWriter.createContainerElement( 'a', {@@ -200,7 +204,7 @@ export class ReferenceLinkEditing extends Plugin {const editorEl = editor.editing.view.getDomRoot();const component = glob.getComponentByEl<EditorComponent>(editorEl);- component.loadReferenceLinkTitle($(domElement), href);+ component.loadReferenceLinkTitle($(domElement), href, storedTitle);return domElement;});@@ -222,7 +226,8 @@ export class ReferenceLinkEditing extends Plugin {class: 'reference-link'} );- const title = glob.getReferenceLinkTitleSync(href);+ const storedTitle = modelItem.getAttribute('storedTitle') as string | undefined;+ const title = glob.getReferenceLinkTitleSync(href, storedTitle);const innerText = viewWriter.createText(title);viewWriter.insert(viewWriter.createPositionAt(referenceLinkView, 0), innerText);@@ -233,6 +238,19 @@ export class ReferenceLinkEditing extends Plugin {}}+/** The text inside `element` and its descendants. */+function getText( element: ViewElement ): string {+ let text = '';+ for ( const child of element.getChildren() ) {+ if ( child.is( '$text' ) ) {+ text += child.data;+ } else if ( child.is( 'element' ) ) {+ text += getText( child );+ }+ }+ return text;+}+/** The attachment a reference link points to, or `null` for a link to a note. */export function getAttachmentId( href: unknown ) {const query = typeof href === 'string' ? href.split( '?' )[ 1 ] : undefined;