Skip to content

Build your personal knowledge base with Trilium Notes

fix(slash commands): repair the image upload entry and its stale spec

Elian Doran1516c0511caf
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index d800bcfb99..acb11c5b44 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4256,6 +4256,7 @@
"type-the-content-here": "Type the content here...",
"undefined-custom-task-state": "Undefined custom task state",
"url": "URL",
+ "upload-an-image-from-your-device": "Upload an image from your device.",
"upload-image": "Upload image",
"warning": "Warning",
"working": "Working…"
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
index 68ad48e821..b2d46bb53b 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
@@ -8,6 +8,8 @@ import {
Essentials,
_getModelData as getModelData,
Heading,
+ Image,
+ ImageUpload,
keyCodes,
MentionEditing,
Paragraph,
@@ -184,9 +186,10 @@ describe("TriliumSlashCommands", () => {
// No `heading.options` to derive from, so the palette carries no headings at all...
expect(buildDefaultSlashCommands(editor).map((definition) => definition.id))
- .toEqual([ "blockQuote", "codeBlock", "insertTable", "horizontalLine", "indent", "outdent" ]);
+ .toEqual([ "blockQuote", "codeBlock", "insertTable", "horizontalLine", "indent", "outdent", "uploadImage" ]);
- // ...and of those, only the one whose plugin is actually loaded survives the catalog.
+ // ...and of the command-backed ones, only the one whose plugin is actually loaded
+ // survives the catalog.
const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);
expect(ids).toContain("/blockQuote");
expect(ids).not.toContain("/codeBlock");
@@ -264,6 +267,107 @@ describe("TriliumSlashCommands", () => {
});
});
+ describe("image upload", () => {
+ /** The palette entry opens a file picker, so the spec drives the `<input>` it creates. */
+ function uploadEntry(target: Editor): SlashCommandDefinition {
+ const definition = buildDefaultSlashCommands(target).find((candidate) => candidate.id === "uploadImage");
+
+ if (!definition) {
+ throw new Error("the palette should carry an `uploadImage` entry");
+ }
+
+ 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.
+ expect(isSlashCommandEnabled(editor, uploadEntry(editor))).toBe(false);
+ expect((await queryPalette("")).map((item) => (item as { id: string }).id)).not.toContain("/uploadImage");
+
+ editor = await createTestEditor(
+ [ Essentials, Paragraph, Image, ImageUpload, MentionEditing, TriliumMentionUI, TriliumSlashCommands ]
+ );
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ expect(isSlashCommandEnabled(editor, uploadEntry(editor))).toBe(true);
+ expect((await queryPalette("")).map((item) => (item as { id: string }).id)).toContain("/uploadImage");
+ });
+
+ it("uploads only the picked files whose type `image.upload.types` allows", async () => {
+ editor = await createTestEditor(
+ [ Essentials, Paragraph, Image, ImageUpload, MentionEditing, TriliumMentionUI, TriliumSlashCommands ],
+ { image: { upload: { types: [ "png", "svg+xml" ] } } }
+ );
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ const execute = vi.spyOn(editor, "execute").mockReturnValue(undefined);
+ const click = vi.spyOn(HTMLInputElement.prototype, "click").mockReturnValue(undefined);
+
+ uploadEntry(editor).execute?.(editor);
+
+ expect(click).toHaveBeenCalledOnce();
+ const input = click.mock.instances[0] as HTMLInputElement;
+
+ // `accept` narrows the native picker to the configured types, and the `+` in a type
+ // like `svg+xml` survives into the filter regexp rather than being read as a quantifier.
+ expect(input.accept).toBe("image/png,image/svg+xml");
+ expect(input.type).toBe("file");
+ expect(input.isConnected).toBe(true);
+
+ const png = new File([ "" ], "a.png", { type: "image/png" });
+ const svg = new File([ "<svg/>" ], "b.svg", { type: "image/svg+xml" });
+ const text = new File([ "" ], "c.txt", { type: "text/plain" });
+ const gif = new File([ "" ], "d.gif", { type: "image/gif" });
+
+ input.files = filesOf(png, svg, text, gif);
+ input.dispatchEvent(new Event("change"));
+
+ expect(execute).toHaveBeenCalledWith("uploadImage", { file: [ png, svg ] });
+ expect(input.isConnected).toBe(false);
+ });
+
+ it("uploads nothing, and still cleans up, when the picker yields no allowed image", async () => {
+ editor = await createTestEditor(
+ [ Essentials, Paragraph, Image, ImageUpload, MentionEditing, TriliumMentionUI, TriliumSlashCommands ],
+ { image: { upload: { types: [ "png" ] } } }
+ );
+
+ const execute = vi.spyOn(editor, "execute").mockReturnValue(undefined);
+ const click = vi.spyOn(HTMLInputElement.prototype, "click").mockReturnValue(undefined);
+
+ uploadEntry(editor).execute?.(editor);
+ const input = click.mock.instances[0] as HTMLInputElement;
+
+ input.files = filesOf(new File([ "" ], "c.txt", { type: "text/plain" }));
+ input.dispatchEvent(new Event("change"));
+
+ expect(execute).not.toHaveBeenCalled();
+ expect(input.isConnected).toBe(false);
+ });
+
+ it("accepts nothing in an editor that configures no upload types", async () => {
+ // `image.upload.types` is undefined without `ImageUpload`; reading it must not throw.
+ const click = vi.spyOn(HTMLInputElement.prototype, "click").mockReturnValue(undefined);
+
+ uploadEntry(editor).execute?.(editor);
+ const input = click.mock.instances[0] as HTMLInputElement;
+
+ expect(input.accept).toBe("");
+ input.remove();
+ });
+ });
+
describe("snippets", () => {
const SNIPPETS: SnippetDefinition[] = [
{
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
index 23db5bb57f..2ebff64d6c 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
@@ -639,42 +639,47 @@ function buildImageUploadCommand(editor: Editor): SlashCommandDefinition {
return {
id: "uploadImage",
title: t("Upload image"),
+ description: t("Upload an image from your device."),
+ aliases: [ "picture", "photo" ],
icon: IconImage,
- execute(editor) {
+ // The entry opens a file picker instead of naming `uploadImage`, so `commandName` cannot
+ // gate it; without this it would be offered in an editor that has no `ImageUpload`.
+ isEnabled: (target) => target.commands.get("uploadImage")?.isEnabled ?? false,
+ execute(target) {
+ const imageTypes = target.config.get("image.upload.types") ?? [];
+ const imageTypesRegExp = createImageTypeRegExp(imageTypes);
const input = document.createElement("input");
input.type = "file";
- input.accept = "*/*";
+ input.accept = imageTypes.map((type) => `image/${type}`).join(",");
+ input.multiple = true;
+ input.style.display = "none";
- const imageTypes = editor.config.get( 'image.upload.types' )!;
- const imageTypesRegExp = createImageTypeRegExp( imageTypes );
-
- input.addEventListener( "change", () => {
+ 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));
+ .filter((file) => imageTypesRegExp.test(file.type));
- if (imagesToUpload) {
- editor.execute('uploadImage', { file: imagesToUpload });
- editor.editing.view.focus();
+ if (imagesToUpload.length) {
+ target.execute("uploadImage", { file: imagesToUpload });
+ target.editing.view.focus();
}
input.remove();
- }, { once: true } );
-
- input.style.display = 'none';
- document.body.appendChild( input );
+ }, { 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: Array<string> ): RegExp {
- // Sanitize the MIME type name which may include: "+", "-" or ".".
- const regExpSafeNames = types.map( type => type.replace( '+', '\\+' ) );
+function createImageTypeRegExp(types: string[]): RegExp {
+ // Sanitize the MIME type name which can include: "+", "-" or ".".
+ const regExpSafeNames = types.map((type) => type.replace("+", "\\+"));
- return new RegExp( `^image\\/(${ regExpSafeNames.join( '|' ) })$` );
+ return new RegExp(`^image\\/(${regExpSafeNames.join("|")})$`);
}
/**