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): fix a reference link to a missing note from the add link dialog
Elian Dorana99cf3bfedba
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.tsindex 1026f4e89a..c1fd3239c7 100644--- a/apps/client/src/services/link.spec.ts+++ b/apps/client/src/services/link.spec.ts@@ -1054,7 +1054,7 @@ describe("loadReferenceLinkTitle", () => {getNote.mockRestore();expect($stored.text()).toBe("Deleted note");- expect($stored.hasClass("reference-link-missing")).toBe(true);+ expect($stored.is(".reference-link-missing.no-link-navigation")).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]");diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.tsindex f579db6ea6..d88f65073c 100644--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@ -703,7 +703,7 @@ async function loadReferenceLinkTitle(if (!note) {$el.text(storedTitle || MISSING_NOTE_TITLE)- .addClass("reference-link-missing")+ .addClass("reference-link-missing no-link-navigation").prepend($("<span>").addClass("tn-icon bx bx-x"));return;}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 81660184cf..3e08fbfc61 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -56,6 +56,7 @@"add_link": {"add_link": "Add link","edit_link": "Edit link",+ "fix_link": "Fix link","help_on_links": "Help on links","note": "Note","search_note": "search for note by its name",@@ -65,7 +66,8 @@"anchor": "Anchor (optional)","anchor_none": "None (link to note)","button_add_link": "Add link",- "button_edit_link": "Save link"+ "button_edit_link": "Save link",+ "button_fix_link": "Fix link"},"branch_prefix": {"edit_branch_prefix": "Edit branch prefix",diff --git a/apps/client/src/widgets/dialogs/add_link.tsx b/apps/client/src/widgets/dialogs/add_link.tsxindex cd9f726ffe..4db5f51bde 100644--- a/apps/client/src/widgets/dialogs/add_link.tsx+++ b/apps/client/src/widgets/dialogs/add_link.tsx@@ -54,6 +54,11 @@ export interface AddLinkOpts {* dialog says it is editing rather than adding, too.*/currentLink?: Suggestion;+ /**+ * Repoints a reference link to a missing note. The dialog is titled "Fix link", searches for+ * `text`, and offers only notes, always as a reference link.+ */+ fixLink?: boolean;addLink(notePath: string, linkTitle: string | null, externalLink?: boolean): Promise<void>;}@@ -186,15 +191,19 @@ export default function AddLinkDialog() {const autocompleteRef = useRef<HTMLInputElement>(null);const handleRef = useRef<NoteAutocompleteHandle>(null);+ const title = opts?.fixLink ? t("add_link.fix_link")+ : opts?.currentLink ? t("add_link.edit_link") : t("add_link.add_link");+ const buttonText = opts?.fixLink ? t("add_link.button_fix_link")+ : opts?.currentLink ? t("add_link.button_edit_link") : t("add_link.button_add_link");return (<ModalclassName="add-link-dialog"size="lg"maxWidth={1000}- title={opts?.currentLink ? t("add_link.edit_link") : t("add_link.add_link")}+ title={title}helpPageId="QEAPj01N5f7w"- footer={<Button text={opts?.currentLink ? t("add_link.button_edit_link") : t("add_link.button_add_link")} keyboardShortcut="Enter" />}+ footer={<Button text={buttonText} keyboardShortcut="Enter" />}onSubmit={onSubmit}onShown={onShown}onHidden={() => {@@ -228,7 +237,7 @@ export default function AddLinkDialog() {handleRef={handleRef}onChange={setSuggestion}opts={{- allowExternalLinks: true,+ allowExternalLinks: !opts?.fixLink,allowCreatingNotes: true}}/>@@ -249,7 +258,7 @@ export default function AddLinkDialog() {</FormGroup>)}- {!opts?.hasSelection && !opts?.targetOnly && (+ {!opts?.hasSelection && !opts?.targetOnly && !opts?.fixLink && (<div className="add-link-title-settings">{(linkType !== "external-link") && (<>diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 8751111d40..de29fd3e97 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -215,6 +215,16 @@ export default function EditableText({}});},+ fixReferenceLink(storedTitle: string, fix: (href: string) => void) {+ parentComponent?.triggerCommand("showAddLinkDialog", {+ text: storedTitle,+ hasSelection: false,+ fixLink: true,+ async addLink(notePath) {+ fix(`#${notePath}`);+ }+ });+ },pasteMarkdownIntoTextCommand() {if (!editorApiRef.current) return;parentComponent?.triggerCommand("showPasteMarkdownDialog", {diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.htmlindex 72aefc8035..f4e76b20e0 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.html@@ -23,6 +23,11 @@<li>The title of this link cannot be changed. Instead, it will always showthe current title of the linked note.</li><li>The icon of the linked note will also be displayed.</li>+ <li>If the linked note is deleted, the link keeps the last title it showed,+ in red and with a <span class="tn-icon bx bx-x"></span> icon instead of the+ note icon. Clicking it while editing opens the <em>Fix link</em> dialog,+ which searches for that title; picking a note, or creating a new one, replaces+ the link with one to that note.</li></ol></li><li><em>Link title can be changed arbitrarily</em>diff --git a/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.md b/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.mdindex 4893518de2..1a5da6217f 100644--- a/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.md+++ b/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.md@@ -16,6 +16,7 @@ There are two link types which you can select when creating the link to the note1. This is sometimes also called "reference link".2. The title of this link cannot be changed. Instead, it will always show the current title of the linked note.3. The icon of the linked note will also be displayed.+ 4. If the linked note is deleted, the link keeps the last title it showed, in red and with a <span class="tn-icon bx bx-x"></span> icon instead of the note icon. Clicking it while editing opens the _Fix link_ dialog, which searches for that title; picking a note, or creating a new one, replaces the link with one to that note.2. _Link title can be changed arbitrarily_1. This will create a traditional hyperlink, where the text of the link can be different from the note title.diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex aa010d256f..4e12d103cf 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -85,6 +85,11 @@ declare global {loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string, storedTitle?: string): Promise<void>;+ /**+ * Lets the user pick the note a reference link to a missing note should point at instead,+ * starting from `storedTitle`, and calls `fix()` with the new href.+ */+ fixReferenceLink?(storedTitle: string, fix: (href: string) => void): 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.diff --git a/packages/ckeditor5/src/plugins/referencelink.spec.ts b/packages/ckeditor5/src/plugins/referencelink.spec.tsindex 7bad5a6cbc..0722a6a160 100644--- a/packages/ckeditor5/src/plugins/referencelink.spec.ts+++ b/packages/ckeditor5/src/plugins/referencelink.spec.ts@@ -322,6 +322,59 @@ describe("ReferenceLink", () => {openSpy.mockRestore();});++ it("replaces the reference it is given with one to the new href, in one undo step", async () => {+ editor.setData('<p>a<a class="reference-link" href="#root/gone">Gone</a>b</p>');++ editor.execute("referenceLink", { href: "#root/noteNew", replace: findReference(editor) });+ await Promise.resolve();+ await Promise.resolve();++ expect(getModelData(editor.model, { withoutSelection: true }))+ .toBe('<paragraph>a<reference href="#root/noteNew"></reference>b</paragraph>');++ editor.execute("undo");++ expect(getModelData(editor.model, { withoutSelection: true }))+ .toBe('<paragraph>a<reference href="#root/gone" storedTitle="Gone"></reference>b</paragraph>');+ });++ it("asks to fix a reference to a missing note when it is clicked, and not one to a note", () => {+ const fixReferenceLink = vi.fn();+ // The test setup makes `$` a passthrough, so the title element arrives as itself.+ loadReferenceLinkTitle.mockImplementation(async (el: HTMLElement, href: string) => {+ el.classList.toggle("reference-link-missing", href === "#root/gone");+ });+ installGlobMock({+ getComponentByEl: () => ({ loadReferenceLinkTitle, fixReferenceLink }),+ getReferenceLinkTitle,+ getReferenceLinkTitleSync+ });+ editor.setData(+ '<p><a class="reference-link" href="#root/noteAbc">Fine</a>'+ + '<a class="reference-link" href="#root/gone">Gone</a></p>'+ );+ const titles = editor.editing.view.getDomRoot()?.querySelectorAll("a.reference-link > span");+ const click = (domTarget: Element | undefined) => editor.editing.view.document.fire("click", {+ domTarget,+ domEvent: {},+ preventDefault: () => {}+ });++ click(titles?.[0]);+ expect(fixReferenceLink).not.toHaveBeenCalled();++ click(titles?.[1]);+ expect(fixReferenceLink).toHaveBeenCalledTimes(1);+ expect(fixReferenceLink.mock.calls[0]?.[0]).toBe("Gone");++ const execute = vi.spyOn(editor, "execute");+ fixReferenceLink.mock.calls[0]?.[1]("#root/noteNew");+ expect(execute).toHaveBeenCalledWith("referenceLink", {+ href: "#root/noteNew",+ replace: findReference(editor)?.nextSibling+ });+ });});function findReference(editor: ClassicEditor) {diff --git a/packages/ckeditor5/src/plugins/referencelink.ts b/packages/ckeditor5/src/plugins/referencelink.tsindex 2ca136a745..e5e43ec3e2 100644--- a/packages/ckeditor5/src/plugins/referencelink.ts+++ b/packages/ckeditor5/src/plugins/referencelink.ts@@ -1,4 +1,7 @@-import { Command, ModelElement, ModelLivePosition, LinkEditing, Plugin, toWidget, ViewElement, viewToModelPositionOutsideModelElement, Widget } from "ckeditor5";+import {+ ClickObserver, Command, LinkEditing, ModelElement, ModelLivePosition, Plugin, toWidget,+ type ViewDocumentClickEvent, ViewElement, viewToModelPositionOutsideModelElement, Widget+} from "ckeditor5";export default class ReferenceLink extends Plugin {static get requires() {@@ -8,13 +11,33 @@ export default class ReferenceLink extends Plugin {class ReferenceLinkCommand extends Command {- override execute({ href }: { href: string }) {+ /**+ * Inserts a reference to `href` at the selection, or in place of the `replace` reference.+ */+ override execute({ href, replace }: { href: string; replace?: ModelElement }) {if (!href?.trim()) {return;}const editor = this.editor;+ if (replace) {+ glob.getReferenceLinkTitle(href).then(() => {+ const root = replace.root;+ if (!root.is('rootElement') || root.rootName === '$graveyard') {+ return;+ }++ editor.model.change(writer => {+ const reference = writer.createElement('reference', {href});+ writer.insert(reference, writer.createPositionBefore(replace));+ writer.remove(replace);+ writer.setSelection(reference, 'on');+ });+ });+ return;+ }+const selectionPosition = editor.model.document.selection.getFirstPosition();if (!selectionPosition) {return;@@ -138,6 +161,38 @@ export class ReferenceLinkEditing extends Plugin {// This works even if the link is not a reference link, since it is handled by Trilium.return true;});++ const view = this.editor.editing.view;+ view.addObserver( ClickObserver );+ this.listenTo<ViewDocumentClickEvent>( view.document, 'click', ( _evt, data ) => {+ this._fixMissingReference( data.domTarget );+ } );+ }++ /**+ * Asks the editor component to fix the reference link around `domTarget` when+ * `loadReferenceLinkTitle()` rendered it as one to a missing note.+ */+ private _fixMissingReference( domTarget: HTMLElement | undefined ) {+ const editor = this.editor;+ const anchor = domTarget?.closest<HTMLAnchorElement>( 'a.reference-link' );+ if ( editor.isReadOnly || !anchor?.querySelector( '.reference-link-missing' ) ) {+ return;+ }++ const viewElement = editor.editing.view.domConverter.mapDomToView( anchor );+ const reference = viewElement?.is( 'element' )+ ? editor.editing.mapper.toModelElement( viewElement )+ : undefined;+ if ( !reference?.is( 'element', 'reference' ) ) {+ return;+ }++ const component = glob.getComponentByEl<EditorComponent>( editor.editing.view.getDomRoot() );+ component?.fixReferenceLink?.( String( reference.getAttribute( 'storedTitle' ) ?? '' ), href => {+ editor.execute( 'referenceLink', { href, replace: reference } );+ editor.editing.view.focus();+ } );}_defineSchema() {