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
client/text editor/include notes: add "Convert to link" context menu item for embedded attachments
Adorian Dorand0c459de7318
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.tsindex 1f2827f4f4..95efe99bf1 100644--- a/apps/client/src/menus/link_context_menu.spec.ts+++ b/apps/client/src/menus/link_context_menu.spec.ts@@ -292,6 +292,77 @@ describe("openContextMenu", () => {expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(1);});+ describe("on the title of an attachment embed", () => {+ const execute = vi.fn();+ const selectIncludeAt = vi.fn();+ const convertCommand = { isEnabled: true };+ let hasPlugin = true;+ let editable: HTMLElement;++ beforeEach(() => {+ selectIncludeAt.mockReturnValue(true);+ convertCommand.isEnabled = true;+ hasPlugin = true;+ mocks.getAttachmentOfNote.mockResolvedValue({ attachmentId: "att-1" });+ mocks.getAttachmentActionGroups.mockReturnValue([+ [ { title: "Download", icon: "bx bx-download", run: vi.fn() } ]+ ]);+ mocks.getTextEditorContaining.mockResolvedValue({+ plugins: { has: () => hasPlugin, get: () => ({ selectIncludeAt }) },+ commands: {+ get: (name: string) => (name === "convertEmbedToLink"+ ? convertCommand+ : undefined)+ },+ execute+ });+ editable = document.createElement("div");+ editable.className = "ck-editor__editable";+ editable.setAttribute("contenteditable", "true");+ editable.innerHTML = `<section class="include-note"><h4 class="include-note-title">`+ + `<span><a href="#">report.pdf</a></span></h4></section>`;+ });++ async function openOnTitle() {+ const link = editable.querySelector("a") ?? undefined;+ await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(link), VIEW_SCOPE);+ return mocks.show.mock.lastCall?.[0].items;+ }++ it("ends the menu with converting the embed to a link, selecting it first", async () => {+ const items = await openOnTitle();++ const title = editable.querySelector(".include-note-title");+ expect(selectIncludeAt).toHaveBeenCalledWith(title);+ expect(items.slice(4)).toMatchObject([+ { kind: "separator" },+ { title: "Download" },+ { title: "link_context_menu.convert_embed_to_link", uiIcon: "bx bx-link" }+ ]);+ items.at(-1).handler();+ expect(execute).toHaveBeenCalledWith("convertEmbedToLink");+ });++ it("leaves it out in a read-only note, or for an embed it cannot convert", async () => {+ hasPlugin = false;+ expect(await openOnTitle()).toHaveLength(6);+ expect(selectIncludeAt).not.toHaveBeenCalled();++ hasPlugin = true;+ selectIncludeAt.mockReturnValue(false);+ expect(await openOnTitle()).toHaveLength(6);++ selectIncludeAt.mockReturnValue(true);+ convertCommand.isEnabled = false;+ expect(await openOnTitle()).toHaveLength(6);++ convertCommand.isEnabled = true;+ editable.removeAttribute("contenteditable");+ expect(await openOnTitle()).toHaveLength(6);+ expect(mocks.getTextEditorContaining).toHaveBeenCalledTimes(3);+ });+ });+it("adds nothing for a link to a note, or to an attachment that no longer exists", async () => {await linkContextMenu.openContextMenu("root/n1", contextMenuEvent());expect(mocks.getAttachmentOfNote).not.toHaveBeenCalled();diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.tsindex 82ffb374e7..7a0e9558c0 100644--- a/apps/client/src/menus/link_context_menu.ts+++ b/apps/client/src/menus/link_context_menu.ts@@ -108,10 +108,11 @@ async function getAttachmentItems(}// Imported on demand: `attachment_actions` imports `link`, which imports this module.- const [ attachment, { getAttachmentActionGroups }, embedItem ] = await Promise.all([+ const [ attachment, { getAttachmentActionGroups }, embedItem, linkItem ] = await Promise.all([froca.getAttachmentOfNote(noteId, attachmentId),import("../services/attachment_actions.js"),- getConvertToEmbedItem(e)+ getConvertToEmbedItem(e),+ getConvertToLinkItem(e)]);if (!attachment) {return [];@@ -128,7 +129,8 @@ async function getAttachmentItems(}))]);- return embedItem ? [ ...actionItems, embedItem ] : actionItems;+ const conversionItems = [ embedItem, linkItem ].filter((item) => item !== null);+ return [ ...actionItems, ...conversionItems ];}/** "Convert link to an embed", for an attachment link in a text note open for editing. */@@ -136,13 +138,8 @@ async function getConvertToEmbedItem(e: ContextMenuEvent): Promise<MenuItem<Commconst link = e.target instanceof Element? e.target.closest<HTMLElement>("a.reference-link"): null;- // Checked first: a note shown read-only has no editor, and asking for one waits for a timeout.- if (!link?.closest(".ck-editor__editable[contenteditable='true']")) {- return null;- }-- const editor = await getTextEditorContaining(link);- if (!editor?.commands.get("embedAttachmentLink")?.isEnabled) {+ const editor = await getEditingTextEditor(link);+ if (!link || !editor?.commands.get("embedAttachmentLink")?.isEnabled) {return null;}@@ -156,6 +153,36 @@ async function getConvertToEmbedItem(e: ContextMenuEvent): Promise<MenuItem<Comm};}+/** "Convert to link", for the title of an attachment embed in a text note open for editing. */+async function getConvertToLinkItem(e: ContextMenuEvent): Promise<MenuItem<CommandNames> | null> {+ const title = e.target instanceof Element+ ? e.target.closest<HTMLElement>(".include-note-title")+ : null;+ const editor = await getEditingTextEditor(title);+ // `convertEmbedToLink` acts on the selected embed, so the right-clicked one is selected first.+ if (!title || !editor?.plugins.has("IncludeNote")+ || !editor.plugins.get("IncludeNote").selectIncludeAt(title)+ || !editor.commands.get("convertEmbedToLink")?.isEnabled) {+ return null;+ }++ return {+ title: t("link_context_menu.convert_embed_to_link"),+ uiIcon: "bx bx-link",+ handler: () => editor.execute("convertEmbedToLink")+ };+}++/** The text editor containing `element`, or `null` when there is none or it is read-only. */+async function getEditingTextEditor(element: Element | null) {+ // Checked first: a note shown read-only has no editor, and asking for one waits for a timeout.+ if (!element?.closest(".ck-editor__editable[contenteditable='true']")) {+ return null;+ }++ return getTextEditorContaining(element);+}+function getNtxId(e: ContextMenuEvent | GeoMouseEvent) {if (utils.isDesktop()) {const subContexts = appContext.tabManager.getActiveContext()?.getSubContexts();diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 0a45c517ae..50076e7b86 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3058,7 +3058,8 @@"open_note_in_other_split": "Open note in the other split","open_note_in_new_window": "Open note in a new window","open_note_in_popup": "Quick edit",- "convert_link_to_embed": "Convert link to an embed"+ "convert_link_to_embed": "Convert link to an embed",+ "convert_embed_to_link": "Convert to link"},"electron_integration": {"desktop-application": "Desktop Application",diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.htmlindex 8f228b41d3..e518f23fae 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html@@ -78,7 +78,8 @@<li>An embed takes the default box size of included notes. To change its size,select the embed and use the box size menu in its toolbar.</li><li>To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span> <em>Convert to link</em> button- in its toolbar.</li>+ in its toolbar, or right-click its title and select <em>Convert to link</em>,+ at the end of the menu.</li></ul><p>An embed follows its attachment like a link does. Converting the attachmentinto a note turns the embed into an included note. In a <a href="#root/_help_R9pX4DGra2Vt">shared note</a>,diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.mdindex a30f0afaf0..d45f818528 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md@@ -42,7 +42,7 @@ An attachment can be shown in the text instead of linked, the way <a class="ref* To attach files and embed them straight away, select _Attach and embed file_ from the arrow beside the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. Each file gets an embed of its own, which shows the file name while the file uploads.* To embed an attachment that is already linked, right-click a link to it in a text note being edited and select _Convert link to an embed_, at the end of the menu.* An embed takes the default box size of included notes. To change its size, select the embed and use the box size menu in its toolbar.-* To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span> _Convert to link_ button in its toolbar.+* To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span> _Convert to link_ button in its toolbar, or right-click its title and select _Convert to link_, at the end of the menu.An embed follows its attachment like a link does. Converting the attachment into a note turns the embed into an included note. In a [shared note](../../Advanced%20Usage/Sharing.md), an embedded picture is displayed, and any other attachment appears as a link to download it.diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 041f63b417..991a45e95f 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -28,6 +28,7 @@ export * from "./utils.js";// Import with sideffects to ensure that type augmentations are present.import "./plugins/file_upload/uploadfileplugin.js";+import "./plugins/includenote.js";import "./plugins/math/math.js";import "./plugins/mermaid/mermaid.js";import "./plugins/referencelink.js";diff --git a/packages/ckeditor5/src/plugins/includenote.spec.ts b/packages/ckeditor5/src/plugins/includenote.spec.tsindex eea7e2589e..9b08b4e3a7 100644--- a/packages/ckeditor5/src/plugins/includenote.spec.ts+++ b/packages/ckeditor5/src/plugins/includenote.spec.ts@@ -479,6 +479,28 @@ describe("IncludeNote", () => {}).not.toThrow();});+ it("selects the include that a DOM element is part of, for a context menu opened on it", () => {+ editor.setData("<p>foo</p>"+ + "<section class=\"include-note\" data-note-id=\"noteMenu\" data-box-size=\"small\">"+ + "</section>");+ const domRoot = editor.editing.view.getDomRoot();+ const wrapper = domRoot?.querySelector("div.include-note-wrapper");+ const paragraph = domRoot?.querySelector("p");+ if (!wrapper || !paragraph) {+ throw new Error("Expected a rendered include and paragraph.");+ }+ const title = document.createElement("h4");+ wrapper.append(title);+ const plugin = editor.plugins.get("IncludeNote");++ expect(plugin.selectIncludeAt(paragraph)).toBe(false);+ expect(editor.model.document.selection.getSelectedElement()).toBeNull();++ expect(plugin.selectIncludeAt(title)).toBe(true);+ expect(editor.model.document.selection.getSelectedElement()?.getAttribute("noteId"))+ .toBe("noteMenu");+ });+it("falls back gracefully in the button factory when the insert command is absent", () => {// Exercise the falsy `if (command)` branch in IncludeNoteUI: when the command lookup// returns undefined, the button must still be created (just without the binding).diff --git a/packages/ckeditor5/src/plugins/includenote.ts b/packages/ckeditor5/src/plugins/includenote.tsindex bb8ff5da1f..fc5f713ade 100644--- a/packages/ckeditor5/src/plugins/includenote.ts+++ b/packages/ckeditor5/src/plugins/includenote.ts@@ -51,6 +51,27 @@ export default class IncludeNote extends Plugin {static get requires() {return [ IncludeNoteEditing, IncludeNoteUI ];}++ static get pluginName() {+ return 'IncludeNote' as const;+ }++ /**+ * Selects the include that `domElement` is part of, so that commands act on the include a+ * context menu is opened on. Returns `false` when `domElement` is not part of an include of+ * this editor.+ */+ selectIncludeAt( domElement: Element ): boolean {+ const include = getIncludeNoteAt( this.editor, domElement );+ if ( !include ) {+ return false;+ }++ this.editor.model.enqueueChange( { isUndoable: false }, writer => {+ writer.setSelection( include, 'on' );+ } );+ return true;+ }}class IncludeNoteUI extends Plugin {@@ -374,6 +395,18 @@ function getSelectedIncludeNote( editor: Editor ) {return selection.getFirstPosition()?.findAncestor( 'includeNote' ) ?? null;}+/** The include whose rendering contains `domElement`, or `null`. */+function getIncludeNoteAt( editor: Editor, domElement: Element ) {+ const sectionElement = domElement.closest<HTMLElement>( 'section.include-note' );+ const viewElement = sectionElement+ && editor.editing.view.domConverter.mapDomToView( sectionElement );+ if ( !viewElement?.is( 'element' ) ) {+ return null;+ }++ return editor.editing.mapper.toModelElement( viewElement ) ?? null;+}+/*** The `data-*` attribute naming what an include shows: an attachment, or a note. An embed whose* upload has not ended names nothing.@@ -512,20 +545,7 @@ function isInteractiveTarget( target: EventTarget | null, boundary: HTMLElement}function selectIncludeNoteWidget( domElement: HTMLElement, editor: Editor ) {- // Find the parent section element (the widget container)- const sectionElement = domElement.closest( 'section.include-note' ) as HTMLElement | null;- if ( !sectionElement ) {- return;- }-- // Get the view element from the DOM element- const viewElement = editor.editing.view.domConverter.mapDomToView( sectionElement );- if ( !viewElement || !viewElement.is( 'element' ) ) {- return;- }-- // Get the model element from the view element- const modelElement = editor.editing.mapper.toModelElement( viewElement );+ const modelElement = getIncludeNoteAt( editor, domElement );if ( !modelElement ) {return;}@@ -538,3 +558,9 @@ function selectIncludeNoteWidget( domElement: HTMLElement, editor: Editor ) {writer.setSelection( modelElement, 'on' );} );}++declare module 'ckeditor5' {+ interface PluginsMap {+ [ IncludeNote.pluginName ]: IncludeNote;+ }+}