Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: add extra commands to the context menu of attachment links

Adorian Doran5e6263b9d6fe
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.ts
index cd2cbd2cab..2a96555501 100644
--- a/apps/client/src/menus/link_context_menu.spec.ts
+++ b/apps/client/src/menus/link_context_menu.spec.ts
@@ -13,11 +13,19 @@ const mocks = vi.hoisted(() => ({
subContexts: [ { ntxId: "ntx-first" }, { ntxId: "ntx-last" } ] as { ntxId: string }[],
activeNtxId: "ntx-active" as string | null,
/** False when no tab is open at all, which leaves both the hoisting and the split unresolvable. */
- hasActiveContext: true
+ hasActiveContext: true,
+ getAttachment: vi.fn(),
+ getAttachmentActionGroups: vi.fn()
}));
vi.mock("./context_menu", () => ({ default: { show: mocks.show } }));
+vi.mock("../services/froca", () => ({ default: { getAttachment: mocks.getAttachment } }));
+
+vi.mock("../services/attachment_actions", () => ({
+ getAttachmentActionGroups: mocks.getAttachmentActionGroups
+}));
+
vi.mock("../services/i18n", () => ({ t: (key: string) => key }));
vi.mock("../services/utils", () => ({
@@ -65,6 +73,7 @@ beforeEach(() => {
mocks.subContexts = [ { ntxId: "ntx-first" }, { ntxId: "ntx-last" } ];
mocks.activeNtxId = "ntx-active";
mocks.hasActiveContext = true;
+ mocks.getAttachment.mockResolvedValue(null);
});
describe("getItems", () => {
@@ -191,8 +200,9 @@ describe("handleLinkContextMenuItem", () => {
});
describe("openContextMenu", () => {
- it("shows the menu at the pointer and routes the chosen item with the link's own state", () => {
- linkContextMenu.openContextMenu("root/n1", contextMenuEvent(), VIEW_SCOPE, "explicitHoist");
+ it("shows the menu at the pointer and routes the choice with the link's state", async () => {
+ const event = contextMenuEvent();
+ await linkContextMenu.openContextMenu("root/n1", event, VIEW_SCOPE, "explicitHoist");
const shown = mocks.show.mock.calls[0][0];
expect(shown).toMatchObject({ x: 12, y: 34 });
@@ -204,4 +214,45 @@ describe("openContextMenu", () => {
viewScope: VIEW_SCOPE
});
});
+
+ it("appends the actions on a linked attachment, each group after a separator", async () => {
+ const attachment = { attachmentId: "att-1" };
+ const download = vi.fn();
+ mocks.getAttachment.mockResolvedValue(attachment);
+ mocks.getAttachmentActionGroups.mockReturnValue([
+ [ { title: "Download", icon: "bx bx-download", run: download } ],
+ [ {
+ title: "Open custom",
+ icon: "bx bx-customize",
+ disabledReason: "Desktop only",
+ run: vi.fn()
+ } ]
+ ]);
+
+ await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(), VIEW_SCOPE);
+
+ expect(mocks.getAttachment).toHaveBeenCalledWith("att-1", true);
+ expect(mocks.getAttachmentActionGroups).toHaveBeenCalledWith(attachment);
+ const { items } = mocks.show.mock.calls[0][0];
+ expect(items.slice(4)).toMatchObject([
+ { kind: "separator" },
+ { title: "Download", uiIcon: "bx bx-download", enabled: true },
+ { kind: "separator" },
+ { title: "Open custom", uiIcon: "bx bx-customize", enabled: false }
+ ]);
+
+ items[5].handler();
+ expect(download).toHaveBeenCalledOnce();
+ });
+
+ 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.getAttachment).not.toHaveBeenCalled();
+
+ await linkContextMenu.openContextMenu("root/n1", contextMenuEvent(), VIEW_SCOPE);
+ expect(mocks.getAttachment).toHaveBeenCalledWith("att-1", true);
+
+ expect(mocks.show.mock.calls.map(([ shown ]) => shown.items.length)).toEqual([ 4, 4 ]);
+ expect(mocks.getAttachmentActionGroups).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.ts
index 4811d4b7de..3afd0a225d 100644
--- a/apps/client/src/menus/link_context_menu.ts
+++ b/apps/client/src/menus/link_context_menu.ts
@@ -1,17 +1,25 @@
import type { GeoMouseEvent } from "../widgets/collections/geomap/map.js";
import appContext, { type CommandNames } from "../components/app_context.js";
+import froca from "../services/froca.js";
import { t } from "../services/i18n.js";
import type { ViewScope } from "../services/link.js";
import utils, { isMobile } from "../services/utils.js";
import { getClosestNtxId } from "../widgets/widget_utils.js";
import contextMenu, { type ContextMenuEvent, type MenuItem } from "./context_menu.js";
-function openContextMenu(notePath: string, e: ContextMenuEvent, viewScope: ViewScope = {}, hoistedNoteId: string | null = null) {
+async function openContextMenu(
+ notePath: string,
+ e: ContextMenuEvent,
+ viewScope: ViewScope = {},
+ hoistedNoteId: string | null = null
+) {
+ const attachmentItems = await getAttachmentItems(viewScope);
+
contextMenu.show({
x: e.pageX,
y: e.pageY,
- items: getItems(e),
+ items: [ ...getItems(e), ...attachmentItems ],
selectMenuItemHandler: ({ command }) => handleLinkContextMenuItem(command, e, notePath, viewScope, hoistedNoteId)
});
}
@@ -79,6 +87,34 @@ function handleLinkContextMenuItem(command: string | undefined, e: ContextMenuEv
return false;
}
+/** The actions on the attachment a link points to, each group after a separator. */
+async function getAttachmentItems(
+ { viewMode, attachmentId }: ViewScope
+): Promise<MenuItem<CommandNames>[]> {
+ if (viewMode !== "attachments" || !attachmentId) {
+ return [];
+ }
+
+ // Imported on demand: `attachment_actions` imports `link`, which imports this module.
+ const [ attachment, { getAttachmentActionGroups } ] = await Promise.all([
+ froca.getAttachment(attachmentId, true),
+ import("../services/attachment_actions.js")
+ ]);
+ if (!attachment) {
+ return [];
+ }
+
+ return getAttachmentActionGroups(attachment).flatMap((group): MenuItem<CommandNames>[] => [
+ { kind: "separator" },
+ ...group.map((action) => ({
+ title: action.title,
+ uiIcon: action.icon,
+ enabled: !action.disabledReason,
+ handler: () => void action.run()
+ }))
+ ]);
+}
+
function getNtxId(e: ContextMenuEvent | GeoMouseEvent) {
if (utils.isDesktop()) {
const subContexts = appContext.tabManager.getActiveContext()?.getSubContexts();
diff --git a/apps/client/src/services/attachment_actions.spec.ts b/apps/client/src/services/attachment_actions.spec.ts
new file mode 100644
index 0000000000..6f70cd8449
--- /dev/null
+++ b/apps/client/src/services/attachment_actions.spec.ts
@@ -0,0 +1,204 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type FAttachment from "../entities/fattachment";
+
+const mocks = vi.hoisted(() => ({
+ open: {
+ openAttachmentExternally: vi.fn(),
+ openAttachmentCustom: vi.fn(),
+ downloadAttachment: vi.fn()
+ },
+ dialog: { prompt: vi.fn(), confirm: vi.fn() },
+ server: { upload: vi.fn(), put: vi.fn(), remove: vi.fn(), post: vi.fn() },
+ toast: { showMessage: vi.fn(), showError: vi.fn() },
+ utils: { isElectron: vi.fn(() => true), copyHtmlToClipboard: vi.fn() },
+ createLink: vi.fn(),
+ triggerCommand: vi.fn(),
+ setNote: vi.fn(),
+ showImageCompressionDialog: vi.fn()
+}));
+
+vi.mock("./i18n", () => ({ t: (key: string) => key }));
+vi.mock("./open", () => ({ default: mocks.open }));
+vi.mock("./dialog", () => ({ default: mocks.dialog }));
+vi.mock("./server", () => ({ default: mocks.server }));
+vi.mock("./toast", () => ({ default: mocks.toast }));
+vi.mock("./utils", () => ({ default: mocks.utils }));
+vi.mock("./ws", () => ({ default: { waitForMaxKnownEntityChangeId: vi.fn() } }));
+vi.mock("./link", () => ({ default: { createLink: mocks.createLink } }));
+vi.mock("../components/app_context", () => ({
+ default: {
+ triggerCommand: mocks.triggerCommand,
+ tabManager: { getActiveContext: () => ({ setNote: mocks.setNote }) }
+ }
+}));
+vi.mock("../widgets/dialogs/image_compression/image_compression_dialog", () => ({
+ showImageCompressionDialog: mocks.showImageCompressionDialog
+}));
+
+const { copyAttachmentReference, getAttachmentActionGroups } = await import("./attachment_actions");
+
+function attachmentOf(role: string, mime = "application/pdf") {
+ const title = "report.pdf";
+ return { attachmentId: "att1", ownerId: "owner1", role, mime, title } as FAttachment;
+}
+
+function titles(attachment: FAttachment) {
+ const groups = getAttachmentActionGroups(attachment);
+ return groups.map((group) => group.map((action) => action.title));
+}
+
+/** The actions keyed by their title, which the mocked `t()` leaves as the translation key. */
+function actionsOf(attachment: FAttachment) {
+ const actions = getAttachmentActionGroups(attachment).flat();
+ return Object.fromEntries(actions.map((action) => [ action.title, action ]));
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.utils.isElectron.mockReturnValue(true);
+});
+
+describe("getAttachmentActionGroups", () => {
+ it("groups the actions, offering text extraction and compression only where they apply", () => {
+ expect(titles(attachmentOf("file"))).toEqual([
+ [
+ "attachments_actions.open_externally",
+ "attachments_actions.open_custom",
+ "attachments_actions.download",
+ "ocr.view_extracted_text"
+ ],
+ [
+ "attachments_actions.upload_new_revision",
+ "attachments_actions.rename_attachment",
+ "attachments_actions.delete_attachment"
+ ],
+ [ "attachments_actions.convert_attachment_into_note" ]
+ ]);
+
+ const image = titles(attachmentOf("image", "image/png"));
+ expect(image[0]).toContain("ocr.view_extracted_text");
+ expect(image[2]).toEqual([
+ "compress-image",
+ "attachments_actions.convert_attachment_into_note"
+ ]);
+
+ // A link preview's picture belongs to the preview, not to the note.
+ const favicon = titles(attachmentOf("favicon", "image/png"));
+ expect(favicon[0]).not.toContain("ocr.view_extracted_text");
+ expect(favicon[2]).toEqual([ "attachments_actions.convert_attachment_into_note" ]);
+ });
+
+ it("disables custom opening outside the desktop app, saying why", () => {
+ expect(actionsOf(attachmentOf("file"))["attachments_actions.open_custom"].disabledReason)
+ .toBeUndefined();
+
+ mocks.utils.isElectron.mockReturnValue(false);
+ expect(actionsOf(attachmentOf("file"))["attachments_actions.open_custom"].disabledReason)
+ .toBe("attachments_actions.open_custom_client_only");
+ });
+
+ it("opens, downloads, extracts text from and compresses the attachment", async () => {
+ const actions = actionsOf(attachmentOf("image", "image/png"));
+
+ await actions["attachments_actions.open_externally"].run();
+ await actions["attachments_actions.open_custom"].run();
+ await actions["attachments_actions.download"].run();
+ await actions["ocr.view_extracted_text"].run();
+ await actions["compress-image"].run();
+
+ expect(mocks.open.openAttachmentExternally).toHaveBeenCalledWith("att1", "image/png");
+ expect(mocks.open.openAttachmentCustom).toHaveBeenCalledWith("att1", "image/png");
+ expect(mocks.open.downloadAttachment).toHaveBeenCalledWith("att1");
+ expect(mocks.triggerCommand).toHaveBeenCalledWith("showOcrTextDialog", {
+ textUrl: "ocr/attachments/att1/text",
+ processUrl: "ocr/process-attachment/att1"
+ });
+ expect(mocks.showImageCompressionDialog).toHaveBeenCalledWith({
+ type: "attachment",
+ attachmentId: "att1",
+ mime: "image/png"
+ });
+ });
+
+ it("offers copying a reference only to a caller that supplies the copy", async () => {
+ const copyReference = vi.fn();
+ const [ first ] = getAttachmentActionGroups(attachmentOf("file"), { copyReference });
+
+ expect(first.map((action) => action.title)).toEqual([
+ "attachments_actions.open_externally",
+ "attachments_actions.open_custom",
+ "attachments_actions.download",
+ "attachments_actions.copy_link_to_clipboard",
+ "ocr.view_extracted_text"
+ ]);
+
+ await first[3].run();
+ expect(copyReference).toHaveBeenCalledOnce();
+ });
+
+ it("renames, deletes and converts only once the user has agreed", async () => {
+ const actions = actionsOf(attachmentOf("file"));
+ mocks.dialog.prompt.mockResolvedValueOnce(" ").mockResolvedValueOnce("Renamed");
+ mocks.dialog.confirm.mockResolvedValue(false);
+
+ await actions["attachments_actions.rename_attachment"].run();
+ await actions["attachments_actions.delete_attachment"].run();
+ await actions["attachments_actions.convert_attachment_into_note"].run();
+ expect(mocks.server.put).not.toHaveBeenCalled();
+ expect(mocks.server.remove).not.toHaveBeenCalled();
+ expect(mocks.server.post).not.toHaveBeenCalled();
+
+ mocks.dialog.confirm.mockResolvedValue(true);
+ mocks.server.post.mockResolvedValue({ note: { noteId: "newNote" } });
+
+ await actions["attachments_actions.rename_attachment"].run();
+ await actions["attachments_actions.delete_attachment"].run();
+ await actions["attachments_actions.convert_attachment_into_note"].run();
+ expect(mocks.server.put)
+ .toHaveBeenCalledWith("attachments/att1/rename", { title: "Renamed" });
+ expect(mocks.server.remove).toHaveBeenCalledWith("attachments/att1");
+ expect(mocks.server.post).toHaveBeenCalledWith("attachments/att1/convert-to-note");
+ expect(mocks.setNote).toHaveBeenCalledWith("newNote");
+ });
+
+ it("uploads the picked file as a new revision, reporting the outcome", async () => {
+ const click = vi.spyOn(HTMLInputElement.prototype, "click").mockReturnValue(undefined);
+ const file = new File([ "new" ], "report.pdf", { type: "application/pdf" });
+
+ const outcomes = [
+ [ true, mocks.toast.showMessage ],
+ [ false, mocks.toast.showError ]
+ ] as const;
+
+ for (const [ uploaded, report ] of outcomes) {
+ click.mockClear();
+ mocks.server.upload.mockResolvedValue({ uploaded });
+ await actionsOf(attachmentOf("file"))["attachments_actions.upload_new_revision"].run();
+
+ const input = click.mock.instances[0] as unknown as HTMLInputElement;
+ expect(input.type).toBe("file");
+ Object.defineProperty(input, "files", { value: { item: () => file } });
+ input.dispatchEvent(new Event("change"));
+
+ await vi.waitFor(() => expect(report).toHaveBeenCalled());
+ expect(mocks.server.upload).toHaveBeenLastCalledWith("attachments/att1/file", file);
+ }
+ });
+});
+
+describe("copyAttachmentReference", () => {
+ it("puts a reference link to the attachment on the clipboard", async () => {
+ const html = "<a class=\"reference-link\">x</a>";
+ mocks.createLink.mockResolvedValue([ { outerHTML: html } ]);
+
+ await copyAttachmentReference(attachmentOf("file"));
+
+ expect(mocks.createLink).toHaveBeenCalledWith("owner1", {
+ referenceLink: true,
+ viewScope: { viewMode: "attachments", attachmentId: "att1" }
+ });
+ expect(mocks.utils.copyHtmlToClipboard).toHaveBeenCalledWith(html);
+ expect(mocks.toast.showMessage).toHaveBeenCalledWith("attachment_detail_2.link_copied");
+ });
+});
diff --git a/apps/client/src/services/attachment_actions.ts b/apps/client/src/services/attachment_actions.ts
new file mode 100644
index 0000000000..a0bd50b883
--- /dev/null
+++ b/apps/client/src/services/attachment_actions.ts
@@ -0,0 +1,195 @@
+import type { ConvertAttachmentToNoteResponse } from "@triliumnext/commons";
+
+import appContext from "../components/app_context.js";
+import type FAttachment from "../entities/fattachment.js";
+import {
+ showImageCompressionDialog
+} from "../widgets/dialogs/image_compression/image_compression_dialog.js";
+import dialog from "./dialog.js";
+import { t } from "./i18n.js";
+import link from "./link.js";
+import open from "./open.js";
+import server from "./server.js";
+import toast from "./toast.js";
+import utils from "./utils.js";
+import ws from "./ws.js";
+
+/** One action on an attachment, as the menus offering it list it. */
+export interface AttachmentAction {
+ title: string;
+ icon: string;
+ /** A longer explanation, shown where the menu supports a tooltip. */
+ tooltip?: string;
+ /** Why the action cannot run here. Unset when it can. */
+ disabledReason?: string;
+ run: () => void | Promise<void>;
+}
+
+export interface AttachmentActionOptions {
+ /** Copies a reference to the attachment. Without it, the actions offer no copy. */
+ copyReference?: () => void | Promise<void>;
+}
+
+/**
+ * The actions on `attachment`, in the groups a menu separates with a divider. The attachment page
+ * and the context menu of an attachment link both list them.
+ */
+export function getAttachmentActionGroups(
+ attachment: FAttachment,
+ { copyReference }: AttachmentActionOptions = {}
+): AttachmentAction[][] {
+ const { attachmentId, mime } = attachment;
+
+ return [
+ [
+ {
+ title: t("attachments_actions.open_externally"),
+ tooltip: t("attachments_actions.open_externally_title"),
+ icon: "bx bx-file-find",
+ run: () => open.openAttachmentExternally(attachmentId, mime)
+ },
+ {
+ title: t("attachments_actions.open_custom"),
+ tooltip: t("attachments_actions.open_custom_title"),
+ icon: "bx bx-customize",
+ disabledReason: utils.isElectron()
+ ? undefined
+ : t("attachments_actions.open_custom_client_only"),
+ run: () => open.openAttachmentCustom(attachmentId, mime)
+ },
+ {
+ title: t("attachments_actions.download"),
+ icon: "bx bx-download",
+ run: () => open.downloadAttachment(attachmentId)
+ },
+ ...(copyReference ? [ {
+ title: t("attachments_actions.copy_link_to_clipboard"),
+ icon: "bx bx-copy",
+ run: copyReference
+ } ] : []),
+ ...(supportsOcr(attachment) ? [ {
+ title: t("ocr.view_extracted_text"),
+ icon: "bx bx-text",
+ run: () => appContext.triggerCommand("showOcrTextDialog", {
+ textUrl: `ocr/attachments/${attachmentId}/text`,
+ processUrl: `ocr/process-attachment/${attachmentId}`
+ })
+ } ] : [])
+ ],
+ [
+ {
+ title: t("attachments_actions.upload_new_revision"),
+ icon: "bx bx-upload",
+ run: () => pickFile((file) => uploadNewRevision(attachment, file))
+ },
+ {
+ title: t("attachments_actions.rename_attachment"),
+ icon: "bx bx-rename",
+ run: () => renameAttachment(attachment)
+ },
+ {
+ title: t("attachments_actions.delete_attachment"),
+ icon: "bx bx-trash destructive-action-icon",
+ run: () => deleteAttachment(attachment)
+ }
+ ],
+ [
+ // A link preview's pictures are left out: the server already sized them.
+ ...(attachment.role === "image" ? [ {
+ title: t("compress-image"),
+ icon: "bx bx-collapse-alt",
+ run: () => void showImageCompressionDialog({
+ type: "attachment",
+ attachmentId,
+ mime
+ })
+ } ] : []),
+ {
+ title: t("attachments_actions.convert_attachment_into_note"),
+ icon: "bx bx-note",
+ run: () => convertAttachmentToNote(attachment)
+ }
+ ]
+ ];
+}
+
+/** Whether the attachment is an ordinary file, previewed and linked like one. */
+export function isFileLikeAttachment(attachment: FAttachment) {
+ return attachment.role === "file" || attachment.role === "importSource";
+}
+
+/** Puts a reference link to the attachment on the clipboard. */
+export async function copyAttachmentReference(attachment: FAttachment) {
+ const $link = await link.createLink(attachment.ownerId, {
+ referenceLink: true,
+ viewScope: {
+ viewMode: "attachments",
+ attachmentId: attachment.attachmentId
+ }
+ });
+
+ utils.copyHtmlToClipboard($link[0].outerHTML);
+ toast.showMessage(t("attachment_detail_2.link_copied"));
+}
+
+/** Link previews' pictures are left out: their text belongs to the preview, not to the note. */
+function supportsOcr(attachment: FAttachment) {
+ return attachment.role === "image" || isFileLikeAttachment(attachment);
+}
+
+/** Opens the browser's file picker and passes the picked file to `onPick`. */
+function pickFile(onPick: (file: File) => void) {
+ const input = document.createElement("input");
+ input.type = "file";
+ input.addEventListener("change", () => {
+ const file = input.files?.item(0);
+ if (file) {
+ onPick(file);
+ }
+ });
+ input.click();
+}
+
+async function uploadNewRevision(attachment: FAttachment, file: File) {
+ const result = await server.upload(`attachments/${attachment.attachmentId}/file`, file);
+ if (result.uploaded) {
+ toast.showMessage(t("attachments_actions.upload_success"));
+ } else {
+ toast.showError(t("attachments_actions.upload_failed"));
+ }
+}
+
+async function renameAttachment(attachment: FAttachment) {
+ const title = await dialog.prompt({
+ title: t("attachments_actions.rename_attachment"),
+ message: t("attachments_actions.enter_new_name"),
+ defaultValue: attachment.title
+ });
+
+ if (!title?.trim()) return;
+ await server.put(`attachments/${attachment.attachmentId}/rename`, { title });
+}
+
+async function deleteAttachment(attachment: FAttachment) {
+ const { title } = attachment;
+ if (!(await dialog.confirm(t("attachments_actions.delete_confirm", { title })))) {
+ return;
+ }
+
+ await server.remove(`attachments/${attachment.attachmentId}`);
+ toast.showMessage(t("attachments_actions.delete_success", { title }));
+}
+
+async function convertAttachmentToNote(attachment: FAttachment) {
+ const { title } = attachment;
+ if (!(await dialog.confirm(t("attachments_actions.convert_confirm", { title })))) {
+ return;
+ }
+
+ const { note: newNote } = await server.post<ConvertAttachmentToNoteResponse>(
+ `attachments/${attachment.attachmentId}/convert-to-note`
+ );
+ toast.showMessage(t("attachments_actions.convert_success", { title }));
+ await ws.waitForMaxKnownEntityChangeId();
+ await appContext.tabManager.getActiveContext()?.setNote(newNote.noteId);
+}
diff --git a/apps/client/src/widgets/type_widgets/Attachment.tsx b/apps/client/src/widgets/type_widgets/Attachment.tsx
index a21907f1b3..29f3a0142e 100644
--- a/apps/client/src/widgets/type_widgets/Attachment.tsx
+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx
@@ -1,34 +1,33 @@
import "./Attachment.css";
-import { attachmentIcon, ConvertAttachmentToNoteResponse, isImageAttachmentRole } from "@triliumnext/commons";
+import { attachmentIcon, isImageAttachmentRole } from "@triliumnext/commons";
import { t } from "i18next";
+import { Fragment } from "preact";
import { useContext, useEffect, useMemo, useRef, useState } from "preact/hooks";
-import appContext from "../../components/app_context";
import type NoteContext from "../../components/note_context";
import FAttachment from "../../entities/fattachment";
import FNote from "../../entities/fnote";
import imageContextMenu from "../../menus/image_context_menu";
+import {
+ copyAttachmentReference,
+ getAttachmentActionGroups,
+ isFileLikeAttachment
+} from "../../services/attachment_actions";
import { partitionAttachmentsByGroup } from "../../services/attachment_groups";
import { attachmentRoleLabel } from "../../services/attachment_role_names";
import content_renderer from "../../services/content_renderer";
-import dialog from "../../services/dialog";
import froca from "../../services/froca";
import image from "../../services/image";
-import link, { type ViewScope } from "../../services/link";
-import open from "../../services/open";
+import { type ViewScope } from "../../services/link";
import options from "../../services/options";
-import server from "../../services/server";
-import toast from "../../services/toast";
import utils from "../../services/utils";
-import ws from "../../services/ws";
import { showImageCompressionDialog } from "../dialogs/image_compression/image_compression_dialog";
import ActionButton from "../react/ActionButton";
import { Badge } from "../react/Badge";
import Button from "../react/Button";
import { ExternallyControlledCollapsible } from "../react/Collapsible";
import Dropdown from "../react/Dropdown";
-import FormFileUpload from "../react/FormFileUpload";
import { FormDropdownDivider, FormListItem } from "../react/FormList";
import HelpButton from "../react/HelpButton";
import { useAttachments, useTriliumEvent } from "../react/hooks";
@@ -212,12 +211,8 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
const [ modified, setModified ] = useState(attachment.utcDateModified);
// "importSource" attachments (e.g. OneNote debug source) behave like ordinary files for
// preview, OCR and link-copying purposes.
- const isFileLike = attachment.role === "file" || attachment.role === "importSource";
+ const isFileLike = isFileLikeAttachment(attachment);
const isPicture = isImageAttachmentRole(attachment.role);
- // A link preview's pictures are deliberately left out: the server already sized both, and both
- // belong to a preview rather than to the note, so reading text out of them — or offering to
- // recompress them further down — is noise in every attachment list that holds a preview.
- const supportsOcr = attachment.role === "image" || isFileLike;
// Opened in full detail, an image gets the interactive zoom/pan viewer and audio/video the full media
// player — both mounted here rather than through the content renderer, which has no tab context to hand
@@ -277,17 +272,7 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
const $img = refToJQuerySelector(isZoomableImage ? imageViewerWrapper : contentWrapper).find("img");
if ($img.length) image.copyImageReferenceToClipboard($img.parent());
} else if (isFileLike) {
- const $link = await link.createLink(attachment.ownerId, {
- referenceLink: true,
- viewScope: {
- viewMode: "attachments",
- attachmentId: attachment.attachmentId
- }
- });
-
- utils.copyHtmlToClipboard($link[0].outerHTML);
-
- toast.showMessage(t("attachment_detail_2.link_copied"));
+ await copyAttachmentReference(attachment);
} else {
throw new Error(t("attachment_detail_2.unrecognized_role", { role: attachment.role }));
}
@@ -300,10 +285,6 @@ function AttachmentInfo({ attachment, isFullDetail, ownerNote, noteContext, view
<AttachmentActions
attachment={attachment}
copyAttachmentReferenceToClipboard={copyAttachmentReferenceToClipboard}
- onShowOcr={supportsOcr ? () => appContext.triggerCommand("showOcrTextDialog", {
- textUrl: `ocr/attachments/${attachment.attachmentId}/text`,
- processUrl: `ocr/process-attachment/${attachment.attachmentId}`
- }) : undefined}
/>
<AttachmentIcon attachment={attachment} />
<h4 className="attachment-title">
@@ -418,9 +399,13 @@ function DeletionBadge({ utcDateScheduledForErasureSince }: { utcDateScheduledFo
);
}
-function AttachmentActions({ attachment, copyAttachmentReferenceToClipboard, onShowOcr }: { attachment: FAttachment, copyAttachmentReferenceToClipboard: () => void, onShowOcr?: () => void }) {
- const isElectron = utils.isElectron();
- const fileUploadRef = useRef<HTMLInputElement>(null);
+function AttachmentActions({ attachment, copyAttachmentReferenceToClipboard }: {
+ attachment: FAttachment;
+ copyAttachmentReferenceToClipboard: () => void;
+}) {
+ const groups = getAttachmentActionGroups(attachment, {
+ copyReference: copyAttachmentReferenceToClipboard
+ });
return (
<div className="attachment-actions-container">
@@ -431,103 +416,21 @@ function AttachmentActions({ attachment, copyAttachmentReferenceToClipboard, onS
iconAction
mobileBottomSheet
>
- <FormListItem
- icon="bx bx-file-find"
- title={t("attachments_actions.open_externally_title")}
- onClick={() => open.openAttachmentExternally(attachment.attachmentId, attachment.mime)}
- >{t("attachments_actions.open_externally")}</FormListItem>
- <FormListItem
- icon="bx bx-customize"
- title={t("attachments_actions.open_custom_title")}
- onClick={() => open.openAttachmentCustom(attachment.attachmentId, attachment.mime)}
- disabled={!isElectron}
- disabledTooltip={!isElectron ? t("attachments_actions.open_custom_client_only") : t("attachments_actions.open_externally_detail_page")}
- >{t("attachments_actions.open_custom")}</FormListItem>
- <FormListItem
- icon="bx bx-download"
- onClick={() => open.downloadAttachment(attachment.attachmentId)}
- >{t("attachments_actions.download")}</FormListItem>
- <FormListItem
- icon="bx bx-copy"
- onClick={copyAttachmentReferenceToClipboard}
- >{t("attachments_actions.copy_link_to_clipboard")}</FormListItem>
- {onShowOcr && (
- <FormListItem
- icon="bx bx-text"
- onClick={onShowOcr}
- >{t("ocr.view_extracted_text")}</FormListItem>
- )}
- <FormDropdownDivider />
-
- <FormListItem
- icon="bx bx-upload"
- onClick={() => fileUploadRef.current?.click()}
- >{t("attachments_actions.upload_new_revision")}</FormListItem>
- <FormListItem
- icon="bx bx-rename"
- onClick={async () => {
- const attachmentTitle = await dialog.prompt({
- title: t("attachments_actions.rename_attachment"),
- message: t("attachments_actions.enter_new_name"),
- defaultValue: attachment.title
- });
-
- if (!attachmentTitle?.trim()) return;
- await server.put(`attachments/${attachment.attachmentId}/rename`, { title: attachmentTitle });
- }}
- >{t("attachments_actions.rename_attachment")}</FormListItem>
- <FormListItem
- icon="bx bx-trash destructive-action-icon"
- onClick={async () => {
- if (!(await dialog.confirm(t("attachments_actions.delete_confirm", { title: attachment.title })))) {
- return;
- }
-
- await server.remove(`attachments/${attachment.attachmentId}`);
- toast.showMessage(t("attachments_actions.delete_success", { title: attachment.title }));
- }}
- >{t("attachments_actions.delete_attachment")}</FormListItem>
- <FormDropdownDivider />
-
- {attachment.role === "image" && (
- <FormListItem
- icon="bx bx-collapse-alt"
- onClick={() => void showImageCompressionDialog({
- type: "attachment",
- attachmentId: attachment.attachmentId,
- mime: attachment.mime
- })}
- >{t("compress-image")}</FormListItem>
- )}
- <FormListItem
- icon="bx bx-note"
- onClick={async () => {
- if (!(await dialog.confirm(t("attachments_actions.convert_confirm", { title: attachment.title })))) {
- return;
- }
-
- const { note: newNote } = await server.post<ConvertAttachmentToNoteResponse>(`attachments/${attachment.attachmentId}/convert-to-note`);
- toast.showMessage(t("attachments_actions.convert_success", { title: attachment.title }));
- await ws.waitForMaxKnownEntityChangeId();
- await appContext.tabManager.getActiveContext()?.setNote(newNote.noteId);
- }}
- >{t("attachments_actions.convert_attachment_into_note")}</FormListItem>
-
- <FormFileUpload
- inputRef={fileUploadRef}
- hidden
- onChange={async files => {
- const fileToUpload = files?.item(0);
- if (fileToUpload) {
- const result = await server.upload(`attachments/${attachment.attachmentId}/file`, fileToUpload);
- if (result.uploaded) {
- toast.showMessage(t("attachments_actions.upload_success"));
- } else {
- toast.showError(t("attachments_actions.upload_failed"));
- }
- }
- }}
- />
+ {groups.map((group, index) => (
+ <Fragment key={index}>
+ {index > 0 && <FormDropdownDivider />}
+ {group.map((action) => (
+ <FormListItem
+ key={action.title}
+ icon={action.icon}
+ title={action.tooltip}
+ disabled={!!action.disabledReason}
+ disabledTooltip={action.disabledReason}
+ onClick={() => void action.run()}
+ >{action.title}</FormListItem>
+ ))}
+ </Fragment>
+ ))}
</Dropdown>
</div>
);
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
index 6ef186456b..e439206ef4 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
@@ -6,9 +6,11 @@
* crash and restarted the editor, which reverted the note to its last saved content — the images
* being uploaded flickered and vanished instead of a "cannot upload" toast appearing.
*/
-import type { FileUploadData } from "@triliumnext/ckeditor5";
+import type { CKTextEditor, FileUploadData } from "@triliumnext/ckeditor5";
import { describe, expect, it, vi } from "vitest";
+import type LoadResults from "../../../services/load_results";
+
const showError = vi.hoisted(() => vi.fn());
const showErrorTitleAndMessage = vi.hoisted(() => vi.fn());
const showMessage = vi.hoisted(() => vi.fn());
@@ -26,6 +28,7 @@ vi.mock("../../../services/i18n", async (importOriginal) => ({
vi.mock("@triliumnext/ckeditor5", () => ({}));
const {
+ notifyAttachmentChanges,
onNotificationInfo,
onNotificationWarning,
showFileUploadProgress
@@ -125,3 +128,48 @@ describe("showFileUploadProgress", () => {
);
});
});
+
+describe("notifyAttachmentChanges", () => {
+ type Row = { attachmentId?: string; isDeleted?: boolean };
+
+ function setUp(rows: Row[], isContentReloaded = false) {
+ const updateAttachmentLinks = vi.fn();
+ const editor = {
+ plugins: { get: () => ({ updateAttachmentLinks }) }
+ } as unknown as CKTextEditor;
+ const loadResults = {
+ getAttachmentRows: () => rows,
+ isNoteContentReloaded: vi.fn(() => isContentReloaded)
+ };
+
+ return { editor, loadResults, updateAttachmentLinks };
+ }
+
+ it("passes the changed attachments to the editor's reference links", () => {
+ const { editor, loadResults, updateAttachmentLinks } = setUp([
+ { attachmentId: "renamed" },
+ { attachmentId: "deleted", isDeleted: true }
+ ]);
+
+ const results = loadResults as unknown as LoadResults;
+ notifyAttachmentChanges(editor, results, "note1", "component1");
+
+ expect(loadResults.isNoteContentReloaded).toHaveBeenCalledWith("note1", "component1");
+ expect(updateAttachmentLinks).toHaveBeenCalledWith([
+ { attachmentId: "renamed", isDeleted: false },
+ { attachmentId: "deleted", isDeleted: true }
+ ]);
+ });
+
+ it("leaves the links alone when no attachment changed, or the content was reloaded", () => {
+ const cases: [ Row[], boolean ][] = [ [ [], false ], [ [ { attachmentId: "a" } ], true ] ];
+
+ for (const [ rows, isContentReloaded ] of cases) {
+ const { editor, loadResults, updateAttachmentLinks } = setUp(rows, isContentReloaded);
+
+ notifyAttachmentChanges(editor, loadResults as unknown as LoadResults, "note1");
+
+ expect(updateAttachmentLinks).not.toHaveBeenCalled();
+ }
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 86e6711257..f8c50b23fb 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -18,6 +18,7 @@ import dateNoteService from "../../../services/date_notes";
import dialog from "../../../services/dialog";
import { t } from "../../../services/i18n";
import link, { parseNavigationStateFromUrl } from "../../../services/link";
+import type LoadResults from "../../../services/load_results";
import note_create from "../../../services/note_create";
import options from "../../../services/options";
import { consumeSearchTerms } from "../../../services/search_jump";
@@ -268,6 +269,13 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
refreshIncludedNote(containerRef.current, noteId);
});
+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
+ const editor = watchdogRef.current?.editor as CKTextEditor | null | undefined;
+ if (editor && note) {
+ notifyAttachmentChanges(editor, loadResults, note.noteId, parentComponent?.componentId);
+ }
+ });
+
useTriliumEvent("executeWithTextEditor", async ({ callback, resolve, ntxId: eventNtxId }) => {
if (eventNtxId !== ntxId) return;
const editor = await waitForEditor() as CKTextEditor | undefined;
@@ -661,6 +669,30 @@ export function onNotificationInfo(_evt: NotificationEventInfo, data: Notificati
toast.showMessage(data.message);
}
+/**
+ * Passes the attachments changed in `loadResults` to the editor's reference links, so a link shows
+ * the new title of its attachment or goes away with it.
+ *
+ * Exported for testing.
+ */
+export function notifyAttachmentChanges(
+ editor: CKTextEditor,
+ loadResults: LoadResults,
+ noteId: string,
+ componentId?: string
+) {
+ const changes = loadResults.getAttachmentRows().flatMap(({ attachmentId, isDeleted }) =>
+ attachmentId ? [ { attachmentId, isDeleted: !!isDeleted } ] : []
+ );
+
+ // The server rewrote the links in reloaded content itself, as when converting an attachment.
+ if (!changes.length || loadResults.isNoteContentReloaded(noteId, componentId)) {
+ return;
+ }
+
+ editor.plugins.get("ReferenceLinkEditing").updateAttachmentLinks(changes);
+}
+
/**
* Shows the progress of a file attachment upload in a toast until the upload ends.
*
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.html
index 5e2b041400..7019ab6096 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
@@ -51,6 +51,14 @@
</ul>
<p>Dragging a file that is not a picture from the file explorer onto the
text also attaches it and inserts a link to it.</p>
+<h2>Acting on an attachment link</h2>
+<p>Right-clicking a link to an attachment shows the ways to open it, followed
+ by actions on the attachment: opening it externally, downloading it, uploading
+ a new revision, renaming or deleting it, and converting it into a note.</p>
+<p>Links follow changes to their attachment: renaming it updates the title
+ they show, and deleting it removes them from the text notes open for editing
+ at that moment. Converting it into a note turns its links into links to
+ the new note.</p>
<h2>Converting notes to attachments</h2>
<p><a class="reference-link" href="#root/_help_W8vYD3Q1zjCR">File</a>&nbsp;notes
can be easily converted to attachments of the parent note.</p>
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.md
index dfff7eab18..597b23034b 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
@@ -29,6 +29,12 @@ To attach files to a <a class="reference-link" href="../../Note%20Types/Text.md
Dragging a file that is not a picture from the file explorer onto the text also attaches it and inserts a link to it.
+## Acting on an attachment link
+
+Right-clicking a link to an attachment shows the ways to open it, followed by actions on the attachment: opening it externally, downloading it, uploading a new revision, renaming or deleting it, and converting it into a note.
+
+Links follow changes to their attachment: renaming it updates the title they show, and deleting it removes them from the text notes open for editing at that moment. Converting it into a note turns its links into links to the new note.
+
## Converting notes to attachments
<a class="reference-link" href="../../Note%20Types/File.md">File</a> notes can be easily converted to attachments of the parent note.
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index a0b96a52bc..ede0b95100 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -29,6 +29,7 @@ export * from "./utils.js";
import "./plugins/file_upload/uploadfileplugin.js";
import "./plugins/math/math.js";
import "./plugins/mermaid/mermaid.js";
+import "./plugins/referencelink.js";
import "./plugins/table_context_menu.js";
import "./plugins/table_paste_rows.js";
diff --git a/packages/ckeditor5/src/plugins/referencelink.spec.ts b/packages/ckeditor5/src/plugins/referencelink.spec.ts
index 44a281b9af..bc14dd10a8 100644
--- a/packages/ckeditor5/src/plugins/referencelink.spec.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.spec.ts
@@ -213,6 +213,33 @@ describe("ReferenceLink", () => {
expect(loadReferenceLinkTitle).toHaveBeenCalledWith(expect.anything(), "#root/abc");
});
+ it("redraws the links to a changed attachment and removes those to a deleted one", () => {
+ const attachmentHref = (id: string) =>
+ `#root/owner?viewMode=attachments&amp;attachmentId=${id}`;
+ editor.setData(
+ `<p><a class="reference-link" href="${attachmentHref("renamed")}">a</a></p>` +
+ `<p><a class="reference-link" href="${attachmentHref("deleted")}">b</a></p>` +
+ "<p><a class=\"reference-link\" href=\"#root/noteAbc\">c</a></p>"
+ );
+ loadReferenceLinkTitle.mockClear();
+
+ editor.plugins.get("ReferenceLinkEditing").updateAttachmentLinks([
+ { attachmentId: "renamed", isDeleted: false },
+ { attachmentId: "deleted", isDeleted: true }
+ ]);
+
+ const redrawnHrefs = new Set(loadReferenceLinkTitle.mock.calls.map(([ , href ]) => href));
+ 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></paragraph>" +
+ "<paragraph><reference href=\"#root/noteAbc\"></reference></paragraph>"
+ );
+ // The removal records a change made elsewhere, so undo cannot bring the link back.
+ expect(editor.commands.get("undo")?.isEnabled).toBe(false);
+ });
+
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>');
diff --git a/packages/ckeditor5/src/plugins/referencelink.ts b/packages/ckeditor5/src/plugins/referencelink.ts
index 6d355f9643..4974bdf4fd 100644
--- a/packages/ckeditor5/src/plugins/referencelink.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.ts
@@ -60,11 +60,61 @@ class ReferenceLinkCommand extends Command {
}
}
-class ReferenceLinkEditing extends Plugin {
+/** An attachment that changed, as `ReferenceLinkEditing#updateAttachmentLinks` takes it. */
+export interface AttachmentLinkChange {
+ attachmentId: string;
+ isDeleted: boolean;
+}
+
+export class ReferenceLinkEditing extends Plugin {
static get requires() {
return [ Widget, LinkEditing ];
}
+ static get pluginName() {
+ return 'ReferenceLinkEditing' as const;
+ }
+
+ /**
+ * Redraws the links to changed attachments, so they show the current title, and removes the
+ * links to deleted ones.
+ */
+ updateAttachmentLinks( changes: AttachmentLinkChange[] ) {
+ const editor = this.editor;
+ const isDeletedById = new Map(
+ changes.map( change => [ change.attachmentId, change.isDeleted ] )
+ );
+ const changedLinks: ModelElement[] = [];
+ const deletedLinks: ModelElement[] = [];
+
+ for ( const root of editor.model.document.getRoots() ) {
+ for ( const { item } of editor.model.createRangeIn( root ) ) {
+ if ( !item.is( 'element', 'reference' ) ) {
+ continue;
+ }
+
+ const attachmentId = getAttachmentId( item.getAttribute( 'href' ) );
+ const isDeleted = attachmentId ? isDeletedById.get( attachmentId ) : undefined;
+ if ( isDeleted !== undefined ) {
+ ( isDeleted ? deletedLinks : changedLinks ).push( item );
+ }
+ }
+ }
+
+ for ( const link of changedLinks ) {
+ editor.editing.reconvertItem( link );
+ }
+
+ if ( deletedLinks.length ) {
+ // The attachment changed outside this editor, so undo does not bring its link back.
+ editor.model.enqueueChange( { isUndoable: false }, writer => {
+ for ( const link of deletedLinks ) {
+ writer.remove( link );
+ }
+ } );
+ }
+ }
+
init() {
this._defineSchema();
this._defineConverters();
@@ -176,3 +226,15 @@ class ReferenceLinkEditing extends Plugin {
} );
}
}
+
+/** The attachment a reference link points to, or `null` for a link to a note. */
+function getAttachmentId( href: unknown ) {
+ const query = typeof href === 'string' ? href.split( '?' )[ 1 ] : undefined;
+ return query ? new URLSearchParams( query ).get( 'attachmentId' ) : null;
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [ReferenceLinkEditing.pluginName]: ReferenceLinkEditing;
+ }
+}