Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: add a quick way to upload attachments straight from the text editor

Adorian Doran9a63e768a612
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.ts
index 74451f8254..e3f4794683 100644
--- a/apps/client/src/services/link.spec.ts
+++ b/apps/client/src/services/link.spec.ts
@@ -826,16 +826,18 @@ describe("getReferenceLinkTitle / getReferenceLinkTitleSync", () => {
expect(await linkService.getReferenceLinkTitle(`#root/${note.noteId}`)).toBe("Referenced");
});
- it("getReferenceLinkTitle resolves attachment titles", async () => {
+ it("getReferenceLinkTitle resolves an attachment the cached list lacks", async () => {
const note = buildNote({ title: "WithAtt" });
- note.getAttachmentById = vi.fn(async () => ({ title: "Att" }) as any);
+ note.attachments = [];
+ froca.getAttachment = vi.fn(async () => ({ title: "Att" }) as any);
const title = await linkService.getReferenceLinkTitle(`#root/${note.noteId}?viewMode=attachments&attachmentId=a1`);
expect(title).toBe("Att");
+ expect(froca.getAttachment).toHaveBeenCalledWith("a1", true);
});
it("getReferenceLinkTitle returns [missing attachment] when attachment not found", async () => {
const note = buildNote({ title: "WithAtt2" });
- note.getAttachmentById = vi.fn(async () => null as any);
+ froca.getAttachment = vi.fn(async () => null);
const title = await linkService.getReferenceLinkTitle(`#root/${note.noteId}?viewMode=attachments&attachmentId=a2`);
expect(title).toBe("[missing attachment]");
});
diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.ts
index 62815ad3b1..91db292e3c 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -718,7 +718,8 @@ async function getReferenceLinkTitle(href: string) {
}
if (viewScope?.viewMode === "attachments" && viewScope?.attachmentId) {
- const attachment = await note.getAttachmentById(viewScope.attachmentId);
+ // `froca.getAttachment()` reloads the attachments when the cached list lacks this one.
+ const attachment = await froca.getAttachment(viewScope.attachmentId, true);
return attachment ? attachment.title : "[missing attachment]";
}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index c9007bd698..5ac240e2b8 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1589,7 +1589,8 @@
"editor_crashed_details_title": "Technical information",
"auto-detect-language": "Auto-detected",
"keeps-crashing": "Editing component keeps crashing. Please try restarting Trilium. If problem persists, consider creating a bug report.",
- "nothing_selected_to_cut": "Select some text first to cut it into a sub-note."
+ "nothing_selected_to_cut": "Select some text first to cut it into a sub-note.",
+ "uploading_attachment": "Uploading attachment"
},
"empty": {
"open_note_instruction": "Open a note by typing the note's title into the input below or choose a note in the tree.",
@@ -4238,6 +4239,7 @@
"ask-ai": "Ask AI…",
"ask-ai-to": "Ask AI to…",
"ask-ai-to-rewrite-the-selection-or-generate-new-content": "Ask AI to rewrite the selection or generate new content.",
+ "attach-file": "Attach file",
"box-size": "Box size",
"bulleted-list": "Bulleted list",
"card": "Card",
@@ -4357,6 +4359,7 @@
"undefined-custom-task-state": "Undefined custom task state",
"url": "URL",
"upload-an-image-from-your-device": "Upload an image from your device.",
+ "upload-files-as-attachments-and-insert-links-to-them": "Upload files as attachments and insert links to them.",
"upload-image": "Upload image",
"warning": "Warning",
"working": "Working…",
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 c4e5f5e7b2..6ef186456b 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts
@@ -6,19 +6,30 @@
* 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 { describe, expect, it, vi } from "vitest";
const showError = vi.hoisted(() => vi.fn());
const showErrorTitleAndMessage = vi.hoisted(() => vi.fn());
const showMessage = vi.hoisted(() => vi.fn());
+const showPersistent = vi.hoisted(() => vi.fn());
+const closePersistent = vi.hoisted(() => vi.fn());
vi.mock("../../../services/toast", () => ({
- default: { showError, showErrorTitleAndMessage, showMessage }
+ default: { showError, showErrorTitleAndMessage, showMessage, showPersistent, closePersistent }
+}));
+vi.mock("../../../services/i18n", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../../../services/i18n")>(),
+ t: (key: string) => key
}));
// Imported by EditableText for editor types and content styles; irrelevant (and heavy) here.
vi.mock("@triliumnext/ckeditor5", () => ({}));
-const { onNotificationInfo, onNotificationWarning } = await import("./EditableText");
+const {
+ onNotificationInfo,
+ onNotificationWarning,
+ showFileUploadProgress
+} = await import("./EditableText");
describe("onNotificationWarning", () => {
/** The payload `Notification#_showNotification` builds, with the `EventInfo` before it. */
@@ -70,3 +81,47 @@ describe("onNotificationInfo", () => {
expect(evt.stop).not.toHaveBeenCalled();
});
});
+
+describe("showFileUploadProgress", () => {
+ it("shows the progress of an upload in a toast until the upload ends", async () => {
+ vi.clearAllMocks();
+ let finish = () => {};
+ const done = new Promise<void>((resolve) => {
+ finish = () => resolve();
+ });
+ const listeners = new Map<string, () => void>();
+ const loader = {
+ id: "loader1",
+ uploadedPercent: 0,
+ on: vi.fn((event: string, callback: () => void) => listeners.set(event, callback)),
+ off: vi.fn()
+ };
+
+ const upload = { fileName: "report.pdf", loader, done } as unknown as FileUploadData;
+
+ showFileUploadProgress({}, upload);
+ expect(showPersistent).toHaveBeenLastCalledWith(expect.objectContaining({
+ id: "file-upload-loader1",
+ title: "editable_text.uploading_attachment",
+ message: "report.pdf",
+ progress: 0,
+ dismissible: false
+ }));
+
+ loader.uploadedPercent = 40;
+ listeners.get("change:uploadedPercent")?.();
+ expect(showPersistent).toHaveBeenLastCalledWith(expect.objectContaining({
+ id: "file-upload-loader1",
+ progress: 0.4
+ }));
+ expect(closePersistent).not.toHaveBeenCalled();
+
+ finish();
+ await done;
+ expect(closePersistent).toHaveBeenCalledWith("file-upload-loader1");
+ expect(loader.off).toHaveBeenCalledWith(
+ "change:uploadedPercent",
+ listeners.get("change:uploadedPercent")
+ );
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
index e03c891f12..86e6711257 100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@ -1,7 +1,13 @@
import "./EditableText.css";
import "./LinkEmbed.css";
-import { CKTextEditor, EditorWatchdog, SnippetDefinition } from "@triliumnext/ckeditor5";
+import {
+ CKTextEditor,
+ EditorWatchdog,
+ type FileUploadData,
+ type FileUploadEvent,
+ SnippetDefinition
+} from "@triliumnext/ckeditor5";
import { deferred } from "@triliumnext/commons";
import { createPortal } from "preact/compat";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
@@ -492,6 +498,9 @@ export default function EditableText({ note, parentComponent, ntxId, noteContext
setupImageOpening(containerRef.current, false);
}
+ editor.plugins.get("FileUploadEditing")
+ .on<FileUploadEvent>("upload", showFileUploadProgress);
+
initialized.current.resolve();
// Restore the data, either on the first render or if the editor crashes.
// We are not using CKEditor's built-in watch dog content, instead we are using the data we store regularly in the spaced update (see `dataSaved`).
@@ -651,3 +660,27 @@ export function onNotificationWarning(evt: NotificationEventInfo, data: Notifica
export function onNotificationInfo(_evt: NotificationEventInfo, data: NotificationEventData) {
toast.showMessage(data.message);
}
+
+/**
+ * Shows the progress of a file attachment upload in a toast until the upload ends.
+ *
+ * Exported for testing.
+ */
+export function showFileUploadProgress(_evt: unknown, { fileName, loader, done }: FileUploadData) {
+ const id = `file-upload-${loader.id}`;
+ const showProgress = () => toast.showPersistent({
+ id,
+ icon: "bx bx-paperclip",
+ title: t("editable_text.uploading_attachment"),
+ message: fileName,
+ progress: loader.uploadedPercent / 100,
+ dismissible: false
+ });
+
+ showProgress();
+ loader.on("change:uploadedPercent", showProgress);
+ void done.then(() => {
+ loader.off("change:uploadedPercent", showProgress);
+ toast.closePersistent(id);
+ });
+}
diff --git a/apps/client/src/widgets/type_widgets/text/toolbar.ts b/apps/client/src/widgets/type_widgets/text/toolbar.ts
index 0dc2dc64ec..0f6c272eca 100644
--- a/apps/client/src/widgets/type_widgets/text/toolbar.ts
+++ b/apps/client/src/widgets/type_widgets/text/toolbar.ts
@@ -94,6 +94,7 @@ export function buildClassicToolbar(multilineToolbar: boolean, aiAssistant: bool
// width.
...(aiAssistant ? ["aiAssistant"] : []),
"imageUpload",
+ "fileUpload",
"blockQuote",
"admonition",
"insertTable",
@@ -167,6 +168,7 @@ export function buildFloatingToolbar(aiAssistant: boolean) {
"todoList",
"|",
"imageUpload",
+ "fileUpload",
"blockQuote",
"admonition",
"codeBlock",
diff --git a/apps/server/internal.openapi.yaml b/apps/server/internal.openapi.yaml
index 92a186789b..1fd5309b9f 100644
--- a/apps/server/internal.openapi.yaml
+++ b/apps/server/internal.openapi.yaml
@@ -1405,6 +1405,14 @@ paths:
operationId: uploadAttachment
parameters:
- $ref: '#/components/parameters/noteId'
+ - name: role
+ in: query
+ description: >-
+ `file` stores a picture as a file attachment and answers with a link to it, instead of
+ an image URL.
+ schema:
+ type: string
+ enum: [file]
requestBody:
required: true
content:
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 d62a507562..5e2b041400 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
@@ -33,6 +33,24 @@
</ul>
<p>The system attachments are displayed at the end of the attachments list,
in a dedicated section (<em>Generated by Trilium</em>).</p>
+<h2>Attaching files from a text note</h2>
+<p>To attach files to a&nbsp;<a class="reference-link" href="#root/_help_iPIMuisry3hd">Text</a>&nbsp;note
+ and link them in its content, press the <span class="tn-icon cke cke-paper-clip"></span> <em>Attach file</em> button
+ in the&nbsp;<a class="reference-link" href="#root/_help_nRhnJkTT8cPs">Formatting toolbar</a>,
+ next to the <span class="tn-icon cke cke-image-upload"></span> image upload
+ button, and select one or more files. The same action is available as <em>Attach file</em> in
+ the&nbsp;<a class="reference-link" href="#root/_help_ZlN4nump6EbW">Slash Commands</a>.</p>
+<ul>
+ <li>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.</li>
+ <li>While a file uploads, its link shows the file name and a toast shows the
+ progress.</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&nbsp;<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 the
+ text also attaches it and inserts a link to it.</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/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Images.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Images.html
index bc06ea7603..c5f88dfd1d 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Images.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Images.html
@@ -13,6 +13,10 @@
for the <em>Insert image</em> icon.</li>
<li>You can also copy and paste an image from web (see section below).</li>
</ul>
+<aside class="admonition tip">
+ <p>To link a picture instead of displaying it, attach it with the <span class="tn-icon cke cke-paper-clip"></span> <em>Attach file</em> button.
+ See&nbsp;<a class="reference-link" href="#root/_help_0vhv7lsOLy82">Attachments</a>.</p>
+</aside>
<h2>Clipboard &amp; automatic download of images</h2>
<p>Trilium has a special handling for images copied to and pasted from the
clipboard.</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 48f55e1933..dfff7eab18 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
@@ -19,6 +19,16 @@ There are two different types of attachment:
The system attachments are displayed at the end of the attachments list, in a dedicated section (_Generated by Trilium_).
+## Attaching files from a text note
+
+To attach files to a <a class="reference-link" href="../../Note%20Types/Text.md">Text</a> note and link them in its content, press the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button in the <a class="reference-link" href="../../Note%20Types/Text/Formatting%20toolbar.md">Formatting toolbar</a>, next to the <span class="tn-icon cke cke-image-upload"></span> image upload button, and select one or more files. The same action is available as _Attach file_ in the <a class="reference-link" href="../../Note%20Types/Text/Slash%20Commands.md">Slash Commands</a>.
+
+* 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>).
+
+Dragging a file that is not a picture from the file explorer onto the text also attaches it and inserts a link to it.
+
## 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/docs/User Guide/User Guide/Note Types/Text/Images.md b/docs/User Guide/User Guide/Note Types/Text/Images.md
index 4bbcd3c5eb..1e97e3f525 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Images.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Images.md
@@ -11,6 +11,9 @@ To add an image to the note:
* Alternatively, from the <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a> look for the _Insert image_ icon.
* You can also copy and paste an image from web (see section below).
+> [!TIP]
+> To link a picture instead of displaying it, attach it with the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. See <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/Notes/Attachments.md">Attachments</a>.
+
## Clipboard & automatic download of images
Trilium has a special handling for images copied to and pasted from the clipboard.
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 836ccb0b2f..a0b96a52bc 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -13,6 +13,7 @@ export { default as EditorWatchdog } from "./custom_watchdog";
export { CHAT_INPUT_PLUGINS, MEMO_PLUGINS } from "./plugins.js";
export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, TextTransformationConfig, TextTypingTransformationDescription, WatchdogConfig, WatchdogState } from "ckeditor5";
export type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";
+export type { FileUploadData, FileUploadEvent } from "./plugins/file_upload/fileuploadediting.js";
export type { PasteTarget } from "./plugins/cuttonote.js";
export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";
export type { TriliumMentionFeed } from "./plugins/mention/types.js";
@@ -25,6 +26,7 @@ export { MESSAGE_KEY_PREFIX, MESSAGE_OVERRIDES, slugify } from "./messages.js";
export * from "./utils.js";
// Import with sideffects to ensure that type augmentations are present.
+import "./plugins/file_upload/uploadfileplugin.js";
import "./plugins/math/math.js";
import "./plugins/mermaid/mermaid.js";
import "./plugins/table_context_menu.js";
diff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts
new file mode 100644
index 0000000000..4738e19e3b
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts
@@ -0,0 +1,65 @@
+import {
+ ClassicEditor,
+ Command,
+ Essentials,
+ FileDialogButtonView,
+ IconPaperClip,
+ Paragraph
+} from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import FileUploadUI from "./file_upload_ui.js";
+
+describe("FileUploadUI", () => {
+ let editor: ClassicEditor;
+ let command: Command;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([Essentials, Paragraph, FileUploadUI]);
+ command = new Command(editor);
+ command.refresh();
+ editor.commands.add("fileUpload", command);
+ });
+
+ function createButton() {
+ const button = editor.ui.componentFactory.create("fileUpload");
+ if (!(button instanceof FileDialogButtonView)) {
+ throw new Error("Expected a file dialog button.");
+ }
+ return button;
+ }
+
+ it("registers a paperclip button that picks any number of files of any type", () => {
+ const button = createButton();
+
+ expect(button.label).toBe("Attach file");
+ expect(button.icon).toBe(IconPaperClip);
+ expect(button.tooltip).toBe(true);
+ expect(button.allowMultipleFiles).toBe(true);
+ expect(button.acceptedType).toBeUndefined();
+ });
+
+ it("follows the enabled state of the `fileUpload` command", () => {
+ const button = createButton();
+ expect(button.isEnabled).toBe(true);
+
+ command.forceDisabled("spec");
+ expect(button.isEnabled).toBe(false);
+ });
+
+ it("attaches the picked files and returns the focus to the editor", () => {
+ const button = createButton();
+ const execute = vi.spyOn(editor, "execute").mockImplementation(() => undefined);
+ const focus = vi.spyOn(editor.editing.view, "focus");
+ const files = [
+ new File(["a"], "a.pdf", { type: "application/pdf" }),
+ new File(["b"], "b.png", { type: "image/png" })
+ ];
+
+ button.fire("done", files);
+
+ expect(execute).toHaveBeenCalledWith("fileUpload", { file: files });
+ expect(focus).toHaveBeenCalled();
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts
new file mode 100644
index 0000000000..e59f15fa9c
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts
@@ -0,0 +1,39 @@
+import {
+ FileDialogButtonView,
+ IconPaperClip,
+ Plugin,
+ type FileInputViewDoneEvent
+} from "ckeditor5";
+
+/** Registers the `fileUpload` toolbar button, which attaches the picked files and links them. */
+export default class FileUploadUI extends Plugin {
+ static get pluginName() {
+ return "FileUploadUI" as const;
+ }
+
+ init() {
+ const editor = this.editor;
+
+ editor.ui.componentFactory.add("fileUpload", (locale) => {
+ const button = new FileDialogButtonView(locale);
+ button.set({
+ label: editor.t("Attach file"),
+ icon: IconPaperClip,
+ tooltip: true,
+ allowMultipleFiles: true
+ });
+
+ const command = editor.commands.get("fileUpload");
+ if (command) {
+ button.bind("isEnabled").to(command);
+ }
+
+ button.on<FileInputViewDoneEvent>("done", (_evt, files) => {
+ editor.execute("fileUpload", { file: Array.from(files) });
+ editor.editing.view.focus();
+ });
+
+ return button;
+ });
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
index 2464babd92..2df3ed2ad6 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts
@@ -8,11 +8,13 @@ import {
toWidget,
viewToModelPositionOutsideModelElement,
_getModelData as getModelData,
- _setModelData as setModelData
+ _setModelData as setModelData,
+ type FileLoader
} from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
+import { isFileAttachmentUpload } from "../uploadimage.js";
import FileUploadCommand from "./fileuploadcommand.js";
/**
@@ -33,7 +35,7 @@ class ReferenceSchema extends Plugin {
allowWhere: "$text",
isInline: true,
isObject: true,
- allowAttributes: ["href", "uploadId", "uploadStatus"]
+ allowAttributes: ["href", "uploadId", "uploadStatus", "uploadFileName"]
});
// Editing downcast: the mapper needs a real view element for every model element.
@@ -102,105 +104,60 @@ describe("FileUploadCommand", () => {
// refresh()
// -----------------------------------------------------------------
- it("is always enabled regardless of the selection position", () => {
- setModelData(editor.model, "<paragraph>[]foo</paragraph>");
+ it("is enabled only where the schema allows a reference link", () => {
+ const schema = editor.model.schema;
+ schema.register("plainBlock", { inheritAllFrom: "$block" });
+ schema.addChildCheck((context, definition) =>
+ context.endsWith("plainBlock") && definition.name === "reference" ? false : undefined
+ );
+ editor.conversion.elementToElement({ model: "plainBlock", view: "pre" });
const command = editor.commands.get("fileUpload");
- command?.refresh();
- expect(command?.isEnabled).toBe(true);
- });
- it("remains enabled after refresh is called", () => {
- const command = editor.commands.get("fileUpload");
- command?.refresh();
+ setModelData(editor.model, "<paragraph>[]foo</paragraph>");
expect(command?.isEnabled).toBe(true);
+
+ setModelData(editor.model, "<plainBlock>[]foo</plainBlock>");
+ expect(command?.isEnabled).toBe(false);
});
// -----------------------------------------------------------------
- // execute() — happy path (single file)
+ // execute()
// -----------------------------------------------------------------
- it("inserts a reference placeholder for a single file", () => {
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- const file = new File(["content"], "test.txt", { type: "text/plain" });
- editor.execute("fileUpload", { file: [file] });
-
- const modelData = getModelData(editor.model);
- expect(modelData).toContain("reference");
- });
+ it("inserts a placeholder per file, named after it, with a space after each link", () => {
+ setModelData(editor.model, "<paragraph>foo[]</paragraph>");
- it("inserts a reference placeholder with an uploadId attribute", () => {
- setModelData(editor.model, "<paragraph>[]</paragraph>");
+ editor.execute("fileUpload", {
+ file: [
+ new File(["a"], "a.txt", { type: "text/plain" }),
+ new File(["b"], "b.png", { type: "image/png" })
+ ]
+ });
- const file = new File(["content"], "test.txt", { type: "text/plain" });
- editor.execute("fileUpload", { file: [file] });
-
- // Walk the model root and find the inserted reference element.
- const root = editor.model.document.getRoot();
- let foundReference = false;
- if (root) {
- for (const child of Array.from(root.getChildren())) {
- if (child.is("element")) {
- for (const node of Array.from(child.getChildren())) {
- if (node.is("element", "reference")) {
- foundReference = true;
- // href is set to '' and uploadId is a loader id (number/string).
- expect(node.getAttribute("href")).toBe("");
- expect(node.getAttribute("uploadId")).toBeDefined();
- }
- }
- }
- }
- }
- expect(foundReference).toBe(true);
+ expect(getModelData(editor.model)).toMatch(new RegExp(
+ "^<paragraph>foo" +
+ "<reference href=\"\" uploadFileName=\"a.txt\" uploadId=\"\\w+\"></reference> " +
+ "<reference href=\"\" uploadFileName=\"b.png\" uploadId=\"\\w+\"></reference> " +
+ "\\[\\]</paragraph>$"
+ ));
});
- it("inserts a space text node after the reference placeholder", () => {
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- const file = new File(["x"], "x.txt", { type: "text/plain" });
- editor.execute("fileUpload", { file: [file] });
-
- // The model data string representation should show that a text
- // node with a space follows the reference element.
- const modelStr = getModelData(editor.model);
- // The space is inserted by writer.insertText(' ', placeholder, 'after').
- expect(modelStr).toContain(" ");
- });
-
- // -----------------------------------------------------------------
- // execute() — multiple files
- // -----------------------------------------------------------------
-
- it("inserts one reference placeholder per file when multiple files are passed", () => {
+ it("marks the loader of every file as a file attachment upload", () => {
setModelData(editor.model, "<paragraph>[]</paragraph>");
+ const createLoaderSpy = vi.spyOn(editor.plugins.get(FileRepository), "createLoader");
const files = [
- new File(["a"], "a.txt", { type: "text/plain" }),
- new File(["b"], "b.txt", { type: "text/plain" })
+ new File(["1"], "one.txt", { type: "text/plain" }),
+ new File(["2"], "two.png", { type: "image/png" })
];
editor.execute("fileUpload", { file: files });
- const root = editor.model.document.getRoot();
- let referenceCount = 0;
- if (root) {
- for (const child of Array.from(root.getChildren())) {
- if (child.is("element")) {
- for (const node of Array.from(child.getChildren())) {
- if (node.is("element", "reference")) {
- referenceCount++;
- }
- }
- }
- }
+ expect(createLoaderSpy.mock.calls).toEqual([ [ files[0] ], [ files[1] ] ]);
+ for (const { value } of createLoaderSpy.mock.results) {
+ expect(isFileAttachmentUpload(value as FileLoader)).toBe(true);
}
- expect(referenceCount).toBe(2);
});
- // -----------------------------------------------------------------
- // execute() — empty file array
- // -----------------------------------------------------------------
-
it("does not modify the model when an empty file array is passed", () => {
setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");
const before = getModelData(editor.model);
@@ -210,10 +167,6 @@ describe("FileUploadCommand", () => {
expect(getModelData(editor.model)).toBe(before);
});
- // -----------------------------------------------------------------
- // uploadFile() — no loader returned (no upload adapter configured)
- // -----------------------------------------------------------------
-
it("does not throw and does not insert anything when createLoader returns null", () => {
// Remove the upload adapter so createLoader returns null.
(editor.plugins.get(FileRepository) as unknown as { createUploadAdapter: unknown }).createUploadAdapter = undefined;
@@ -222,31 +175,7 @@ describe("FileUploadCommand", () => {
const before = getModelData(editor.model);
const file = new File(["x"], "x.txt", { type: "text/plain" });
- // Should not throw even without an upload adapter.
expect(() => editor.execute("fileUpload", { file: [file] })).not.toThrow();
-
- // The model should be unchanged (the early-return guard was hit).
expect(getModelData(editor.model)).toBe(before);
});
-
- // -----------------------------------------------------------------
- // Spy: FileRepository.createLoader is actually called
- // -----------------------------------------------------------------
-
- it("calls FileRepository.createLoader for each file", () => {
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- const fileRepository = editor.plugins.get(FileRepository);
- const createLoaderSpy = vi.spyOn(fileRepository, "createLoader");
-
- const files = [
- new File(["1"], "one.txt", { type: "text/plain" }),
- new File(["2"], "two.txt", { type: "text/plain" })
- ];
- editor.execute("fileUpload", { file: files });
-
- expect(createLoaderSpy).toHaveBeenCalledTimes(2);
- expect(createLoaderSpy).toHaveBeenCalledWith(files[0]);
- expect(createLoaderSpy).toHaveBeenCalledWith(files[1]);
- });
});
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
index 56f9b76b0a..84add026fa 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts
@@ -1,52 +1,52 @@
-import { Command, FileRepository, Model, type ModelNodeAttributes, type ModelWriter } from "ckeditor5";
+import { Command, FileRepository, type Model, type ModelWriter } from "ckeditor5";
-interface FileUploadOpts {
- file: File[];
-}
+import { uploadAsFileAttachment } from "../uploadimage.js";
-export default class FileUploadCommand extends Command {
- override refresh() {
- this.isEnabled = true;
- }
-
- /**
- * Executes the command.
- *
- * @fires execute
- * @param {Object} options Options for the executed command.
- * @param {File|Array.<File>} options.file The file or an array of files to upload.
- */
- override execute( options: FileUploadOpts ) {
- const editor = this.editor;
- const model = editor.model;
-
- const fileRepository = editor.plugins.get( FileRepository );
-
- model.change( writer => {
- const filesToUpload = options.file;
- for ( const file of filesToUpload ) {
- uploadFile( writer, model, fileRepository, file );
- }
- } );
- }
+export interface FileUploadOptions {
+ file: File[];
}
/**
- * Handles uploading single file.
+ * 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.
*/
-function uploadFile( writer: ModelWriter, model: Model, fileRepository: FileRepository, file: File ) {
- const loader = fileRepository.createLoader( file );
-
- // Do not throw when upload adapter is not set. FileRepository will log an error anyway.
- if ( !loader ) {
- return;
- }
-
- insertFileLink( writer, model, { href: '', uploadId: loader.id }, file );
+export default class FileUploadCommand extends Command {
+ override refresh() {
+ const model = this.editor.model;
+ const position = model.document.selection.getFirstPosition();
+
+ this.isEnabled = !!position && model.schema.checkChild(position, "reference");
+ }
+
+ override execute({ file: files }: FileUploadOptions) {
+ const model = this.editor.model;
+ const fileRepository = this.editor.plugins.get(FileRepository);
+
+ model.change((writer) => {
+ for (const file of files) {
+ // `createLoader()` logs an error and returns null when no upload adapter is set.
+ const loader = fileRepository.createLoader(file);
+ if (!loader) {
+ continue;
+ }
+
+ uploadAsFileAttachment(loader);
+ insertPlaceholder(writer, model, loader.id, file.name);
+ }
+ });
+ }
}
-function insertFileLink( writer: ModelWriter, model: Model, attributes: ModelNodeAttributes = {}, file: File ) {
- const placeholder = writer.createElement( 'reference', attributes );
- model.insertContent( placeholder, model.document.selection );
- writer.insertText( ' ', placeholder, 'after' );
+/** Inserts the link `FileUploadEditing` completes once the upload ends, and a space after it. */
+function insertPlaceholder(writer: ModelWriter, model: Model, uploadId: string, fileName: string) {
+ const placeholder = writer.createElement("reference", {
+ href: "",
+ uploadId,
+ uploadFileName: fileName
+ });
+ model.insertContent(placeholder, model.document.selection);
+
+ const afterPlaceholder = writer.createPositionAfter(placeholder);
+ writer.insertText(" ", afterPlaceholder);
+ writer.setSelection(afterPlaceholder.getShiftedBy(1));
}
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts
index cdd33c9336..c2ba04fc59 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts
@@ -20,7 +20,11 @@ import {
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
-import FileUploadEditing, { isHtmlIncluded } from "./fileuploadediting.js";
+import FileUploadEditing, {
+ isHtmlIncluded,
+ type FileUploadData,
+ type FileUploadEvent
+} from "./fileuploadediting.js";
describe("FileUploadEditing", () => {
let editor: ClassicEditor;
@@ -197,25 +201,61 @@ describe("FileUploadEditing", () => {
// change post-fixer + _readAndUpload — happy path
// -----------------------------------------------------------------
- it("reads, uploads and completes a placeholder, then reloads the data", async () => {
+ it("completes a placeholder in place and keeps the undo history", async () => {
const controls = installUploadAdapter(editor);
- const fileRepository = editor.plugins.get(FileRepository);
+ const setDataSpy = vi.spyOn(editor, "setData");
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
const file = new File(["content"], "x.txt", { type: "text/plain" });
- const loader = fileRepository.createLoader(file);
- const uploadId = loader?.id;
+ editor.execute("fileUpload", { file: [ file ] });
+ await waitFor(() => controls.uploadCalled());
+ controls.resolveUpload({ default: "#root/abc" });
- insertReference(uploadId);
+ // Long enough for any delayed step of the upload chain.
+ await new Promise((res) => setTimeout(res, 250));
- await waitFor(() => controls.uploadCalled());
+ expect(getModelData(editor.model))
+ .toBe("<paragraph><reference href=\"#root/abc\"></reference> []</paragraph>");
+ expect(setDataSpy).not.toHaveBeenCalled();
- const setDataSpy = vi.spyOn(editor, "setData");
- controls.resolveUpload({ default: "api/attachments/done/download" });
+ // Undo takes back the inserted link, not the completion of its upload.
+ editor.execute("undo");
+ expect(getModelData(editor.model)).toBe("<paragraph>[]</paragraph>");
+ });
- // Wait for the .then chain plus the 100ms froca delay.
- await new Promise((res) => setTimeout(res, 250));
+ it("announces each upload and settles `done` whatever the outcome", async () => {
+ const controls = installUploadAdapter(editor);
+ vi.spyOn(editor.plugins.get(Notification), "showWarning").mockImplementation(() => {});
+ const uploads: FileUploadData[] = [];
+ editor.plugins.get(FileUploadEditing).on<FileUploadEvent>("upload", (_evt, upload) => {
+ uploads.push(upload);
+ });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
- expect(setDataSpy).toHaveBeenCalled();
+ for (const outcome of [ "resolve", "reject" ]) {
+ editor.execute("fileUpload", { file: [ new File(["content"], `${outcome}.pdf`) ] });
+ await waitFor(() => uploads.length > 0 && controls.uploadCalled());
+
+ const upload = uploads.pop();
+ expect(upload?.fileName).toBe(`${outcome}.pdf`);
+ expect(upload?.loader).toBe(editor.plugins.get(FileRepository).loaders.last);
+
+ let isDone = false;
+ void upload?.done.then(() => {
+ isDone = true;
+ });
+ await flushAsync();
+ expect(isDone).toBe(false);
+
+ if (outcome === "resolve") {
+ controls.resolveUpload({ default: "#root/abc" });
+ } else {
+ setLoaderStatus(upload?.loader ?? null, "error");
+ controls.rejectUpload("boom");
+ }
+ await flushAsync();
+ expect(isDone).toBe(true);
+ }
});
it("aborts the loader when the placeholder is inserted into the graveyard", () => {
@@ -507,7 +547,7 @@ class ReferenceSchema extends Plugin {
allowWhere: "$text",
isInline: true,
isObject: true,
- allowAttributes: ["href", "uploadId", "uploadStatus"]
+ allowAttributes: ["href", "uploadId", "uploadStatus", "uploadFileName"]
});
conversion.for("editingDowncast").elementToElement({
diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts
index efd428957f..1089e2756b 100644
--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts
@@ -1,6 +1,29 @@
-import { Clipboard, FileRepository, Notification, Plugin, type Editor, type FileLoader, type ModelItem, type ViewRange } from 'ckeditor5';
+import {
+ Clipboard,
+ FileRepository,
+ Notification,
+ Plugin,
+ type Editor,
+ type FileLoader,
+ type ModelItem,
+ type ViewRange
+} from 'ckeditor5';
import FileUploadCommand from './fileuploadcommand';
+/** A file attachment upload, announced by the `upload` event of `FileUploadEditing`. */
+export interface FileUploadData {
+ fileName: string;
+ /** Reports the progress of the upload in `uploadedPercent`. */
+ loader: FileLoader;
+ /** Resolves when the upload ends, whether it succeeded or not. */
+ done: Promise<void>;
+}
+
+export type FileUploadEvent = {
+ name: 'upload';
+ args: [ FileUploadData ];
+};
+
export default class FileUploadEditing extends Plugin {
static get requires() {
@@ -37,7 +60,7 @@ export default class FileUploadEditing extends Plugin {
return;
}
- const files = Array.from( data.dataTransfer.files );
+ const files: File[] = Array.from( data.dataTransfer.files );
editor.model.change( writer => {
// Set selection to paste target.
@@ -105,35 +128,38 @@ export default class FileUploadEditing extends Plugin {
const fileRepository = editor.plugins.get( FileRepository );
const notification = editor.plugins.get( Notification );
- model.enqueueChange(writer => {
+ // The upload's changes are not undoable, so undo removes the inserted link instead.
+ model.enqueueChange( { isUndoable: false }, writer => {
writer.setAttribute( 'uploadStatus', 'reading', fileElement );
} );
+ let finish = () => {};
+ const done = new Promise<void>( resolve => {
+ finish = () => resolve();
+ } );
+ this.fire<FileUploadEvent>( 'upload', {
+ fileName: String( fileElement.getAttribute( 'uploadFileName' ) ?? '' ),
+ loader,
+ done
+ } );
+
return loader.read()
.then( () => {
const promise = loader.upload();
- model.enqueueChange(writer => {
+ model.enqueueChange( { isUndoable: false }, writer => {
writer.setAttribute( 'uploadStatus', 'uploading', fileElement );
} );
return promise;
} )
.then( data => {
- model.enqueueChange(writer => {
- writer.setAttributes( { uploadStatus: 'complete', href: data.default }, fileElement );
+ model.enqueueChange( { isUndoable: false }, writer => {
+ writer.setAttribute( 'href', data.default, fileElement );
} );
clean();
-
- // wait a bit so that froca has time to load the changes
- return new Promise(res => setTimeout(res, 100));
} )
- .then(() => {
- // we're correctly updating the model, but the view remains broken,
- // hack around it is to force CKEditor to reload the now updated HTML
- editor.setData(editor.getData());
- })
.catch( error => {
// If status is not 'error' nor 'aborted' - throw error, because it means that something else went wrong,
// it might be a generic error, and it would be real pain to find what is going on.
@@ -152,15 +178,17 @@ export default class FileUploadEditing extends Plugin {
clean();
// Permanently remove file from insertion batch.
- model.enqueueChange(writer => {
+ model.enqueueChange( { isUndoable: false }, writer => {
writer.remove( fileElement );
} );
- } );
+ } )
+ .finally( finish );
function clean() {
- model.enqueueChange(writer => {
+ model.enqueueChange( { isUndoable: false }, writer => {
writer.removeAttribute( 'uploadId', fileElement );
writer.removeAttribute( 'uploadStatus', fileElement );
+ writer.removeAttribute( 'uploadFileName', fileElement );
} );
fileRepository.destroyLoader( loader );
diff --git a/packages/ckeditor5/src/plugins/file_upload/uploadfileplugin.spec.ts b/packages/ckeditor5/src/plugins/file_upload/uploadfileplugin.spec.ts
index 6499bb76dc..5f7f937be5 100644
--- a/packages/ckeditor5/src/plugins/file_upload/uploadfileplugin.spec.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/uploadfileplugin.spec.ts
@@ -2,6 +2,8 @@ import { ClassicEditor, Essentials, Paragraph } from "ckeditor5";
import { beforeEach, describe, expect, it } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
+import FileUploadUI from "./file_upload_ui.js";
+import FileUploadEditing from "./fileuploadediting.js";
import Uploadfileplugin from "./uploadfileplugin.js";
describe("Uploadfileplugin", () => {
@@ -19,10 +21,9 @@ describe("Uploadfileplugin", () => {
expect(Uploadfileplugin.pluginName).toBe("fileUploadPlugin");
});
- it("declares FileUploadEditing as a required plugin", () => {
- const requires = Uploadfileplugin.requires;
- expect(requires).toHaveLength(1);
- const FileUploadEditing = requires[0];
- expect(editor.plugins.has(FileUploadEditing as never)).toBe(true);
+ it("loads the editing and the UI plugins", () => {
+ expect(Uploadfileplugin.requires).toEqual([ FileUploadEditing, FileUploadUI ]);
+ expect(editor.plugins.has(FileUploadEditing)).toBe(true);
+ expect(editor.plugins.has(FileUploadUI)).toBe(true);
});
});
diff --git a/packages/ckeditor5/src/plugins/file_upload/uploadfileplugin.ts b/packages/ckeditor5/src/plugins/file_upload/uploadfileplugin.ts
index 0c9caf0259..711e84a73d 100644
--- a/packages/ckeditor5/src/plugins/file_upload/uploadfileplugin.ts
+++ b/packages/ckeditor5/src/plugins/file_upload/uploadfileplugin.ts
@@ -1,12 +1,26 @@
import { Plugin } from "ckeditor5";
-import FileUploadEditing from "./fileuploadediting";
+
+import FileUploadUI from "./file_upload_ui.js";
+import type FileUploadCommand from "./fileuploadcommand.js";
+import FileUploadEditing from "./fileuploadediting.js";
export default class Uploadfileplugin extends Plugin {
- static get requires() {
- return [ FileUploadEditing ];
- }
+ static get requires() {
+ return [ FileUploadEditing, FileUploadUI ] as const;
+ }
+
+ static get pluginName() {
+ return "fileUploadPlugin" as const;
+ }
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ FileUploadEditing: FileUploadEditing;
+ [FileUploadUI.pluginName]: FileUploadUI;
+ }
- static get pluginName() {
- return 'fileUploadPlugin';
- }
+ interface CommandsMap {
+ fileUpload: FileUploadCommand;
+ }
}
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
index 98e8b2e887..adbaef831e 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
@@ -282,16 +282,6 @@ describe("TriliumSlashCommands", () => {
return definition;
}
- function filesOf(...files: File[]): FileList {
- const transfer = new DataTransfer();
-
- for (const file of files) {
- transfer.items.add(file);
- }
-
- return transfer.files;
- }
-
it("is offered only where an `uploadImage` command is registered", async () => {
// The entry runs a file picker rather than naming the command, so `commandName` cannot
// gate it and `isEnabled` has to.
@@ -632,6 +622,7 @@ describe("buildTriliumSlashCommands", () => {
[ "collapsible", "Collapsible block", "collapsible" ],
[ "footnote", "Footnote", "InsertFootnote" ],
[ "internal-link", "Internal link", INTERNAL_LINK_COMMAND ],
+ [ "attach-file", "Attach file", "fileUpload" ],
[ "include-note", "Include note", INCLUDE_NOTE_COMMAND ],
[ "page-break", "Page break", "pageBreak" ],
[ "markdown-import", "Markdown import", MARKDOWN_IMPORT_COMMAND ],
@@ -649,6 +640,30 @@ describe("buildTriliumSlashCommands", () => {
expect(entry.icon).toContain("<svg");
});
+ it("attach-file attaches every file picked, of any type, and returns the focus", () => {
+ const execute = vi.spyOn(editor, "execute").mockReturnValue(undefined);
+ const focus = vi.spyOn(editor.editing.view, "focus");
+ const click = vi.spyOn(HTMLInputElement.prototype, "click").mockReturnValue(undefined);
+
+ definition("attach-file").execute?.(editor);
+
+ expect(click).toHaveBeenCalledOnce();
+ const input = click.mock.instances[0] as HTMLInputElement;
+ expect(input.type).toBe("file");
+ expect(input.accept).toBe("");
+ expect(input.multiple).toBe(true);
+ expect(input.isConnected).toBe(true);
+
+ const pdf = new File([ "" ], "a.pdf", { type: "application/pdf" });
+ const png = new File([ "" ], "b.png", { type: "image/png" });
+ input.files = filesOf(pdf, png);
+ input.dispatchEvent(new Event("change"));
+
+ expect(execute).toHaveBeenCalledWith("fileUpload", { file: [ pdf, png ] });
+ expect(focus).toHaveBeenCalled();
+ expect(input.isConnected).toBe(false);
+ });
+
it.each([
[ "align-left", "left" ],
[ "align-center", "center" ],
@@ -922,3 +937,14 @@ describe("buildTriliumSlashCommands", () => {
expect(definition("page-break").title).toBe("Întrerupere de pagină");
});
});
+
+/** Builds the `FileList` a file input holds after the user picks `files`. */
+function filesOf(...files: File[]): FileList {
+ const transfer = new DataTransfer();
+
+ for (const file of files) {
+ transfer.items.add(file);
+ }
+
+ return transfer.files;
+}
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
index a1ab08f475..fe2a44b8c3 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
@@ -18,6 +18,7 @@ import {
IconNumberedList,
IconOutdent,
IconPageBreak,
+ IconPaperClip,
IconParagraph,
IconQuote,
IconTable,
@@ -361,6 +362,18 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitio
icon: internalLinkIcon,
commandName: INTERNAL_LINK_COMMAND
},
+ {
+ id: "attach-file",
+ title: t("Attach file"),
+ description: t("Upload files as attachments and insert links to them."),
+ aliases: [ "attachment", "upload" ],
+ icon: IconPaperClip,
+ commandName: "fileUpload",
+ execute: (target: Editor) => pickFiles("", (files) => {
+ target.execute("fileUpload", { file: files });
+ target.editing.view.focus();
+ })
+ },
{
id: "math",
title: t("Math equation"),
@@ -696,32 +709,43 @@ function buildImageUploadCommand(editor: Editor): SlashCommandDefinition {
execute(target) {
const imageTypes = target.config.get("image.upload.types") ?? [];
const imageTypesRegExp = createImageTypeRegExp(imageTypes);
- const input = document.createElement("input");
-
- input.type = "file";
- input.accept = imageTypes.map((type) => `image/${type}`).join(",");
- input.multiple = true;
- input.style.display = "none";
+ const accept = imageTypes.map((type) => `image/${type}`).join(",");
- input.addEventListener("change", () => {
- /* v8 ignore next -- `files` is only null on an input that is not of type `file` */
- const imagesToUpload = Array.from(input.files ?? [])
- .filter((file) => imageTypesRegExp.test(file.type));
+ pickFiles(accept, (files) => {
+ const imagesToUpload = files.filter((file) => imageTypesRegExp.test(file.type));
if (imagesToUpload.length) {
target.execute("uploadImage", { file: imagesToUpload });
target.editing.view.focus();
}
-
- input.remove();
- }, { once: true });
-
- document.body.appendChild(input);
- input.click();
+ });
}
};
}
+/**
+ * Opens the browser's file picker and passes the picked files to `onPick`.
+ *
+ * @param accept the `accept` attribute of the file input, empty for any type.
+ */
+function pickFiles(accept: string, onPick: (files: File[]) => void) {
+ const input = document.createElement("input");
+
+ input.type = "file";
+ input.accept = accept;
+ input.multiple = true;
+ input.style.display = "none";
+
+ input.addEventListener("change", () => {
+ /* v8 ignore next -- `files` is only null on an input that is not of type `file` */
+ onPick(Array.from(input.files ?? []));
+ input.remove();
+ }, { once: true });
+
+ document.body.appendChild(input);
+ input.click();
+}
+
// Source: https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-image/src/imageupload/utils.ts
function createImageTypeRegExp(types: string[]): RegExp {
// Sanitize the MIME type name which can include: "+", "-" or ".".
diff --git a/packages/ckeditor5/src/plugins/referencelink.spec.ts b/packages/ckeditor5/src/plugins/referencelink.spec.ts
index 5bcb6e40da..44a281b9af 100644
--- a/packages/ckeditor5/src/plugins/referencelink.spec.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.spec.ts
@@ -185,6 +185,34 @@ describe("ReferenceLink", () => {
expect(loadReferenceLinkTitle.mock.calls[0]?.[1]).toBe("#root/noteAbc");
});
+ it("shows a placeholder's file name, then redraws it as a titled link once uploaded", () => {
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ const reference = editor.model.change((writer) => {
+ const element = writer.createElement("reference", {
+ href: "",
+ uploadId: "u1",
+ uploadFileName: "report.pdf"
+ });
+ editor.model.insertContent(element);
+ return element;
+ });
+ const findAnchor = () =>
+ editor.editing.view.getDomRoot()?.querySelector("a.reference-link");
+
+ expect(findAnchor()?.textContent).toBe("report.pdf");
+ expect(findAnchor()?.querySelector(".bx-spin")).not.toBeNull();
+ expect(loadReferenceLinkTitle).not.toHaveBeenCalled();
+
+ editor.model.change((writer) => {
+ writer.setAttribute("href", "#root/abc", reference);
+ writer.removeAttribute("uploadFileName", reference);
+ });
+
+ expect(findAnchor()?.getAttribute("href")).toBe("#root/abc");
+ expect(findAnchor()?.querySelector(".bx-spin")).toBeNull();
+ expect(loadReferenceLinkTitle).toHaveBeenCalledWith(expect.anything(), "#root/abc");
+ });
+
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 0fb9af97c8..6d355f9643 100644
--- a/packages/ckeditor5/src/plugins/referencelink.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.ts
@@ -96,7 +96,7 @@ class ReferenceLinkEditing extends Plugin {
// The inline widget is self-contained, so it cannot be split by the caret, and it can be selected:
isObject: true,
- allowAttributes: [ 'href', 'uploadId', 'uploadStatus' ]
+ allowAttributes: [ 'href', 'uploadId', 'uploadStatus', 'uploadFileName' ]
} );
}
@@ -117,9 +117,11 @@ class ReferenceLinkEditing extends Plugin {
} );
conversion.for( 'editingDowncast' ).elementToElement( {
- model: 'reference',
+ // Redraws a placeholder when its upload sets `href` and clears `uploadFileName`.
+ model: { name: 'reference', attributes: [ 'href', 'uploadFileName' ] },
view: ( modelItem, { writer: viewWriter } ) => {
const href = modelItem.getAttribute('href') as string;
+ const uploadFileName = String(modelItem.getAttribute('uploadFileName') ?? '');
const referenceLinkView = viewWriter.createContainerElement( 'a', {
href,
@@ -132,6 +134,13 @@ class ReferenceLinkEditing extends Plugin {
const noteTitleView = viewWriter.createUIElement('span', {}, function( domDocument ) {
const domElement = this.toDomElement( domDocument );
+ if (uploadFileName) {
+ const spinner = domDocument.createElement("span");
+ spinner.className = "bx bx-loader-alt bx-spin";
+ domElement.append(spinner, uploadFileName);
+ return domElement;
+ }
+
const editorEl = editor.editing.view.getDomRoot();
const component = glob.getComponentByEl<EditorComponent>(editorEl);
diff --git a/packages/ckeditor5/src/plugins/uploadimage.spec.ts b/packages/ckeditor5/src/plugins/uploadimage.spec.ts
index 8def718225..26363bc66d 100644
--- a/packages/ckeditor5/src/plugins/uploadimage.spec.ts
+++ b/packages/ckeditor5/src/plugins/uploadimage.spec.ts
@@ -3,7 +3,10 @@ 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 from "./uploadimage.js";
+import UploadimagePlugin, {
+ isFileAttachmentUpload,
+ uploadAsFileAttachment
+} from "./uploadimage.js";
/**
* A fake XMLHttpRequest that records the calls the adapter makes and lets the
@@ -158,6 +161,20 @@ 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 () => {
+ const fileRepository = editor.plugins.get(FileRepository);
+ const marked = createFakeLoader(new File(["content"], "pic.png", { type: "image/png" }));
+ uploadAsFileAttachment(marked);
+ expect(isFileAttachmentUpload(marked)).toBe(true);
+
+ void fileRepository.createUploadAdapter?.(marked).upload();
+ expect((await awaitSentXhr()).url).toBe("api/notes/noteAbc/attachments/upload?role=file");
+
+ FakeXHR.last = undefined;
+ void createAdapter(new File(["content"], "pic.png", { type: "image/png" })).upload();
+ expect((await awaitSentXhr()).url).toBe("api/notes/noteAbc/attachments/upload");
+ });
+
it("rejects with the server error message when the response carries one", async () => {
const file = new File(["content"], "pic.png", { type: "image/png" });
const adapter = createAdapter(file);
diff --git a/packages/ckeditor5/src/plugins/uploadimage.ts b/packages/ckeditor5/src/plugins/uploadimage.ts
index 18f981cdaf..0ffa894832 100644
--- a/packages/ckeditor5/src/plugins/uploadimage.ts
+++ b/packages/ckeditor5/src/plugins/uploadimage.ts
@@ -1,5 +1,16 @@
import { FileRepository, Plugin, type FileLoader, type LocaleTranslate, type UploadAdapter } from "ckeditor5";
+const fileAttachmentLoaders = 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);
+}
+
+export function isFileAttachmentUpload(loader: FileLoader) {
+ return fileAttachmentLoaders.has(loader);
+}
+
export default class UploadimagePlugin extends Plugin {
static get requires() {
return [ FileRepository ];
@@ -68,9 +79,10 @@ class Adapter implements UploadAdapter {
const xhr = this.xhr = new XMLHttpRequest();
const {noteId} = glob.getActiveContextNote();
+ const query = isFileAttachmentUpload(this.loader) ? "?role=file" : "";
// this must be a relative path
- const url = `api/notes/${noteId}/attachments/upload`;
+ const url = `api/notes/${noteId}/attachments/upload${query}`;
xhr.open('POST', url, true);
xhr.responseType = 'json';
diff --git a/packages/trilium-core/src/routes/api/attachments.spec.ts b/packages/trilium-core/src/routes/api/attachments.spec.ts
index 9a227502d7..a1615600ec 100644
--- a/packages/trilium-core/src/routes/api/attachments.spec.ts
+++ b/packages/trilium-core/src/routes/api/attachments.spec.ts
@@ -236,6 +236,30 @@ 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" });
+
+ 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
+ }
+ }
+ );
+ 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" })
+ ]);
+ });
+
it("reports a missing upload when no file is present", async () => {
const { noteId } = await createTextNote(api, { title: "No file target" });
diff --git a/packages/trilium-core/src/routes/api/attachments.ts b/packages/trilium-core/src/routes/api/attachments.ts
index c60bf2a7a9..8c05b7683d 100644
--- a/packages/trilium-core/src/routes/api/attachments.ts
+++ b/packages/trilium-core/src/routes/api/attachments.ts
@@ -61,7 +61,10 @@ 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);
- if (isAcceptedImageMime(file.mimetype)) {
+ // `role=file` stores a picture as a file attachment, so the caller gets a link, not an image.
+ const isFileRoleRequested = req.query.role === "file";
+
+ if (!isFileRoleRequested && 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);