Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/text editor: add a way for the user to specify before attaching a file if should be inserted as a link or an embed
Adorian Doran68fac8983f8f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 88d97f41bd..3a4c6a1217 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4241,7 +4241,9 @@"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-and-embed-file": "Attach and embed file","attach-file": "Attach file",+ "attach-file-as-a-link": "Attach file as a link","box-size": "Box size","bulleted-list": "Bulleted list","card": "Card",@@ -4362,7 +4364,8 @@"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-files-as-attachments-and-insert-embeds": "Upload files as attachments and insert embeds.",+ "upload-files-as-attachments-and-insert-links": "Upload files as attachments and insert links.","upload-image": "Upload image","warning": "Warning","working": "Working…",diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 5320318fb6..f35f59e810 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -194,6 +194,9 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextgetNoteId() {return note.noteId;},+ getIncludeNoteDefaultBoxSize() {+ return options.get("includeNoteDefaultBoxSize");+ },// Link preview functionality. The insert flow itself lives in the editor (a balloon form),// so the host only has to supply the metadata and the rendering.async fetchLinkMetadata(url: string) {diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.htmlindex b84a56decf..8f228b41d3 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@@ -38,8 +38,11 @@and link them in its content, press the <span class="tn-icon cke cke-paper-clip"></span> <em>Attach file</em> buttonin the <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 <a class="reference-link" href="#root/_help_ZlN4nump6EbW">Slash Commands</a>.</p>+ button, and select one or more files. The arrow beside the button lists+ the same action as <em>Attach file as a link</em>, followed by <em>Attach and embed file</em>,+ which embeds the files instead (see below). Both actions are also available+ as <em>Attach file as a link</em> and <em>Attach and embed file</em> in the <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 insertedat the cursor. Several files produce several links, separated by a space.</li>@@ -65,11 +68,15 @@class="reference-link" href="#root/_help_nBAXQFj20hS1">Include Note</a> showsa note: a picture is displayed, and a PDF, a video or a document is previewed.</p><ul>- <li>To embed an attachment, right-click a link to it in a text note being- edited and select <em>Convert link to an embed</em>, at the end of the menu.- The embed takes the default box size of included notes.</li>- <li>To change its size, select the embed and use the box size menu in its- toolbar.</li>+ <li>To attach files and embed them straight away, select <em>Attach and embed file</em> from+ the arrow beside the <span class="tn-icon cke cke-paper-clip"></span> <em>Attach file</em> button.+ Each file gets an embed of its own, which shows the file name while the+ file uploads.</li>+ <li>To embed an attachment that is already linked, right-click a link to it+ in a text note being edited and select <em>Convert link to an embed</em>,+ at the end of the menu.</li>+ <li>An embed takes the default box size of included notes. To change its size,+ select the embed and use the box size menu in its toolbar.</li><li>To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span> <em>Convert to link</em> buttonin its toolbar.</li></ul>diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Attachments.mdindex d62f15a508..a30f0afaf0 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@@ -21,7 +21,7 @@ The system attachments are displayed at the end of the attachments list, in a de## 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>.+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 arrow beside the button lists the same action as _Attach file as a link_, followed by _Attach and embed file_, which embeds the files instead (see below). Both actions are also available as _Attach file as a link_ and _Attach and embed 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.@@ -39,8 +39,9 @@ Links follow changes to their attachment: renaming it updates the title they shoAn attachment can be shown in the text instead of linked, the way <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a> shows a note: a picture is displayed, and a PDF, a video or a document is previewed.-* To embed an attachment, right-click a link to it in a text note being edited and select _Convert link to an embed_, at the end of the menu. The embed takes the default box size of included notes.-* To change its size, select the embed and use the box size menu in its toolbar.+* To attach files and embed them straight away, select _Attach and embed file_ from the arrow beside the <span class="tn-icon cke cke-paper-clip"></span> _Attach file_ button. Each file gets an embed of its own, which shows the file name while the file uploads.+* To embed an attachment that is already linked, right-click a link to it in a text note being edited and select _Convert link to an embed_, at the end of the menu.+* An embed takes the default box size of included notes. To change its size, select the embed and use the box size menu in its toolbar.* To turn the embed back into a link, select it and press the <span class="tn-icon cke cke-link"></span> _Convert to link_ button in its toolbar.An embed follows its attachment like a link does. Converting the attachment into a note turns the embed into an included note. In a [shared note](../../Advanced%20Usage/Sharing.md), an embedded picture is displayed, and any other attachment appears as a link to download it.diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex 35470eee72..041b361796 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -53,6 +53,8 @@ declare global {getAttachmentHref(attachmentId: string): Promise<string | null>;/** The note the editor holds. Hosts without a note of their own leave it out. */getNoteId?(): string | undefined;+ /** The box size the user gives a new include. Hosts without includes leave it out. */+ getIncludeNoteDefaultBoxSize?(): string;/*** Reads a page's preview metadata through the host. Never rejects: any failure — network* error, HTTP error, unparseable page — resolves as `{ unresolved: true }` withdiff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.tsindex 4738e19e3b..079f1dcb85 100644--- a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.spec.ts@@ -1,10 +1,14 @@import {ClassicEditor,Command,+ DropdownView,Essentials,FileDialogButtonView,+ FileDialogListItemButtonView,IconPaperClip,- Paragraph+ ListItemView,+ Paragraph,+ SplitButtonView} from "ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -14,52 +18,123 @@ import FileUploadUI from "./file_upload_ui.js";describe("FileUploadUI", () => {let editor: ClassicEditor;let command: Command;+ let includeCommand: Command;beforeEach(async () => {editor = await createTestEditor([Essentials, Paragraph, FileUploadUI]);command = new Command(editor);command.refresh();editor.commands.add("fileUpload", command);+ includeCommand = new Command(editor);+ includeCommand.refresh();+ editor.commands.add("insertIncludeNote", includeCommand);});- function createButton() {- const button = editor.ui.componentFactory.create("fileUpload");- if (!(button instanceof FileDialogButtonView)) {- throw new Error("Expected a file dialog button.");+ function createDropdown() {+ const dropdown = editor.ui.componentFactory.create("fileUpload");+ if (+ !(dropdown instanceof DropdownView)+ || !(dropdown.buttonView instanceof SplitButtonView)+ ) {+ throw new Error("Expected a split button dropdown.");+ }+ const { actionView } = dropdown.buttonView;+ if (!(actionView instanceof FileDialogButtonView)) {+ throw new Error("Expected a file dialog button as the action.");}- return button;- }- it("registers a paperclip button that picks any number of files of any type", () => {- const button = createButton();+ const items = Array.from(dropdown.listView?.items ?? []).map((item) => {+ const button = item instanceof ListItemView ? item.children.first : null;+ if (!(button instanceof FileDialogListItemButtonView)) {+ throw new Error("Expected a file dialog list item.");+ }+ return button;+ });- 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();- });+ return { dropdown, splitButton: dropdown.buttonView, actionView, items };+ }++ function pickFiles() {+ return [+ new File(["a"], "a.pdf", { type: "application/pdf" }),+ new File(["b"], "b.png", { type: "image/png" })+ ];+ }- it("follows the enabled state of the `fileUpload` command", () => {- const button = createButton();- expect(button.isEnabled).toBe(true);+ it("registers a paperclip split button that picks any number of files of any type", () => {+ const { splitButton, actionView } = createDropdown();- command.forceDisabled("spec");- expect(button.isEnabled).toBe(false);+ expect(splitButton.label).toBe("Attach file");+ expect(splitButton.tooltip).toBe(true);+ expect(actionView.label).toBe("Attach file");+ expect(actionView.icon).toBe(IconPaperClip);+ expect(actionView.tooltip).toBe(true);+ expect(actionView.allowMultipleFiles).toBe(true);+ expect(actionView.acceptedType).toBeUndefined();});- it("attaches the picked files and returns the focus to the editor", () => {- const button = createButton();+ it("links the files picked through the button and returns the focus to the editor", () => {+ const { actionView } = createDropdown();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" })- ];+ const files = pickFiles();- button.fire("done", files);+ actionView.fire("done", files);expect(execute).toHaveBeenCalledWith("fileUpload", { file: files });expect(focus).toHaveBeenCalled();});++ it("lists attaching as links and as embeds, each closing the dropdown when picked", () => {+ const { dropdown, items } = createDropdown();+ const execute = vi.spyOn(editor, "execute").mockImplementation(() => undefined);+ const focus = vi.spyOn(editor.editing.view, "focus");+ const openDialog = vi.spyOn(HTMLInputElement.prototype, "click")+ .mockImplementation(() => undefined);+ const files = pickFiles();++ expect(items.map((item) => [ item.label, item.withText, item.allowMultipleFiles ]))+ .toEqual([+ [ "Attach file as a link", true, true ],+ [ "Attach and embed file", true, true ]+ ]);++ const [ linkItem, embedItem ] = items;+ dropdown.render();+ dropdown.isOpen = true;+ linkItem.fire("execute");+ expect(dropdown.isOpen).toBe(false);+ expect(openDialog).toHaveBeenCalledOnce();+ openDialog.mockRestore();++ linkItem.fire("done", files);+ embedItem.fire("done", files);+ expect(execute.mock.calls).toEqual([+ [ "fileUpload", { file: files } ],+ [ "fileUpload", { file: files, asEmbed: true } ]+ ]);+ expect(focus).toHaveBeenCalledTimes(2);+ dropdown.destroy();+ });++ it("follows the `fileUpload` command, and offers embeds only where an include can go", () => {+ const { dropdown, actionView, items: [ linkItem, embedItem ] } = createDropdown();+ expect([ dropdown.isEnabled, actionView.isEnabled ]).toEqual([ true, true ]);+ expect([ linkItem.isEnabled, embedItem.isEnabled ]).toEqual([ true, true ]);++ includeCommand.forceDisabled("spec");+ expect([ linkItem.isEnabled, embedItem.isEnabled ]).toEqual([ true, false ]);++ command.forceDisabled("spec");+ expect([ dropdown.isEnabled, actionView.isEnabled ]).toEqual([ false, false ]);+ });++ it("lists no embeds in an editor without includes", async () => {+ const withoutIncludes = await createTestEditor([Essentials, Paragraph, FileUploadUI]);+ withoutIncludes.commands.add("fileUpload", new Command(withoutIncludes));+ editor = withoutIncludes;++ const labels = createDropdown().items.map((item) => item.label);+ expect(labels).toEqual([ "Attach file as a link" ]);+ });});diff --git a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.tsindex e59f15fa9c..4b0fdae3b7 100644--- a/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts+++ b/packages/ckeditor5/src/plugins/file_upload/file_upload_ui.ts@@ -1,11 +1,22 @@import {+ createDropdown,FileDialogButtonView,+ FileDialogListItemButtonView,IconPaperClip,+ ListItemView,+ ListView,Plugin,- type FileInputViewDoneEvent+ SplitButtonView,+ type FileInputViewDoneEvent,+ type Locale} from "ckeditor5";-/** Registers the `fileUpload` toolbar button, which attaches the picked files and links them. */+import type { FileUploadOptions } from "./fileuploadcommand.js";++/**+ * Registers the `fileUpload` split button. The button attaches the picked files and links them;+ * the list also offers to embed them.+ */export default class FileUploadUI extends Plugin {static get pluginName() {return "FileUploadUI" as const;@@ -13,27 +24,70 @@ export default class FileUploadUI extends Plugin {init() {const editor = this.editor;+ const t = editor.t;editor.ui.componentFactory.add("fileUpload", (locale) => {- const button = new FileDialogButtonView(locale);- button.set({- label: editor.t("Attach file"),+ const actionView = new FileDialogButtonView(locale);+ actionView.set({+ label: t("Attach file"),icon: IconPaperClip,tooltip: true,allowMultipleFiles: true});+ this.attachOnDone(actionView, {});++ const dropdownView = createDropdown(locale, new SplitButtonView(locale, actionView));+ dropdownView.buttonView.set({ label: t("Attach file"), tooltip: true });+ actionView.bind("isEnabled").to(dropdownView);const command = editor.commands.get("fileUpload");if (command) {- button.bind("isEnabled").to(command);+ dropdownView.bind("isEnabled").to(command);}- button.on<FileInputViewDoneEvent>("done", (_evt, files) => {- editor.execute("fileUpload", { file: Array.from(files) });- editor.editing.view.focus();- });+ const buttons = [ this.createListButton(locale, t("Attach file as a link"), {}) ];++ // Embedding goes wherever the "Include note" button can insert an include.+ const includeCommand = editor.commands.get("insertIncludeNote");+ if (includeCommand) {+ const embedButton = this.createListButton(+ locale, t("Attach and embed file"), { asEmbed: true }+ );+ embedButton.bind("isEnabled").to(includeCommand);+ buttons.push(embedButton);+ }++ const listView = dropdownView.listView = new ListView(locale);+ for (const button of buttons) {+ const listItem = new ListItemView(locale);+ listItem.children.add(button);+ listView.items.add(listItem);+ button.delegate("execute").to(dropdownView);+ }+ dropdownView.panelView.children.add(listView);++ return dropdownView;+ });+ }++ private createListButton(locale: Locale, label: string, options: Partial<FileUploadOptions>) {+ const button = new FileDialogListItemButtonView(locale);+ button.set({ label, withText: true, allowMultipleFiles: true });+ this.attachOnDone(button, options);++ return button;+ }++ /** Attaches the files picked through `button`, and returns the focus to the editor. */+ private attachOnDone(+ button: FileDialogButtonView | FileDialogListItemButtonView,+ options: Partial<FileUploadOptions>+ ) {+ const editor = this.editor;- return button;+ button.on<FileInputViewDoneEvent>("done", (_evt, files) => {+ editor.execute("fileUpload", { file: Array.from(files), ...options });+ editor.editing.view.focus();});}}diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.tsindex 65fd9438eb..5dce35fd20 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.spec.ts@@ -14,6 +14,8 @@ import {import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";+import { installGlobMock } from "../../../test/globals-test-kit.js";+import IncludeNote from "../includenote.js";import { isUploadAsLink } from "../uploadimage.js";import FileUploadCommand from "./fileuploadcommand.js";@@ -91,7 +93,9 @@ describe("FileUploadCommand", () => {let editor: ClassicEditor;beforeEach(async () => {- editor = await createTestEditor([Essentials, Paragraph, FileRepository, ReferenceSchema]);+ editor = await createTestEditor([+ Essentials, Paragraph, FileRepository, ReferenceSchema, IncludeNote+ ]);// Provide a minimal upload adapter so FileRepository.createLoader() succeeds.createUploadAdapterPlugin(editor);@@ -142,7 +146,44 @@ describe("FileUploadCommand", () => {));});- it("marks the loader of every file to upload as a link", () => {+ it("inserts an embed placeholder per file, each a block in the host's default size", () => {+ installGlobMock({+ getComponentByEl: () => ({ getIncludeNoteDefaultBoxSize: () => "expandable" })+ });+ setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");++ editor.execute("fileUpload", {+ file: [+ new File(["a"], "a.txt", { type: "text/plain" }),+ new File(["b"], "b.png", { type: "image/png" })+ ],+ asEmbed: true+ });++ expect(getModelData(editor.model)).toMatch(new RegExp(+ "^<paragraph>foo</paragraph>" ++ "<includeNote boxSize=\"expandable\" uploadFileName=\"a.txt\" uploadId=\"\\w+\">" ++ "</includeNote>" ++ "<includeNote boxSize=\"expandable\" uploadFileName=\"b.png\" uploadId=\"\\w+\">" ++ "</includeNote>" ++ "<paragraph>\\[\\]bar</paragraph>$"+ ));+ });++ it("sizes the embeds medium for a host that names no default size", () => {+ installGlobMock({ getComponentByEl: () => ({}) });+ setModelData(editor.model, "<paragraph>[]</paragraph>");++ editor.execute("fileUpload", {+ file: [ new File(["a"], "a.txt", { type: "text/plain" }) ],+ asEmbed: true+ });++ expect(getModelData(editor.model)).toMatch(/^<includeNote boxSize="medium" /);+ });++ it("marks the loader of every file to upload as a link, for an embed too", () => {+ installGlobMock({ getComponentByEl: () => ({}) });setModelData(editor.model, "<paragraph>[]</paragraph>");const createLoaderSpy = vi.spyOn(editor.plugins.get(FileRepository), "createLoader");@@ -150,7 +191,8 @@ describe("FileUploadCommand", () => {new File(["1"], "one.txt", { type: "text/plain" }),new File(["2"], "two.png", { type: "image/png" })];- editor.execute("fileUpload", { file: files });+ editor.execute("fileUpload", { file: [ files[0] ] });+ editor.execute("fileUpload", { file: [ files[1] ], asEmbed: true });expect(createLoaderSpy.mock.calls).toEqual([ [ files[0] ], [ files[1] ] ]);for (const { value } of createLoaderSpy.mock.results) {diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.tsindex 42b468e7aa..91d9dc541b 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadcommand.ts@@ -1,14 +1,17 @@-import { Command, FileRepository, type Model, type ModelWriter } from "ckeditor5";+import { Command, FileRepository, type Editor, type Model, type ModelWriter } from "ckeditor5";import { uploadAsLink } from "../uploadimage.js";export interface FileUploadOptions {file: File[];+ /** Embeds each file in a block of its own instead of linking it. */+ asEmbed?: boolean;}/*** Uploads files as attachments of the note and inserts a reference link to each, separated by- * spaces. Pictures are linked too, rather than shown.+ * spaces. Pictures are linked too, rather than shown. With `asEmbed`, each file is embedded+ * instead.*/export default class FileUploadCommand extends Command {override refresh() {@@ -18,9 +21,10 @@ export default class FileUploadCommand extends Command {this.isEnabled = !!position && model.schema.checkChild(position, "reference");}- override execute({ file: files }: FileUploadOptions) {+ override execute({ file: files, asEmbed }: FileUploadOptions) {const model = this.editor.model;const fileRepository = this.editor.plugins.get(FileRepository);+ const boxSize = asEmbed ? getDefaultBoxSize(this.editor) : undefined;model.change((writer) => {for (const file of files) {@@ -31,7 +35,11 @@ export default class FileUploadCommand extends Command {}uploadAsLink(loader);- insertPlaceholder(writer, model, loader.id, file.name);+ if (boxSize) {+ insertEmbedPlaceholder(writer, model, loader.id, file.name, boxSize);+ } else {+ insertPlaceholder(writer, model, loader.id, file.name);+ }}});}@@ -50,3 +58,25 @@ function insertPlaceholder(writer: ModelWriter, model: Model, uploadId: string,writer.insertText(" ", afterPlaceholder);writer.setSelection(afterPlaceholder.getShiftedBy(1));}++/** Inserts the embed `FileUploadEditing` completes once the upload ends, as a block of its own. */+function insertEmbedPlaceholder(+ writer: ModelWriter,+ model: Model,+ uploadId: string,+ fileName: string,+ boxSize: string+) {+ const placeholder = writer.createElement("includeNote", {+ boxSize,+ uploadId,+ uploadFileName: fileName+ });+ model.insertObject(placeholder, model.document.selection, null, { setSelection: "after" });+}++/** The box size the user gives a new include, `medium` when the host does not say. */+function getDefaultBoxSize(editor: Editor) {+ const component = glob.getComponentByEl<EditorComponent>(editor.editing.view.getDomRoot());+ return component.getIncludeNoteDefaultBoxSize?.() ?? "medium";+}diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.tsindex c2ba04fc59..5d4048603e 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.spec.ts@@ -20,6 +20,8 @@ import {import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";+import { installGlobMock } from "../../../test/globals-test-kit.js";+import IncludeNote from "../includenote.js";import FileUploadEditing, {isHtmlIncluded,type FileUploadData,@@ -585,3 +587,34 @@ class ReferenceSchema extends Plugin {);}}++describe("FileUploadEditing with embeds", () => {+ it("completes an embed placeholder with the attachment it uploaded", async () => {+ const loadIncludedAttachment = vi.fn();+ installGlobMock({+ getComponentByEl: () => ({+ getIncludeNoteDefaultBoxSize: () => "small",+ loadIncludedAttachment+ })+ });+ const editor = await createTestEditor([+ Essentials, Paragraph, FileRepository, Notification, Clipboard, ReferenceSchema,+ IncludeNote, FileUploadEditing+ ]);+ const controls = installUploadAdapter(editor);+ setModelData(editor.model, "<paragraph>[]</paragraph>");++ const file = new File(["content"], "report.pdf", { type: "application/pdf" });+ editor.execute("fileUpload", { file: [ file ], asEmbed: true });+ await waitFor(() => controls.uploadCalled());+ controls.resolveUpload({ default: "#root/owner?viewMode=attachments&attachmentId=att1" });+ await waitFor(() => !getModelData(editor.model).includes("uploadId"));++ expect(getModelData(editor.model)).toBe(+ "<includeNote attachmentId=\"att1\" boxSize=\"small\"></includeNote>" ++ "<paragraph>[]</paragraph>"+ );+ editor.editing.view.getDomRoot()?.querySelectorAll("div.include-note-wrapper");+ expect(loadIncludedAttachment).toHaveBeenCalledWith("att1", expect.anything(), "small");+ });+});diff --git a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.tsindex 1089e2756b..e2675467fb 100644--- a/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts+++ b/packages/ckeditor5/src/plugins/file_upload/fileuploadediting.ts@@ -8,6 +8,7 @@ import {type ModelItem,type ViewRange} from 'ckeditor5';+import { getAttachmentId } from '../referencelink.js';import FileUploadCommand from './fileuploadcommand';/** A file attachment upload, announced by the `upload` event of `FileUploadEditing`. */@@ -93,7 +94,7 @@ export default class FileUploadEditing extends Plugin {/* v8 ignore next -- defensive: an "insert" differ change always reports the inserted node as position.nodeAfter, so `item` is never null here (the falsy branch is unreachable from any model operation). */if ( item ) {const isInGraveyard = entry.position.root.rootName == '$graveyard';- for ( const file of getFileLinksFromChangeItem( editor, item ) ) {+ for ( const file of getUploadPlaceholders( editor, item ) ) {// Check if the file element still has upload id.const uploadId = file.getAttribute( 'uploadId' ) as string | number;if ( !uploadId ) {@@ -155,7 +156,12 @@ export default class FileUploadEditing extends Plugin {} ).then( data => {model.enqueueChange( { isUndoable: false }, writer => {- writer.setAttribute( 'href', data.default, fileElement );+ if ( fileElement.is( 'element', 'includeNote' ) ) {+ const attachmentId = getAttachmentId( data.default );+ writer.setAttribute( 'attachmentId', attachmentId, fileElement );+ } else {+ writer.setAttribute( 'href', data.default, fileElement );+ }} );clean();@@ -204,8 +210,9 @@ export function isHtmlIncluded( dataTransfer: DataTransfer ) {return Array.from( dataTransfer.types ).includes( 'text/html' ) && dataTransfer.getData( 'text/html' ) !== '';}-function getFileLinksFromChangeItem( editor: Editor, item: ModelItem ) {+/** The links and embeds `FileUploadCommand` inserted, in `item` or inside it. */+function getUploadPlaceholders( editor: Editor, item: ModelItem ) {return Array.from( editor.model.createRangeOn( item ) )- .filter( value => value.item.hasAttribute( 'href' ) )- .map( value => value.item );+ .map( value => value.item )+ .filter( node => node.is( 'element', 'reference' ) || node.is( 'element', 'includeNote' ) );}diff --git a/packages/ckeditor5/src/plugins/includenote.spec.ts b/packages/ckeditor5/src/plugins/includenote.spec.tsindex 2c0f892bd2..389da2119d 100644--- a/packages/ckeditor5/src/plugins/includenote.spec.ts+++ b/packages/ckeditor5/src/plugins/includenote.spec.ts@@ -559,6 +559,34 @@ describe("IncludeNote with attachments", () => {expect(loadIncludedAttachment.mock.calls.at(-1)?.[2]).toBe("full");});+ it("shows an embed by its file name while it uploads, and saves it naming nothing", () => {+ setModelData(+ editor.model,+ "<includeNote boxSize=\"small\" uploadFileName=\"report.pdf\" uploadId=\"u1\">"+ + "</includeNote>"+ );++ const wrapper = renderEmbeds()?.[0];+ const title = wrapper?.querySelector(".include-note-title");+ expect(title?.textContent).toBe("report.pdf");+ expect(title?.querySelector(".bx.bx-loader-alt.bx-spin")).not.toBeNull();+ expect(loadIncludedAttachment).not.toHaveBeenCalled();+ expect(loadIncludedNote).not.toHaveBeenCalled();+ const data = editor.getData();+ expect(data).toContain("<section class=\"include-note\" data-box-size=\"small\">");+ expect(data).not.toMatch(/data-(note|attachment)-id/);++ editor.model.change((writer) => {+ const element = findIncludeNote(editor);+ if (element) {+ writer.setAttribute("attachmentId", "att1", element);+ writer.removeAttribute("uploadFileName", element);+ }+ });+ renderEmbeds();+ expect(loadIncludedAttachment).toHaveBeenCalledWith("att1", expect.anything(), "small");+ });+it("turns an attachment link into an embed in its place, as one undo step", () => {editor.setData(`<p>Before <a class="reference-link" href="${LINK_HREF}">x</a> after</p>`);const link = editor.editing.view.getDomRoot()?.querySelector("a.reference-link");diff --git a/packages/ckeditor5/src/plugins/includenote.ts b/packages/ckeditor5/src/plugins/includenote.tsindex 90b741f49e..bb8ff5da1f 100644--- a/packages/ckeditor5/src/plugins/includenote.ts+++ b/packages/ckeditor5/src/plugins/includenote.ts@@ -135,8 +135,11 @@ class IncludeNoteEditing extends Plugin {// Behaves like a self-contained object (e.g. an image).isObject: true,- // An include shows either a note or, as an embed, an attachment.- allowAttributes: [ 'noteId', 'attachmentId', 'boxSize' ],+ // An include shows either a note or, as an embed, an attachment. An embed that+ // `FileUploadEditing` is uploading carries the upload attributes instead of its id.+ allowAttributes: [+ 'noteId', 'attachmentId', 'boxSize', 'uploadId', 'uploadStatus', 'uploadFileName'+ ],// Allow in places where other blocks are allowed (e.g. directly in the root).allowWhere: '$block'@@ -177,10 +180,14 @@ class IncludeNoteEditing extends Plugin {}} );conversion.for( 'editingDowncast' ).elementToElement( {- model: 'includeNote',+ // Redraws an uploading embed when its upload sets `attachmentId` and clears+ // `uploadFileName`.+ model: { name: 'includeNote', attributes: [ 'attachmentId', 'uploadFileName' ] },view: ( modelElement, { writer: viewWriter } ) => {const boxSize = modelElement.getAttribute( 'boxSize' ) as string | undefined;+ const uploadFileName = modelElement.getAttribute( 'uploadFileName' ) as+ string | undefined;const section = viewWriter.createContainerElement( 'section', {class: 'include-note box-size-' + boxSize,@@ -194,7 +201,11 @@ class IncludeNoteEditing extends Plugin {}, function( domDocument ) {const domElement = this.toDomElement( domDocument );- loadIncludedContent( editor, modelElement, $( domElement ), boxSize );+ if ( uploadFileName ) {+ domElement.append( createUploadTitle( domDocument, uploadFileName ) );+ } else {+ loadIncludedContent( editor, modelElement, $( domElement ), boxSize );+ }preventCKEditorHandling( domElement, editor );@@ -363,13 +374,32 @@ function getSelectedIncludeNote( editor: Editor ) {return selection.getFirstPosition()?.findAncestor( 'includeNote' ) ?? null;}-/** The `data-*` attribute naming what an include shows: an attachment, or a note. */+/**+ * The `data-*` attribute naming what an include shows: an attachment, or a note. An embed whose+ * upload has not ended names nothing.+ */function getIncludedEntityAttributes( element: ModelElement ): Record<string, string> {const attachmentId = element.getAttribute( 'attachmentId' ) as string | undefined;+ const noteId = element.getAttribute( 'noteId' ) as string | undefined;++ if ( attachmentId ) {+ return { 'data-attachment-id': attachmentId };+ }++ return noteId ? { 'data-note-id': noteId } : {};+}- return attachmentId- ? { 'data-attachment-id': attachmentId }- : { 'data-note-id': element.getAttribute( 'noteId' ) as string };+/** The title of an embed whose upload is under way: a spinner and the name of the file. */+function createUploadTitle( domDocument: Document, fileName: string ) {+ const title = domDocument.createElement( 'h4' );+ const label = domDocument.createElement( 'span' );+ const spinner = domDocument.createElement( 'span' );+ title.className = 'include-note-title';+ spinner.className = 'bx bx-loader-alt bx-spin';+ label.append( spinner, fileName );+ title.append( label );++ return title;}/** Has the host render what an include shows into its wrapper. */diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.tsindex adbaef831e..37eb901701 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts@@ -622,7 +622,8 @@ describe("buildTriliumSlashCommands", () => {[ "collapsible", "Collapsible block", "collapsible" ],[ "footnote", "Footnote", "InsertFootnote" ],[ "internal-link", "Internal link", INTERNAL_LINK_COMMAND ],- [ "attach-file", "Attach file", "fileUpload" ],+ [ "attach-file", "Attach file as a link", "fileUpload" ],+ [ "attach-and-embed-file", "Attach and embed file", "fileUpload" ],[ "include-note", "Include note", INCLUDE_NOTE_COMMAND ],[ "page-break", "Page break", "pageBreak" ],[ "markdown-import", "Markdown import", MARKDOWN_IMPORT_COMMAND ],@@ -640,12 +641,15 @@ describe("buildTriliumSlashCommands", () => {expect(entry.icon).toContain("<svg");});- it("attach-file attaches every file picked, of any type, and returns the focus", () => {+ it.each([+ [ "attach-file", {} ],+ [ "attach-and-embed-file", { asEmbed: true } ]+ ])("%s attaches every file picked, of any type, and returns the focus", (id, options) => {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);+ definition(id).execute?.(editor);expect(click).toHaveBeenCalledOnce();const input = click.mock.instances[0] as HTMLInputElement;@@ -659,9 +663,29 @@ describe("buildTriliumSlashCommands", () => {input.files = filesOf(pdf, png);input.dispatchEvent(new Event("change"));- expect(execute).toHaveBeenCalledWith("fileUpload", { file: [ pdf, png ] });+ expect(execute).toHaveBeenCalledWith("fileUpload", { file: [ pdf, png ], ...options });expect(focus).toHaveBeenCalled();expect(input.isConnected).toBe(false);+ click.mockRestore();+ });++ it("offers embedding a file only where both a file and an include can go", () => {+ const fileUpload = { isEnabled: true };+ const includeNote = { isEnabled: true };+ const { fake } = makeFakeEditor({+ fileUpload, [INCLUDE_NOTE_COMMAND]: includeNote+ });+ const isEnabled = definition("attach-and-embed-file").isEnabled;+ expect(isEnabled?.(fake)).toBe(true);++ includeNote.isEnabled = false;+ expect(isEnabled?.(fake)).toBe(false);++ includeNote.isEnabled = true;+ fileUpload.isEnabled = false;+ expect(isEnabled?.(fake)).toBe(false);++ expect(isEnabled?.(makeFakeEditor().fake)).toBe(false);});it.each([diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.tsindex fe2a44b8c3..5ef2a925b1 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts@@ -364,8 +364,8 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitio},{id: "attach-file",- title: t("Attach file"),- description: t("Upload files as attachments and insert links to them."),+ title: t("Attach file as a link"),+ description: t("Upload files as attachments and insert links."),aliases: [ "attachment", "upload" ],icon: IconPaperClip,commandName: "fileUpload",@@ -374,6 +374,21 @@ export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinitiotarget.editing.view.focus();})},+ {+ id: "attach-and-embed-file",+ title: t("Attach and embed file"),+ description: t("Upload files as attachments and insert embeds."),+ aliases: [ "attachment", "upload", "embed" ],+ icon: IconPaperClip,+ commandName: "fileUpload",+ // Embedding goes wherever the "Include note" button can insert an include.+ isEnabled: (target: Editor) => !!target.commands.get("fileUpload")?.isEnabled+ && !!target.commands.get(INCLUDE_NOTE_COMMAND)?.isEnabled,+ execute: (target: Editor) => pickFiles("", (files) => {+ target.execute("fileUpload", { file: files, asEmbed: true });+ target.editing.view.focus();+ })+ },{id: "math",title: t("Math equation"),