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: show a preview tooltip over attachment links
Adorian Doran3d4d22a009ef
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.tsindex 36649e1057..b87ab9fe2b 100644--- a/apps/client/src/services/content_renderer.spec.ts+++ b/apps/client/src/services/content_renderer.spec.ts@@ -1,3 +1,4 @@+import { attachmentIcon } from "@triliumnext/commons";import { h, VNode } from "preact";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -547,6 +548,21 @@ describe("generic FNote fallback / webView", () => {expect($renderedContent.find("span").length).toBeGreaterThan(0);});+ it("gives an attachment without a preview its own icon, as a note gets", async () => {+ const pdf = buildAttachment({ role: "file", mime: "application/pdf" });+ const library = buildAttachment({ role: "canvasLibraryItem", mime: "application/json" });++ const cases = [ [ pdf, { tooltip: true } ], [ library, {} ] ] as const;++ for (const [ attachment, options ] of cases) {+ const { $renderedContent } = await getRenderedContent(attachment, options);++ expect($renderedContent.hasClass("no-preview")).toBe(true);+ expect($renderedContent.find("span").attr("class"))+ .toBe(attachmentIcon(attachment.role, attachment.mime));+ }+ });+it("renders a webView footer that opens in a new window when not in electron", async () => {const note = buildNote({ title: "W", type: "webView", "#webViewSrc": "https://example.com" });const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);@@ -800,13 +816,13 @@ describe("getRenderingType detection", () => {expect((await getRenderedContent(att)).type).toBe("file");});- it("returns the raw role for an attachment with an unhandled role (no rendering branch)", async () => {+ it("returns the raw role of an attachment with no branch, drawn as an icon", async () => {const att = buildAttachment({ role: "unknownRole" });const { type, $renderedContent } = await getRenderedContent(att);expect(type).toBe("unknownRole");- // attachment falls through to the final `entity instanceof FNote` check (false) -> empty content- expect($renderedContent.hasClass("no-preview")).toBe(false);- expect($renderedContent.children().length).toBe(0);+ expect($renderedContent.hasClass("no-preview")).toBe(true);+ expect($renderedContent.find("span").attr("class"))+ .toBe(attachmentIcon(att.role, att.mime));});it("maps json file notes to code unless tagged as an icon pack", async () => {diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 5fd15c3d59..95743bd9c5 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -1,6 +1,12 @@import "./content_renderer.css";-import { isImageAttachmentRole, isOfficeMimeType, normalizeMimeTypeForCKEditor, type TextRepresentationResponse } from "@triliumnext/commons";+import {+ attachmentIcon,+ isImageAttachmentRole,+ isOfficeMimeType,+ normalizeMimeTypeForCKEditor,+ type TextRepresentationResponse+} from "@triliumnext/commons";import DOMPurify from "dompurify";import { h, type JSX, render } from "preact";@@ -132,13 +138,16 @@ export async function getRenderedContent(this: {} | { ctx: string }, entity: FNoawait renderWebView(entity, $renderedContent);} else if (type === "llmChat" && entity instanceof FNote) {await renderLlmChat(entity, $renderedContent, options);- } else if (entity instanceof FNote) {+ } else if (entity instanceof FNote || entity instanceof FAttachment) {+ const icon = entity instanceof FNote+ ? entity.getIcon()+ : attachmentIcon(entity.role, entity.mime);$renderedContent.addClass("no-preview");$renderedContent.append(- $("<div>").append($("<span>").addClass(entity.getIcon()))+ $("<div>").append($("<span>").addClass(icon)));- if (entity.type === "webView" && entity.hasLabel("webViewSrc")) {+ if (entity instanceof FNote && entity.type === "webView" && entity.hasLabel("webViewSrc")) {const $footer = $("<footer>").addClass("webview-footer");const $openButton = $(`diff --git a/apps/client/src/services/note_tooltip.spec.ts b/apps/client/src/services/note_tooltip.spec.tsindex 9eee07fbee..19adbe4a75 100644--- a/apps/client/src/services/note_tooltip.spec.ts+++ b/apps/client/src/services/note_tooltip.spec.ts@@ -3,12 +3,20 @@ import $ from "jquery";// --- Mocks (hoisted above imports) ----const { parseNavigationStateFromUrl, renderNormalAttributes, getRenderedContent, getNoteTitleWithPathAsSuffix, getActiveContext } = vi.hoisted(() => ({+const {+ parseNavigationStateFromUrl,+ renderNormalAttributes,+ getRenderedContent,+ getNoteTitleWithPathAsSuffix,+ getActiveContext,+ t+} = vi.hoisted(() => ({parseNavigationStateFromUrl: vi.fn(),renderNormalAttributes: vi.fn(),getRenderedContent: vi.fn(),getNoteTitleWithPathAsSuffix: vi.fn(),- getActiveContext: vi.fn()+ getActiveContext: vi.fn(),+ t: vi.fn((key: string) => key)}));vi.mock("./link.js", () => ({@@ -31,9 +39,7 @@ vi.mock("../components/app_context.js", () => ({default: { tabManager: { getActiveContext } }}));-vi.mock("./i18n.js", () => ({- t: (key: string) => key-}));+vi.mock("./i18n.js", () => ({ t }));// Imports AFTER vi.mock calls.import DeletedFNote from "../entities/deleted_fnote.js";@@ -294,6 +300,34 @@ describe("renderTooltip", () => {expect(html).toContain('class="note-tooltip-attributes"');expect(html).toContain("body");});++ it("renders an attachment under its note's path, without the note's attributes", async () => {+ const owner = fakeNote({ noteId: "owner", bestPath: "root/owner" });+ const attachment = {+ attachmentId: "att1",+ ownerId: "owner",+ title: "report.pdf",+ contentLength: 21_590_000,+ getNote: () => owner+ } as any;+ const href = "#owner?viewMode=attachments&attachmentId=att1";++ const $html = $(`<div>${await renderTooltip(attachment)}</div>`);++ expect(getNoteTitleWithPathAsSuffix).toHaveBeenCalledWith("root/owner", "report.pdf");+ expect(getRenderedContent).toHaveBeenCalledWith(attachment, { tooltip: true, trim: true });+ expect($html.find("h5.note-tooltip-title a").attr("href")).toBe(href);+ expect($html.find(".content").text()).toBe("body");+ expect(renderNormalAttributes).not.toHaveBeenCalled();+ expect($html.find(".note-tooltip-attributes")).toHaveLength(0);+ expect($html.find("a.open-popup-button").attr("href")).toBe(`${href}&popup`);++ // The info line names what it is and its size, unless the link supplies a detail itself.+ expect($html.find(".note-tooltip-detail").text()).toBe("note_tooltip.attachment-info");+ expect(t).toHaveBeenCalledWith("note_tooltip.attachment-info", { size: "20.59 MiB" });+ const $withDetail = $(`<div>${await renderTooltip(attachment, "From the link")}</div>`);+ expect($withDetail.find(".note-tooltip-detail").text()).toBe("From the link");+ });});describe("mouseEnterHandler", () => {@@ -410,6 +444,34 @@ describe("mouseEnterHandler", () => {expect(froca.getNote).not.toHaveBeenCalled();});+ it("previews the attachment an attachment link points to, rather than its note", async () => {+ vi.useFakeTimers();+ froca.getNote = vi.fn(async () => null) as any;+ froca.getAttachment = vi.fn(async () => ({+ attachmentId: "att1",+ ownerId: "owner",+ title: "report.pdf",+ getNote: () => fakeNote({ noteId: "owner", bestPath: "root/owner" })+ })) as any;+ const href = "#root/owner?viewMode=attachments&attachmentId=att1";+ const $link = makeLink(`<a href="${href}">x</a>`);+ parseNavigationStateFromUrl.mockReturnValue({+ notePath: "root/owner",+ noteId: "owner",+ viewScope: { viewMode: "attachments", attachmentId: "att1" }+ });+ hoverActive = true;++ const promise = mouseEnterHandler.call($link[0], eventFor($link));+ await vi.advanceTimersByTimeAsync(600);+ await promise;++ expect(froca.getAttachment).toHaveBeenCalledWith("att1", true);+ expect(froca.getNote).not.toHaveBeenCalled();+ const [ options ] = ($.fn.tooltip as unknown as ReturnType<typeof vi.fn>).mock.calls[0];+ expect(options.title).toContain("attachmentId=att1");+ });+it("routes ordinary note links through froca, not the deleted-content route", async () => {vi.useFakeTimers();const loadSpy = vi.spyOn(DeletedFNote, "load").mockResolvedValue(null);diff --git a/apps/client/src/services/note_tooltip.ts b/apps/client/src/services/note_tooltip.tsindex 0ced0d770a..154a1a5689 100644--- a/apps/client/src/services/note_tooltip.ts+++ b/apps/client/src/services/note_tooltip.ts@@ -1,4 +1,5 @@import appContext from "../components/app_context.js";+import type FAttachment from "../entities/fattachment.js";import type FNote from "../entities/fnote.js";import attributeRenderer from "./attribute_renderer.js";import contentRenderer from "./content_renderer.js";@@ -73,7 +74,8 @@ export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.Triggerereturn;}- if (!notePath || !noteId || viewScope?.viewMode !== "default") {+ const attachmentId = viewScope?.viewMode === "attachments" ? viewScope.attachmentId : undefined;+ if (!notePath || !noteId || (viewScope?.viewMode !== "default" && !attachmentId)) {return;}@@ -96,6 +98,8 @@ export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.Triggere// note tooltip rather than being fed into a jQuery selector (the `?` is an invalid selector).if (url && url.startsWith("#") && !url.startsWith("#root/") && !url.includes("?")) {renderPromise = renderFootnoteOrAnchor($link, url);+ } else if (attachmentId) {+ renderPromise = renderTooltip(await froca.getAttachment(attachmentId, true), detail);} else if ($link.attr("data-note-deleted") != null) {// The element explicitly targets a soft-deleted note (e.g. an entry in the deleted-notes// dialog): read it via the deleted-content route. `DeletedFNote.load` returns null once the@@ -183,12 +187,15 @@ export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.Triggere}/**+ * @param entity the note, or an attachment, which shows under the path of the note that owns it.* @param detail plain text the trigger element contributed about this note (see the `data-tooltip-detail`* attribute), shown under the title. Absent on the vast majority of links, which say* nothing beyond the note itself.*/-export async function renderTooltip(note: FNote | null, detail?: string) {- if (!note) {+export async function renderTooltip(entity: FNote | FAttachment | null, detail?: string) {+ const attachment = entity && "attachmentId" in entity ? entity : null;+ const note = attachment ? attachment.getNote() : entity as FNote | null;+ if (!entity || !note) {return `<div>${t("note_tooltip.note-has-been-deleted")}</div>`;}@@ -204,9 +211,16 @@ export async function renderTooltip(note: FNote | null, detail?: string) {return;}- const { $renderedAttributes } = await attributeRenderer.renderNormalAttributes(note);+ const href = attachment+ ? `#${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}`+ : `#${note.noteId}`;- const { $renderedContent } = await contentRenderer.getRenderedContent(note, {+ // An attachment has no attributes, and those of its note describe the note.+ const $renderedAttributes = attachment+ ? null+ : (await attributeRenderer.renderNormalAttributes(note)).$renderedAttributes;++ const { $renderedContent } = await contentRenderer.getRenderedContent(entity, {tooltip: true,trim: true});@@ -222,27 +236,40 @@ export async function renderTooltip(note: FNote | null, detail?: string) {// Plain, unlinked title — there is no live note to navigate to.content = `<h5 class="${titleClasses.join(" ")}">${utils.escapeHtml(note.title)}</h5>`;} else if (bestNotePath) {- const noteTitleWithPathAsSuffix = await treeService.getNoteTitleWithPathAsSuffix(bestNotePath);+ const noteTitleWithPathAsSuffix = await treeService.getNoteTitleWithPathAsSuffix(+ bestNotePath,+ attachment?.title+ );if (noteTitleWithPathAsSuffix) {+ const titleHtml = noteTitleWithPathAsSuffix.prop("outerHTML");content = `\<h5 class="${titleClasses.join(" ")}">- <a href="#${note.noteId}" data-no-context-menu="true">${noteTitleWithPathAsSuffix.prop("outerHTML")}</a>+ <a href="${href}" data-no-context-menu="true">${titleHtml}</a></h5>`;}}- if (detail) {- content = `${content}<div class="note-tooltip-detail">${utils.escapeHtml(detail)}</div>`;+ const info = detail ?? (attachment+ ? t("note_tooltip.attachment-info", { size: utils.formatSize(attachment.contentLength) })+ : undefined);+ if (info) {+ content = `${content}<div class="note-tooltip-detail">${utils.escapeHtml(info)}</div>`;}- content = `${content}<div class="note-tooltip-attributes">${$renderedAttributes[0].outerHTML}</div>`;+ if ($renderedAttributes) {+ const attributesHtml = $renderedAttributes[0].outerHTML;+ content = `${content}<div class="note-tooltip-attributes">${attributesHtml}</div>`;+ }if (!isContentEmpty) {content += $renderedContent[0].outerHTML;}// The quick-edit (popup) button opens the live editor, which doesn't apply to a deleted note.if (!isDeleted) {- content += `<a class="open-popup-button" title="${t("note_tooltip.quick-edit")}" href="#${note.noteId}?popup"><span class="bx bx-edit" /></a>`;+ const popupHref = attachment ? `${href}&popup` : `${href}?popup`;+ const quickEdit = t("note_tooltip.quick-edit");+ content += `<a class="open-popup-button" title="${quickEdit}" href="${popupHref}">`+ + `<span class="bx bx-edit" /></a>`;}return content;}diff --git a/apps/client/src/services/tree.spec.ts b/apps/client/src/services/tree.spec.tsindex 831e80886a..21ed1040bd 100644--- a/apps/client/src/services/tree.spec.ts+++ b/apps/client/src/services/tree.spec.ts@@ -234,6 +234,18 @@ describe("getNotePathTitleComponents / getNotePathTitle / getNoteTitleWithPathAsexpect($result.find(".note-path").text()).toContain("Alpha2");});+ it("shows a given title with the whole path as its suffix, for what a note owns", async () => {+ const a = buildNote({ title: "Alpha3" });+ const b = buildNote({ title: "Beta3" });++ const notePath = `${a.noteId}/${b.noteId}`;+ const $result = await treeService+ .getNoteTitleWithPathAsSuffix(notePath, "report.pdf") as JQuery<HTMLElement>;++ expect($result.find(".note-title").text()).toBe("report.pdf");+ expect($result.find(".note-path").text()).toBe(" (Alpha3 / Beta3)");+ });+// The empty-components guard inside getNoteTitleWithPathAsSuffix is unreachable through the// public API: getNotePathTitleComponents always pushes at least one component (the loop runs// for "" via split("/") -> [""]), and the internal call is to the local function (not thediff --git a/apps/client/src/services/tree.ts b/apps/client/src/services/tree.tsindex 0e2e49fff7..c92abe0a13 100644--- a/apps/client/src/services/tree.ts+++ b/apps/client/src/services/tree.ts@@ -255,7 +255,11 @@ async function getNotePathTitle(notePath: string) {return titlePath.join(NOTE_PATH_TITLE_SEPARATOR);}-async function getNoteTitleWithPathAsSuffix(notePath: string) {+/**+ * @param ownedTitle the title of something the note owns, such as an attachment. When set, it is+ * shown as the title and the whole of `notePath` becomes the suffix.+ */+async function getNoteTitleWithPathAsSuffix(notePath: string, ownedTitle?: string) {utils.assertArguments(notePath);const titleComponents = await getNotePathTitleComponents(notePath);@@ -265,8 +269,10 @@ async function getNoteTitleWithPathAsSuffix(notePath: string) {return "";}- const title = titleComponents[titleComponents.length - 1];- const path = titleComponents.slice(0, titleComponents.length - 1);+ const title = ownedTitle ?? titleComponents[titleComponents.length - 1];+ const path = ownedTitle+ ? titleComponents+ : titleComponents.slice(0, titleComponents.length - 1);const $titleWithPath = $('<span class="note-title-with-path">').append($('<span class="note-title">').text(title));diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 5ac240e2b8..e89631dc82 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3077,7 +3077,8 @@},"note_tooltip": {"note-has-been-deleted": "Note has been deleted.",- "quick-edit": "Quick edit"+ "quick-edit": "Quick edit",+ "attachment-info": "Attachment • {{size}}"},"geo-map": {"expand-details": "Expand the note to fill the map",diff --git a/apps/server/internal.openapi.yaml b/apps/server/internal.openapi.yamlindex 1fd5309b9f..5160ce4a3d 100644--- a/apps/server/internal.openapi.yaml+++ b/apps/server/internal.openapi.yaml@@ -1405,14 +1405,13 @@ paths:operationId: uploadAttachmentparameters:- $ref: '#/components/parameters/noteId'- - name: role+ - name: linkin: querydescription: >-- `file` stores a picture as a file attachment and answers with a link to it, instead of- an image URL.+ `true` answers with a link to the attachment instead of an image URL, and stores a+ picture as uploaded, without compressing it or shortening its name.schema:- type: string- enum: [file]+ type: booleanrequestBody:required: truecontent: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 7019ab6096..540ec05ad0 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@@ -45,9 +45,10 @@at the cursor. Several files produce several links, separated by a space.</li><li>While a file uploads, its link shows the file name and a toast shows theprogress.</li>- <li>Pictures are attached as files too, so they appear as links rather than- images. To display a picture in the text, use the image upload button instead- (see <a class="reference-link" href="#root/_help_mT0HEkOsz6i1">Images</a>).</li>+ <li>Pictures appear as links rather than images, and are attached exactly+ as they are, without being compressed. To display a picture in the text,+ use the image upload button instead (see <a class="reference-link"+ href="#root/_help_mT0HEkOsz6i1">Images</a>).</li></ul><p>Dragging a file that is not a picture from the file explorer onto thetext also attaches it and inserts a link to it.</p>diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tooltip.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tooltip.htmlindex 3500d61342..3315a9a6ba 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tooltip.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tooltip.html@@ -19,6 +19,11 @@<li>A button to <a href="#root/_help_ZjLYv08Rp3qC">quickly edit</a> the notein a popup.</li></ul>+<p>For a link to an <a href="#root/_help_0vhv7lsOLy82">attachment</a>, the+ tooltip shows the attachment instead: its title after the path of the note+ that owns it, a line giving its size (for example <em>Attachment • 20.59 MiB</em>),+ a preview of its content where one is available, and the quick edit button+ opening the attachment.</p><p>The tooltip can be found in multiple places, including:</p><ul><li>In <a class="reference-link" href="#root/_help_iPIMuisry3hd">Text</a> notes,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 597b23034b..35e3e63a95 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@@ -25,7 +25,7 @@ To attach files to a <a class="reference-link" href="../../Note%20Types/Text.md* Each file becomes an attachment of the note, and a link to it is inserted at the cursor. Several files produce several links, separated by a space.* While a file uploads, its link shows the file name and a toast shows the progress.-* Pictures are attached as files too, so they appear as links rather than images. To display a picture in the text, use the image upload button instead (see <a class="reference-link" href="../../Note%20Types/Text/Images.md">Images</a>).+* Pictures appear as links rather than images, and are attached exactly as they are, without being compressed. To display a picture in the text, use the image upload button instead (see <a class="reference-link" href="../../Note%20Types/Text/Images.md">Images</a>).Dragging a file that is not a picture from the file explorer onto the text also attaches it and inserts a link to it.diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tooltip.md b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tooltip.mdindex dc0c702cda..ebf6a175b2 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tooltip.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tooltip.md@@ -12,6 +12,8 @@ The following information is displayed:* A snippet of the content will be displayed as well.* A button to [quickly edit](../Navigation/Quick%20edit.md) the note in a popup.+For a link to an [attachment](../Notes/Attachments.md), the tooltip shows the attachment instead: its title after the path of the note that owns it, a line giving its size (for example _Attachment • 20.59 MiB_), a preview of its content where one is available, and the quick edit button opening the attachment.+The tooltip can be found in multiple places, including:* In <a class="reference-link" href="../../Note%20Types/Text.md">Text</a> notes, when hovering over <a class="reference-link" href="../../Note%20Types/Text/Links/Internal%20(reference)%20links.md">Internal (reference) links</a> .diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.tsindex 2df3ed2ad6..65fd9438eb 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts@@ -14,7 +14,7 @@ import {import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";-import { isFileAttachmentUpload } from "../uploadimage.js";+import { isUploadAsLink } from "../uploadimage.js";import FileUploadCommand from "./fileuploadcommand.js";/**@@ -142,7 +142,7 @@ describe("FileUploadCommand", () => {));});- it("marks the loader of every file as a file attachment upload", () => {+ it("marks the loader of every file to upload as a link", () => {setModelData(editor.model, "<paragraph>[]</paragraph>");const createLoaderSpy = vi.spyOn(editor.plugins.get(FileRepository), "createLoader");@@ -154,7 +154,7 @@ describe("FileUploadCommand", () => {expect(createLoaderSpy.mock.calls).toEqual([ [ files[0] ], [ files[1] ] ]);for (const { value } of createLoaderSpy.mock.results) {- expect(isFileAttachmentUpload(value as FileLoader)).toBe(true);+ expect(isUploadAsLink(value as FileLoader)).toBe(true);}});diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.tsindex 84add026fa..42b468e7aa 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts@@ -1,6 +1,6 @@import { Command, FileRepository, type Model, type ModelWriter } from "ckeditor5";-import { uploadAsFileAttachment } from "../uploadimage.js";+import { uploadAsLink } from "../uploadimage.js";export interface FileUploadOptions {file: File[];@@ -8,7 +8,7 @@ export interface FileUploadOptions {/*** Uploads files as attachments of the note and inserts a reference link to each, separated by- * spaces. Pictures become file attachments too, so they are linked rather than shown.+ * spaces. Pictures are linked too, rather than shown.*/export default class FileUploadCommand extends Command {override refresh() {@@ -30,7 +30,7 @@ export default class FileUploadCommand extends Command {continue;}- uploadAsFileAttachment(loader);+ uploadAsLink(loader);insertPlaceholder(writer, model, loader.id, file.name);}});diff --git a/packages/ckeditor5/src/plugins/uploadimage.spec.ts b/packages/ckeditor5/src/plugins/uploadimage.spec.tsindex 26363bc66d..44c6e65e23 100644--- a/packages/ckeditor5/src/plugins/uploadimage.spec.ts+++ b/packages/ckeditor5/src/plugins/uploadimage.spec.ts@@ -4,8 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";import { installGlobMock } from "../../test/globals-test-kit.js";import UploadimagePlugin, {- isFileAttachmentUpload,- uploadAsFileAttachment+ isUploadAsLink,+ uploadAsLink} from "./uploadimage.js";/**@@ -161,14 +161,14 @@ describe("UploadimagePlugin", () => {await expect(uploadPromise).resolves.toEqual({ default: "http://example.com/pic.png" });});- it("asks for a file attachment only for a loader marked as one", async () => {+ it("asks for a link only for a loader marked to upload as one", async () => {const fileRepository = editor.plugins.get(FileRepository);const marked = createFakeLoader(new File(["content"], "pic.png", { type: "image/png" }));- uploadAsFileAttachment(marked);- expect(isFileAttachmentUpload(marked)).toBe(true);+ uploadAsLink(marked);+ expect(isUploadAsLink(marked)).toBe(true);void fileRepository.createUploadAdapter?.(marked).upload();- expect((await awaitSentXhr()).url).toBe("api/notes/noteAbc/attachments/upload?role=file");+ expect((await awaitSentXhr()).url).toBe("api/notes/noteAbc/attachments/upload?link=true");FakeXHR.last = undefined;void createAdapter(new File(["content"], "pic.png", { type: "image/png" })).upload();diff --git a/packages/ckeditor5/src/plugins/uploadimage.ts b/packages/ckeditor5/src/plugins/uploadimage.tsindex 0ffa894832..438560377e 100644--- a/packages/ckeditor5/src/plugins/uploadimage.ts+++ b/packages/ckeditor5/src/plugins/uploadimage.ts@@ -1,14 +1,14 @@import { FileRepository, Plugin, type FileLoader, type LocaleTranslate, type UploadAdapter } from "ckeditor5";-const fileAttachmentLoaders = new WeakSet<FileLoader>();+const linkLoaders = new WeakSet<FileLoader>();-/** Makes the loader store its file as a file attachment, even when the file is a picture. */-export function uploadAsFileAttachment(loader: FileLoader) {- fileAttachmentLoaders.add(loader);+/** Makes the upload answer with a link to the attachment, and store a picture as uploaded. */+export function uploadAsLink(loader: FileLoader) {+ linkLoaders.add(loader);}-export function isFileAttachmentUpload(loader: FileLoader) {- return fileAttachmentLoaders.has(loader);+export function isUploadAsLink(loader: FileLoader) {+ return linkLoaders.has(loader);}export default class UploadimagePlugin extends Plugin {@@ -79,7 +79,7 @@ class Adapter implements UploadAdapter {const xhr = this.xhr = new XMLHttpRequest();const {noteId} = glob.getActiveContextNote();- const query = isFileAttachmentUpload(this.loader) ? "?role=file" : "";+ const query = isUploadAsLink(this.loader) ? "?link=true" : "";// this must be a relative pathconst url = `api/notes/${noteId}/attachments/upload${query}`;diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.tsindex a1615600ec..205f212e68 100644--- a/packages/trilium-core/src/routes/api/attachments.spec.ts+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts@@ -1,5 +1,6 @@-import { beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { getImageProvider } from "../../services/image_provider";import { getSql } from "../../services/sql/index";import { createTextNote } from "../../test/api_fixtures";import { CoreApiTester } from "../../test/api_tester";@@ -236,28 +237,33 @@ describe("Attachments API (core)", () => {expect(attachment).toMatchObject({ role: "image", mime: "image/x-icon" });});- it("uploads a picture as a 'file' attachment when the file role is asked for", async () => {- const { noteId } = await createTextNote(api, { title: "Picture as file target" });+ it("stores a picture unchanged as an image, linked to on request", async () => {+ const { noteId } = await createTextNote(api, { title: "Picture as link target" });+ // Past the 40 characters at which "Upload image" names a picture plain "image".+ const originalname = "a picture with a name long enough to be trimmed.png";+ const processImage = vi.spyOn(getImageProvider(), "processImage");const res = await api.post<{ uploaded: boolean; url: string }>(`/api/notes/${noteId}/attachments/upload`,{- query: { role: "file" },- file: {- originalname: "pixel.png",- mimetype: "image/png",- buffer: PIXEL_PNG- }+ query: { link: "true" },+ file: { originalname, mimetype: "image/png", buffer: PIXEL_PNG }});expect(res.status).toBe(200);expect(res.body.uploaded).toBe(true);- expect(res.body.url).toContain(`#root/${noteId}?viewMode=attachments&attachmentId=`);const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);- expect(list.body).toEqual([- expect.objectContaining({ role: "file", mime: "image/png", title: "pixel.png" })- ]);+ const [ attachment ] = list.body;+ expect(attachment)+ .toMatchObject({ role: "image", mime: "image/png", title: originalname });+ const { attachmentId } = attachment;+ expect(res.body.url)+ .toBe(`#root/${noteId}?viewMode=attachments&attachmentId=${attachmentId}`);++ // Not shrunk, whatever the image compression option says.+ expect(processImage).toHaveBeenCalledWith(expect.anything(), originalname, false);+ processImage.mockRestore();});it("reports a missing upload when no file is present", async () => {diff --git a/packages/trilium-core/src/routes/api/attachments.ts b/packages/trilium-core/src/routes/api/attachments.tsindex 8c05b7683d..64026ad112 100644--- a/packages/trilium-core/src/routes/api/attachments.ts+++ b/packages/trilium-core/src/routes/api/attachments.ts@@ -61,13 +61,19 @@ async function uploadAttachment(req: Request<{ noteId: string }>) {// Convert buffer to Uint8Array (Buffer extends Uint8Array, string needs encoding)const buffer = wrapStringOrBuffer(file.buffer as string | Uint8Array);- // `role=file` stores a picture as a file attachment, so the caller gets a link, not an image.- const isFileRoleRequested = req.query.role === "file";+ // With `link=true`, the response links to the attachment and a picture is stored as uploaded.+ const isLinkRequested = req.query.link === "true";- if (!isFileRoleRequested && isAcceptedImageMime(file.mimetype)) {+ if (isAcceptedImageMime(file.mimetype)) {// Always the user's own image: the pictures the app fetches for itself — a link preview's// favicon and cover — are stored by the code that fetched them, never uploaded through here.- const attachment = imageService.saveImageToAttachment(noteId, buffer, file.originalname, true, true);+ const attachment = imageService.saveImageToAttachment(+ noteId,+ buffer,+ file.originalname,+ !isLinkRequested,+ !isLinkRequested+ );// The URL below is fetched the moment this answers — the editor puts it straight into the// document as the source of an image. Answering before the bytes are stored hands it the@@ -75,7 +81,10 @@ async function uploadAttachment(req: Request<{ noteId: string }>) {// something reloads the note. So this one image is waited for; nothing else is.await imageService.awaitImageWrite(attachment.attachmentId);- url = `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}`;+ const { attachmentId, title } = attachment;+ url = isLinkRequested+ ? getAttachmentLinkUrl(noteId, attachmentId)+ : `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`;} else {const attachment = note.saveAttachment({role: "file",@@ -84,7 +93,7 @@ async function uploadAttachment(req: Request<{ noteId: string }>) {content: file.buffer});- url = `#root/${noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}`;+ url = getAttachmentLinkUrl(noteId, attachment.attachmentId);}return {@@ -93,6 +102,10 @@ async function uploadAttachment(req: Request<{ noteId: string }>) {};}+function getAttachmentLinkUrl(noteId: string, attachmentId: string | undefined) {+ return `#root/${noteId}?viewMode=attachments&attachmentId=${attachmentId}`;+}+function renameAttachment(req: Request<{ attachmentId: string }>) {const { title } = req.body;const { attachmentId } = req.params;