High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
JavaScript campaigncampaign-managementemail-marketingemail-subscriptionlistmonkmailing-listnewsletternewsletter-managementnewsletter-softwareself-hostedsms-gatewaysmtptransactional-emails
Fix multiple minor issues and add UX improvements in richtext/Squire editor.
Kailash Nadhb6456cfafd5f
diff --git a/static/admin/assets/css/richtext.css b/static/admin/assets/css/richtext.cssindex 15430858..b0d60ac0 100644--- a/static/admin/assets/css/richtext.css+++ b/static/admin/assets/css/richtext.css@@ -34,7 +34,8 @@ richtext-editor {margin-inline-end: 0;}-.rte-toolbar button {+.rte-toolbar .rte-group > button,+.rte-toolbar ot-dropdown > button {flex: none;padding: 0.4rem;line-height: 0;@@ -83,6 +84,7 @@ richtext-editor {}.rte-content {+ position: relative;min-height: 500px;padding: var(--space-4);font-family: "Geist", var(--font-sans), sans-serif;@@ -98,7 +100,6 @@ richtext-editor {.rte-content img {max-width: 100%;- height: auto;}.rte-content img.img-float-left {@@ -204,13 +205,14 @@ richtext-editor {}.rte-menu {- * {+ [role="menuitem"] > :is(h1, h2, h3, h4, h5, h6) {line-height: 1;margin: 0;padding: 0;}- [role="menuitem"] {+ > [role="menuitem"] {line-height: 1;+ margin: 0;padding: var(--space-1) 0;}}@@ -290,14 +292,13 @@ richtext-editor {padding: var(--space-1) var(--space-3);}-/* Find & replace highlights. */-mark.rte-find {- background: #fff2a8;+:is(.rte-content, .rte-content *)::highlight(rte-find) {+ background-color: #fff2a8;color: inherit;}-mark.rte-find.is-current {- background: #ffcf33;+:is(.rte-content, .rte-content *)::highlight(rte-find-current) {+ background-color: #ffcf33;}/* Table grid-size picker popover. */@@ -356,13 +357,6 @@ mark.rte-find.is-current {font-size: var(--text-7);}-.rte-find-foot {- display: flex;- align-items: center;- justify-content: space-between;- gap: var(--space-2);-}-/* Floating table cell toolbar (shown only when a cell is focused). */.rte-table-tools {position: absolute;@@ -397,28 +391,6 @@ mark.rte-find.is-current {height: 14px;}-/* Image resize overlay. */-.rte-resize {- position: absolute;- z-index: 4;- border: 1px dashed var(--primary);- pointer-events: none;-}--.rte-resize-handle {- position: absolute;- width: 10px;- height: 10px;- background: var(--primary);- border: 1px solid #fff;- pointer-events: auto;-}--.rte-nw { top: -5px; left: -5px; cursor: nwse-resize; }-.rte-ne { top: -5px; right: -5px; cursor: nesw-resize; }-.rte-sw { bottom: -5px; left: -5px; cursor: nesw-resize; }-.rte-se { bottom: -5px; right: -5px; cursor: nwse-resize; }-/* Fullscreen. */richtext-editor.is-fullscreen {position: fixed;diff --git a/static/admin/assets/js/richtext-editor.js b/static/admin/assets/js/richtext-editor.jsindex 8c06815d..dfda88ee 100644--- a/static/admin/assets/js/richtext-editor.js+++ b/static/admin/assets/js/richtext-editor.js@@ -2,7 +2,6 @@import Squire from 'squire-rte';import { beautifyHTML } from './content.js';import { setupTable } from './richtext/table.js';-import { setupResize } from './richtext/resize.js';import {i18n, t, closestInSelection, PALETTE, EMOJIS, CHARS,} from './richtext/data.js';@@ -34,7 +33,10 @@ class RichtextEditor extends HTMLElement {#toolbar = null;#pending = null;#mute = false;+ #resizing = false;#resizeObs = null;+ #clearFind = null;+ #refreshFind = null;connectedCallback() {if (Object.hasOwn(this, 'value')) {@@ -66,7 +68,35 @@ class RichtextEditor extends HTMLElement {this.#fillGrids();this.#setupColorInputs();setupTable(this);- setupResize(this);+ this.content.addEventListener('click', (e) => {+ const el = e.target.closest('img, a[href]');+ if (!el || !this.content.contains(el) || e.detail !== (el.matches('img') ? 2 : 3)) {+ return;+ }++ e.preventDefault();+ e.stopPropagation();+ // Deselect Squire's image resizer before the dialog opens.+ this.content.click();+ const range = document.createRange();+ range.selectNode(el);+ this.editor.setSelection(range);+ this.#run(el.matches('img') ? 'image' : 'link');+ });++ // Squire's getHTML() temporarily detaches its handles. Serialize after+ // the drag ends so live input sync does not break its pointer capture.+ this.content.addEventListener('gotpointercapture', (e) => {+ if (e.target.matches('.squire-resize-handle')) {+ this.#resizing = true;+ }+ });+ this.content.addEventListener('lostpointercapture', () => {+ if (this.#resizing) {+ this.#resizing = false;+ this.sync();+ }+ });// Generic cancel buttons close their dialog.this.querySelectorAll('[data-rte-act="cancel"]').forEach((b) => {@@ -91,6 +121,7 @@ class RichtextEditor extends HTMLElement {}disconnectedCallback() {+ this.#clearFind?.();this.#resizeObs?.disconnect();this.#resizeObs = null;this.editor?.destroy();@@ -112,6 +143,8 @@ class RichtextEditor extends HTMLElement {this.#mute = true;this.editor.setHTML(v);this.#mute = false;+ this.#refreshFind?.();+ this.#updateWordcount();}if (this.#source) {@@ -121,7 +154,7 @@ class RichtextEditor extends HTMLElement {// Push the current content to the host.sync() {- if (!this.editor || this.#mute) {+ if (!this.editor || this.#mute || this.#resizing) {return;}if (this.#source) {@@ -294,7 +327,9 @@ class RichtextEditor extends HTMLElement {}#updateWordcount() {- const text = this.content.textContent.trim();+ const range = document.createRange();+ range.selectNodeContents(this.content);+ const text = this.editor.getSelectedText(range).trim();const n = text ? text.split(/\s+/).length : 0;this.querySelector('[data-rte-wordcount]').textContent = i18n.tc('editor.words', n, { num: n });}@@ -415,8 +450,8 @@ class RichtextEditor extends HTMLElement {f.src.value = img?.getAttribute('src') ?? '';f.alt.value = img?.getAttribute('alt') ?? '';- f.width.value = img?.getAttribute('width') ?? '';- f.height.value = img?.getAttribute('height') ?? '';+ f.width.value = img ? Math.round(img.getBoundingClientRect().width) || '' : '';+ f.height.value = img ? Math.round(img.getBoundingClientRect().height) || '' : '';f.float.value = (img && ['img-float-left', 'img-float-right'].find((c) => img.classList.contains(c))) || '';f.embed.checked = img?.hasAttribute('data-embed') ?? false;@@ -424,18 +459,36 @@ class RichtextEditor extends HTMLElement {const lock = d.querySelector('[data-rte-act="lock"]');const locked = () => lock.getAttribute('aria-pressed') === 'true';const rat = (w, h) => (w > 0 && h > 0 ? w / h : null);- let ratio = img?.naturalWidth- ? rat(img.naturalWidth, img.naturalHeight)- : rat(parseFloat(f.width.value), parseFloat(f.height.value));+ let ratio = rat(Number(f.width.value), Number(f.height.value))+ || (img && rat(img.naturalWidth, img.naturalHeight));+ let lastDimension = 'width';+ let request = 0;++ const scale = () => {+ const from = f.elements[lastDimension];+ const to = f.elements[lastDimension === 'width' ? 'height' : 'width'];+ const v = Number(from.value);+ if (locked() && ratio && Number.isFinite(v) && v > 0) {+ to.value = Math.max(1, Math.round(lastDimension === 'width' ? v / ratio : v * ratio));+ }+ };// Get the ratio from an image's actual size.const loadRatio = (src) => {+ const id = ++request;if (src) {const probe = new Image();- probe.onload = () => { ratio = rat(probe.naturalWidth, probe.naturalHeight); };+ probe.onload = () => {+ if (id !== request) {+ return;+ }+ ratio = rat(probe.naturalWidth, probe.naturalHeight);+ scale();+ };probe.src = src;}};+ d.addEventListener('close', () => { request += 1; }, { once: true });if (!ratio) {loadRatio(f.src.value.trim());}@@ -444,14 +497,14 @@ class RichtextEditor extends HTMLElement {loadRatio(f.src.value.trim());};- const scale = (from, to, fn) => {- const v = parseFloat(from.value);- if (locked() && ratio && Number.isFinite(v)) {- to.value = Math.round(fn(v));- }+ f.width.oninput = () => {+ lastDimension = 'width';+ scale();+ };+ f.height.oninput = () => {+ lastDimension = 'height';+ scale();};- f.width.oninput = () => scale(f.width, f.height, (w) => w / ratio);- f.height.oninput = () => scale(f.height, f.width, (h) => h * ratio);lock.onclick = () => {const on = !locked();@@ -459,6 +512,7 @@ class RichtextEditor extends HTMLElement {lock.classList.toggle('is-active', on);const use = lock.querySelector('use');use.setAttribute('href', `${(use.getAttribute('href') || '').split('#')[0]}#icon-${on ? 'lock' : 'unlock'}`);+ scale();};d.querySelector('[data-rte-act="browse"]').onclick = () => {@@ -475,6 +529,9 @@ class RichtextEditor extends HTMLElement {};d.querySelector('[data-rte-act="submit"]').onclick = () => {+ if (!f.reportValidity()) {+ return;+ }const src = f.src.value.trim();if (!src) {d.close();@@ -500,6 +557,8 @@ class RichtextEditor extends HTMLElement {img.removeAttribute(k);}}+ img.style.removeProperty('width');+ img.style.removeProperty('height');// Only replace the float classes managed by this dialog.img.classList.remove('img-float-left', 'img-float-right');@@ -525,7 +584,7 @@ class RichtextEditor extends HTMLElement {const code = document.createElement('code-editor');code.setAttribute('lang', 'html');const ta = document.createElement('textarea');- ta.value = name === 'source' ? this.editor.getHTML() : '';+ ta.value = name === 'source' ? beautifyHTML(this.editor.getHTML()) : '';code.append(ta);body.replaceChildren(code);@@ -555,11 +614,30 @@ class RichtextEditor extends HTMLElement {let matches = [];let idx = -1;- const clearMarks = () => {- for (const m of this.content.querySelectorAll('mark.rte-find')) {- const parent = m.parentNode;- m.replaceWith(...m.childNodes);- parent.normalize();+ const highlights = ['rte-find', 'rte-find-current'].map((name, priority) => {+ if (!CSS.highlights.has(name)) {+ const highlight = new Highlight();+ highlight.priority = priority;+ CSS.highlights.set(name, highlight);+ }+ return CSS.highlights.get(name);+ });++ const clear = () => {+ for (const range of matches) {+ highlights.forEach((highlight) => highlight.delete(range));+ }+ matches = [];+ };+ this.#clearFind = clear;++ const showCurrent = (scroll) => {+ const range = matches[idx];+ if (range) {+ highlights[1].add(range);+ if (scroll) {+ range.startContainer.parentElement.scrollIntoView({ block: 'center' });+ }}};@@ -567,54 +645,45 @@ class RichtextEditor extends HTMLElement {if (!matches.length) {return;}-- matches[idx]?.classList.remove('is-current');+ highlights[1].delete(matches[idx]);idx = (idx + 1) % matches.length;- matches[idx].classList.add('is-current');- matches[idx].scrollIntoView({ block: 'center' });+ showCurrent(true);};- const doFind = () => {- clearMarks();- matches = [];- idx = -1;-+ const doFind = (scroll = true) => {+ clear();const term = f('find').value;if (!term) {+ idx = -1;count.textContent = '';return;}- const re = new RegExp(`(${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, f('matchcase').checked ? '' : 'i');+ const re = new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), f('matchcase').checked ? 'g' : 'gi');const walker = document.createTreeWalker(this.content, NodeFilter.SHOW_TEXT);- const nodes = [];while (walker.nextNode()) {- nodes.push(walker.currentNode);- }- for (const node of nodes) {- const parts = node.nodeValue.split(re);- if (parts.length < 2) {- continue;+ const node = walker.currentNode;+ for (const match of node.data.matchAll(re)) {+ const range = document.createRange();+ range.setStart(node, match.index);+ range.setEnd(node, match.index + match[0].length);+ matches.push(range);+ highlights[0].add(range);}-- const frag = document.createDocumentFragment();- parts.forEach((part, i) => {- if (i % 2) {- const mark = Object.assign(document.createElement('mark'), { className: 'rte-find', textContent: part });- frag.append(mark);- matches.push(mark);- } else if (part) {- frag.append(part);- }- });- node.replaceWith(frag);}+ idx = scroll ? 0 : Math.max(0, Math.min(idx, matches.length - 1));count.textContent = i18n.ts('editor.findCount', { num: matches.length });- if (matches.length) {- next();+ showCurrent(scroll);+ };+ this.#refreshFind = () => {+ if (panel.matches(':popover-open')) {+ doFind(false);+ } else {+ clear();}};+ this.editor.addEventListener('input', this.#refreshFind);const replaceOne = () => {if (!matches[idx]) {@@ -622,19 +691,21 @@ class RichtextEditor extends HTMLElement {return;}- matches[idx].replaceWith(f('replace').value);- matches.splice(idx, 1);- idx -= 1;- this.sync();- next();+ this.editor.setSelection(matches[idx]);+ this.editor.insertPlainText(f('replace').value, false);};const replaceAll = () => {- matches.forEach((mark) => mark.replaceWith(f('replace').value));- matches = [];- idx = -1;- count.textContent = '';- this.sync();+ if (!matches.length) {+ return;+ }++ this.editor.saveUndoState();+ doFind(false);+ for (const range of [...matches].reverse()) {+ range.deleteContents();+ range.insertNode(document.createTextNode(f('replace').value));+ }};f('find').addEventListener('input', doFind);@@ -658,8 +729,7 @@ class RichtextEditor extends HTMLElement {doFind();}} else {- clearMarks();- this.sync();+ clear();}});}@@ -692,7 +762,7 @@ class RichtextEditor extends HTMLElement {// Keep the popover open so multiple glyphs can be inserted in sequence.b.addEventListener('click', () => {this.editor.focus();- this.editor.insertHTML(ch);+ this.editor.insertPlainText(ch, false);});grid.append(b);@@ -780,9 +850,8 @@ class RichtextEditor extends HTMLElement {'Ctrl-k': link,'Meta-k': link,- // Capture Enter+Shift/Enter to porperly handle para line and line- // break insertion across contexts. Squire's own implementation doesn't- // work properly inside <td>+ // Squire handles both keys; add a trailing BR when its line break+ // would otherwise leave no visible line for the caret (including TDs).Enter: (self, e) => this.#splitBlock(self, e),'Shift-Enter': (self, e) => this.#splitBlock(self, e),};@@ -790,7 +859,7 @@ class RichtextEditor extends HTMLElement {Object.entries(keys).forEach(([key, fn]) => this.editor.setKeyHandler(key, fn));}- // Handle Enter (<p>) and Shift+Enter (<br>) separateely. Squire doesn't have this out of the box.+ // Delegate splitting to Squire, then keep a trailing line break visible.#splitBlock(ed, e) {e.preventDefault();ed.splitBlock(e.shiftKey);diff --git a/static/admin/assets/js/richtext/resize.js b/static/admin/assets/js/richtext/resize.jsdeleted file mode 100644index 92bd5164..00000000--- a/static/admin/assets/js/richtext/resize.js+++ /dev/null@@ -1,97 +0,0 @@-import { closestInSelection } from './data.js';--export function setupResize(cmp) {- const ed = cmp.editor;- let img = null;-- const overlay = document.createElement('div');- overlay.className = 'rte-resize';- overlay.hidden = true;- overlay.innerHTML = ['nw', 'ne', 'sw', 'se'].map((pos) => `<span class="rte-resize-handle rte-${pos}" data-pos="${pos}"></span>`).join('');- cmp.append(overlay);-- const hide = () => {- img = null;- overlay.hidden = true;- };-- const place = () => {- if (!img || !cmp.contains(img)) {- hide();- return;- }-- const wrap = cmp.getBoundingClientRect();- const r = img.getBoundingClientRect();- overlay.hidden = false;-- Object.assign(overlay.style, {- top: `${r.top - wrap.top + cmp.scrollTop}px`,- left: `${r.left - wrap.left}px`,- width: `${r.width}px`,- height: `${r.height}px`,- });- };-- const track = () => {- img = closestInSelection(ed, cmp.content, 'img');- if (img) {- place();- } else {- hide();- }- };-- // Track selection changes and direct clicks on images.- ed.addEventListener('pathChange', track);- ed.addEventListener('select', track);- ed.addEventListener('blur', () => setTimeout(() => {- if (!overlay.matches(':hover')) {- hide();- }- }, 150));-- cmp.content.addEventListener('mouseup', (e) => {- if (e.target.nodeName === 'IMG') {- img = e.target;- place();- }- });-- cmp.addEventListener('scroll', () => img && place(), true);-- // Drag a corner handle to resize, keeping the aspect ratio.- overlay.addEventListener('mousedown', (e) => {- const handle = e.target.closest('.rte-resize-handle');- if (!handle || !img) {- return;- }-- e.preventDefault();- const r = img.getBoundingClientRect();- const sign = handle.dataset.pos.endsWith('w') ? -1 : 1;- const ratio = r.width / (r.height || 1);- let w = 0;- let h = 0;-- const onMove = (ev) => {- w = Math.max(16, Math.round(r.width + sign * (ev.clientX - e.clientX)));- h = Math.round(w / ratio);- Object.assign(overlay.style, { width: `${w}px`, height: `${h}px` });- };-- document.addEventListener('mousemove', onMove);- document.addEventListener('mouseup', () => {- document.removeEventListener('mousemove', onMove);- if (img && w) {- ed.saveUndoState();- img.setAttribute('width', w);- img.setAttribute('height', h);- img.style.removeProperty('width');- img.style.removeProperty('height');- cmp.sync();- }- setTimeout(place, 0);- }, { once: true });- });-}diff --git a/static/admin/build.mjs b/static/admin/build.mjsindex 2fb57ee6..1c0b219c 100644--- a/static/admin/build.mjs+++ b/static/admin/build.mjs@@ -32,7 +32,7 @@ async function build() {await cp(path.join(root, 'node_modules/@knadh/oat/oat.min.css'), path.join(dist, 'oat.min.css'));// ALTCHA is loaded directly by public subscription forms.- await cp(path.join(root, 'node_modules/altcha/dist/main/altcha.umd.cjs'), path.join(root, '../public/static/altcha.umd.js'));+ await cp(path.join(root, 'node_modules/altcha/dist/main/altcha.umd.min.cjs'), path.join(root, '../public/static/altcha.umd.js'));// Entry points = modules loaded directly by a <script> tag: the global main.js and// every per-view module under assets/js/views/.diff --git a/static/admin/partials/campaign-form.html b/static/admin/partials/campaign-form.htmlindex 95415955..025858f1 100644--- a/static/admin/partials/campaign-form.html+++ b/static/admin/partials/campaign-form.html@@ -76,7 +76,7 @@</div>{{- if and (not $isNew) $canSend }}<div class="col-6 col-end hstack justify-end">- <button type="button" class="outline" data-variant="primary" x-cloak x-show="canSchedule" @click="onStart">{{ Icon "clock" }} {{ $root.L.T "campaigns.schedule" }}</button>+ <button type="button" data-variant="primary" x-cloak x-show="canSchedule" @click="onStart">{{ Icon "clock" }} {{ $root.L.T "campaigns.schedule" }}</button><button type="button" class="outline" data-variant="danger" x-cloak x-show="canUnSchedule" @click="onUnschedule">{{ Icon "clock" }} {{ $root.L.T "globals.buttons.unschedule" }}</button></div>{{- end }}diff --git a/static/admin/partials/richtext-editor.html b/static/admin/partials/richtext-editor.htmlindex 071a8405..e20bb7d9 100644--- a/static/admin/partials/richtext-editor.html+++ b/static/admin/partials/richtext-editor.html@@ -135,16 +135,16 @@<ot-dropdown><button type="button" class="ghost" popovertarget="rte-find" title="{{ $L.T "editor.findReplace" }}" aria-label="{{ $L.T "editor.findReplace" }}">{{ Icon "search" $f }}</button><div popover id="rte-find" class="rte-menu rte-find" data-rte-find>- <div data-field><input type="text" name="find" placeholder="{{ $L.T "globals.buttons.find" }}" /></div>- <div data-field><input type="text" name="replace" placeholder="{{ $L.T "globals.fields.replaceWith" }}" /></div>- <label class="rte-find-opt"><input type="checkbox" name="matchcase" /> {{ $L.T "editor.matchCase" }}</label>- <div class="rte-find-foot">+ <input type="text" name="find" placeholder="{{ $L.T "globals.buttons.find" }}" />+ <input type="text" name="replace" placeholder="{{ $L.T "globals.fields.replaceWith" }}" />+ <div class="hstack justify-between">+ <label class="rte-find-opt"><input type="checkbox" name="matchcase" /> {{ $L.T "editor.matchCase" }}</label><small data-hint><span data-rte-findcount></span></small>- <div class="hstack gap-1">- <button type="button" class="outline small" data-rte-act="replace">{{ $L.T "globals.buttons.replace" }}</button>- <button type="button" class="outline small" data-rte-act="replaceAll">{{ $L.T "globals.buttons.replaceAll" }}</button>- <button type="button" class="small" data-variant="primary" data-rte-act="next">{{ $L.T "editor.findNext" }}</button>- </div>+ </div>+ <div class="hstack gap-1">+ <button type="button" class="outline small" data-rte-act="next">{{ $L.T "editor.findNext" }}</button>+ <button type="button" class="outline small" data-rte-act="replace">{{ $L.T "globals.buttons.replace" }}</button>+ <button type="button" class="small" data-rte-act="replaceAll">{{ $L.T "globals.buttons.replaceAll" }}</button></div></div></ot-dropdown>@@ -206,9 +206,9 @@<div data-field><label>{{ $L.T "editor.altText" }}</label><input type="text" name="alt" /></div><div class="hstack gap-2"><div class="rte-img-dims">- <div data-field><label>{{ $L.T "globals.fields.width" }}</label><input type="text" name="width" inputmode="numeric" /></div>+ <div data-field><label>{{ $L.T "globals.fields.width" }}</label><input type="number" name="width" min="1" step="1" inputmode="numeric" /></div><button type="button" class="ghost rte-img-lock is-active" data-rte-act="lock" aria-pressed="true" title="{{ $L.T "editor.constrain" }}" aria-label="{{ $L.T "editor.constrain" }}">{{ Icon "lock" $f }}</button>- <div data-field><label>{{ $L.T "globals.fields.height" }}</label><input type="text" name="height" inputmode="numeric" /></div>+ <div data-field><label>{{ $L.T "globals.fields.height" }}</label><input type="number" name="height" min="1" step="1" inputmode="numeric" /></div></div><div data-field><label>{{ $L.T "editor.float" }}</label>diff --git a/tests/README.md b/tests/README.mdindex e33c0123..b408a550 100644--- a/tests/README.md+++ b/tests/README.md@@ -33,3 +33,10 @@ system dependencies when recreating the dev container.Outside Docker, install the dependencies described in the developer guide.From `tests/`, use `bun run test` for headless tests or `bun run test:ui` for theinteractive UI.++The rich-text editor regression tests can also run directly against local+frontend source, without starting listmonk or touching a database. From `tests/`:++```sh+bun playwright test --config playwright.richtext.config.js richtext.spec.js+```