Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

Add support for pasting (ctrl+v) images and files into the richtext editor.

Kailash Nadh801a76603411
diff --git a/i18n/en.json b/i18n/en.json
index f2910b7e..abca5a2e 100644
--- a/i18n/en.json
+++ b/i18n/en.json
@@ -10,6 +10,7 @@
"bounces.unknownService": "Unknown service.",
"campaigns.addAltText": "Add alternate plain text message",
"campaigns.addAttachments": "Add attachments",
+ "campaigns.attachmentAdded": "Added attachment '{name}'",
"campaigns.archiveEnable": "Publish to public archive",
"campaigns.archiveHelp": "Publish (running, paused, finished) the campaign message on the public archive.",
"campaigns.archiveMeta": "Campaign metadata",
diff --git a/static/admin/assets/js/richtext-editor.js b/static/admin/assets/js/richtext-editor.js
index dfda88ee..fcf5f5fc 100644
--- a/static/admin/assets/js/richtext-editor.js
+++ b/static/admin/assets/js/richtext-editor.js
@@ -2,6 +2,7 @@
import Squire from 'squire-rte';
import { beautifyHTML } from './content.js';
import { setupTable } from './richtext/table.js';
+import { toast } from './utils.js';
import {
i18n, t, closestInSelection, PALETTE, EMOJIS, CHARS,
} from './richtext/data.js';
@@ -37,6 +38,7 @@ class RichtextEditor extends HTMLElement {
#resizeObs = null;
#clearFind = null;
#refreshFind = null;
+ #mediaUpload = null;
connectedCallback() {
if (Object.hasOwn(this, 'value')) {
@@ -63,6 +65,7 @@ class RichtextEditor extends HTMLElement {
} else {
this.initToolbar();
this.initShortcuts();
+ this.#setupMediaPaste();
this.#setupFind();
this.#setupOverflow();
this.#fillGrids();
@@ -121,6 +124,7 @@ class RichtextEditor extends HTMLElement {
}
disconnectedCallback() {
+ this.#mediaUpload?.abort();
this.#clearFind?.();
this.#resizeObs?.disconnect();
this.#resizeObs = null;
@@ -441,6 +445,123 @@ class RichtextEditor extends HTMLElement {
}
}
+ // Capture pasted files and data-URI images, upload them to the server,
+ // then insert them into the editor (images) or add as attachments (non-images).
+ #setupMediaPaste() {
+ // Capture before Squire handles mixed image/file clipboard contents.
+ this.addEventListener('paste', (e) => {
+ const files = [...(e.clipboardData?.files || [])];
+ if (!this.content.contains(e.target) || !this.hasAttribute('allow-attachments')
+ || !files.some((file) => !file.type.startsWith('image/'))) {
+ return;
+ }
+
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ this.#pasteMedia(document.createDocumentFragment(), files);
+ }, true);
+
+ this.editor.addEventListener('pasteImage', (e) => {
+ const files = [...e.detail.clipboardData.files].filter((file) => file.type.startsWith('image/'));
+ if (!files.length) {
+ return;
+ }
+
+ this.#pasteMedia(document.createDocumentFragment(), files);
+ });
+
+ this.editor.addEventListener('willPaste', (e) => {
+ const fragment = e.detail.fragment;
+ if (fragment?.querySelector('img[src^="data:image/"]')) {
+ e.preventDefault();
+ this.#pasteMedia(fragment);
+ }
+ });
+ }
+
+ async #pasteMedia(fragment, files = []) {
+ if (this.inert) {
+ return;
+ }
+
+ const ed = this.editor;
+ const range = ed.getSelection().cloneRange();
+ const uploads = files.length ? files.map((file) => {
+ const img = file.type.startsWith('image/') ? document.createElement('img') : null;
+ if (img) {
+ fragment.append(img);
+ }
+ return [img, file];
+ }) : [...fragment.querySelectorAll('img[src^="data:image/"]')].map((img) => [img, null]);
+
+ const controller = new AbortController();
+ const { signal } = controller;
+ this.#mediaUpload = controller;
+
+ const cancel = (e) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ controller.abort();
+ }
+ };
+
+ // The editor is disabled/locked during uploads, so listen outside it.
+ document.addEventListener('keydown', cancel, true);
+ this.setAttribute('data-spinner', 'overlay');
+ this.setAttribute('aria-busy', 'true');
+ this.inert = true;
+
+ try {
+ for (const [img, file] of uploads) {
+ const blob = file || await (await fetch(img.src, { signal })).blob();
+ signal.throwIfAborted();
+
+ const body = new FormData();
+ body.set('file', blob, blob.name || `image.${blob.type.split('/')[1].split('+')[0]}`);
+
+ const resp = await fetch('/api/media', {
+ method: 'POST', body, signal, headers: { Accept: 'application/json' },
+ });
+
+ if (!resp.ok) {
+ const out = await resp.json().catch(() => ({}));
+ throw new Error(out.message || resp.statusText);
+ }
+ const out = await resp.json();
+ signal.throwIfAborted();
+
+ if (img) {
+ img.setAttribute('src', out.data.url);
+ img.removeAttribute('srcset');
+ } else if (this.editor === ed) {
+ this.dispatchEvent(new CustomEvent('richtext-attachment', { bubbles: true, detail: out.data }));
+ }
+ }
+
+ signal.throwIfAborted();
+
+ if (this.editor === ed && fragment.hasChildNodes()) {
+ const holder = document.createElement('div');
+ holder.append(fragment);
+ ed.setSelection(range);
+ ed.insertHTML(holder.innerHTML);
+ }
+ } catch (err) {
+ if (!signal.aborted) {
+ toast(err.message, 'danger');
+ }
+ } finally {
+ document.removeEventListener('keydown', cancel, true);
+ this.#mediaUpload = null;
+ this.inert = false;
+ this.removeAttribute('aria-busy');
+ if (this.editor === ed) {
+ ed.focus();
+ }
+ }
+ }
+
// Image dialog.
#openImage() {
const ed = this.editor;
diff --git a/static/admin/assets/js/views/campaign.js b/static/admin/assets/js/views/campaign.js
index f307dc96..57654207 100644
--- a/static/admin/assets/js/views/campaign.js
+++ b/static/admin/assets/js/views/campaign.js
@@ -461,6 +461,13 @@ function component(camp, sel) {
this._mediaTarget = null;
},
+ onPasteAttachment(m) {
+ if (this.canEdit && !this.form.media.some((x) => x.id === m.id)) {
+ this.form.media.push(new MediaTag(m));
+ u.toast(i18n.ts('campaigns.attachmentAdded', { name: m.filename }), 'success');
+ }
+ },
+
onPickMedia(m) {
const t = this._mediaTarget;
if (typeof t === 'function') {
diff --git a/static/admin/i18n.txt b/static/admin/i18n.txt
index e4cb3864..5b2c5b99 100644
--- a/static/admin/i18n.txt
+++ b/static/admin/i18n.txt
@@ -37,6 +37,7 @@ globals.messages.statusChanged
editor.confirmSwitchFormat
globals.messages.confirmOverwriteContent
campaigns.testSent
+campaigns.attachmentAdded
# Rich-text editor (strings used by JS in richtext-editor.js).
globals.terms.none
diff --git a/static/admin/partials/campaign-content.html b/static/admin/partials/campaign-content.html
index 53c55f85..02565941 100644
--- a/static/admin/partials/campaign-content.html
+++ b/static/admin/partials/campaign-content.html
@@ -6,9 +6,9 @@
<div class="page-content content editor">
<fieldset class="card editor-box">
<!-- <legend>{{ $root.L.T "globals.fields.content" }}</legend> -->
- <div class="editor-body" :class="{ 'is-loading': showEditorSpinner }" @editor-ready="editorReady = true" @campaign-save.window="onSave" @campaign-preview.window="onPreviewContent" @richtext-media="onEditorMedia($event)" @visual-media="onEditorMedia($event)" @editor-change="form.body = $event.detail.body; form.body_source = $event.detail.source">
+ <div class="editor-body" :class="{ 'is-loading': showEditorSpinner }" @editor-ready="editorReady = true" @campaign-save.window="onSave" @campaign-preview.window="onPreviewContent" @richtext-media="onEditorMedia($event)" @richtext-attachment="onPasteAttachment($event.detail)" @visual-media="onEditorMedia($event)" @editor-change="form.body = $event.detail.body; form.body_source = $event.detail.source">
<template x-if="contentReady && form.content_type === 'richtext'">
- {{ template "richtext-editor" dict "Root" $root "Body" $c.Body "Disabled" (not (or (eq $c.Status "draft") (eq $c.Status "scheduled") (eq $c.Status "paused"))) }}
+ {{ template "richtext-editor" dict "Root" $root "Body" $c.Body "Attachments" true "Disabled" (not (or (eq $c.Status "draft") (eq $c.Status "scheduled") (eq $c.Status "paused"))) }}
</template>
<template x-if="contentReady && form.content_type === 'html'">
<code-editor lang="html" @input="form.body = $event.target.value"><textarea>{{ $c.Body }}</textarea></code-editor>
diff --git a/static/admin/partials/richtext-editor.html b/static/admin/partials/richtext-editor.html
index e20bb7d9..71c10d3c 100644
--- a/static/admin/partials/richtext-editor.html
+++ b/static/admin/partials/richtext-editor.html
@@ -2,7 +2,7 @@
{{- $root := .Root -}}
{{- $L := $root.L -}}
{{- $f := "richtext-icons.svg" -}}
-<richtext-editor {{ if .Disabled }}disabled{{ end }} @input="form.body = $event.target.value">
+<richtext-editor {{ if .Disabled }}disabled{{ end }} {{ if .Attachments }}allow-attachments{{ end }} @input="form.body = $event.target.value">
<textarea data-rte-source hidden>{{ .Body }}</textarea>
<div class="rte-toolbar" role="toolbar" aria-label="{{ $L.T "editor.toolbar" }}">