domma-cms 1.7.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/admin/js/lib/mail-compose.js +1 -0
  3. package/admin/js/templates/call-new.html +1 -1
  4. package/admin/js/views/call-new.js +1 -1
  5. package/admin/js/views/contacts.js +15 -15
  6. package/admin/js/views/form-submissions.js +2 -2
  7. package/package.json +1 -1
  8. package/plugins/_lib/admin/mail/compose-window.js +3 -1
  9. package/plugins/_lib/admin/mail/identity.js +18 -3
  10. package/plugins/_lib/admin/mail/reader-view.js +32 -3
  11. package/plugins/blog/CLAUDE.md +4 -0
  12. package/plugins/blog/admin/lib/email.js +191 -0
  13. package/plugins/blog/admin/views/comments.js +3 -1
  14. package/plugins/blog/plugin.json +2 -2
  15. package/plugins/blog/plugin.public.js +1 -1
  16. package/plugins/blog/tests/email.test.js +69 -0
  17. package/plugins/booking/CLAUDE.md +4 -0
  18. package/plugins/booking/admin/lib/email.js +191 -0
  19. package/plugins/booking/admin/views/panels.js +7 -3
  20. package/plugins/booking/plugin.json +1 -1
  21. package/plugins/booking/tests/email.test.js +69 -0
  22. package/plugins/free-tier.lock.json +27 -19
  23. package/plugins/shopping-cart/CLAUDE.md +4 -0
  24. package/plugins/shopping-cart/admin/lib/email.js +191 -0
  25. package/plugins/shopping-cart/admin/views/orders.js +11 -3
  26. package/plugins/shopping-cart/plugin.json +2 -2
  27. package/plugins/shopping-cart/tests/email.test.js +69 -0
  28. package/plugins/support/CLAUDE.md +4 -0
  29. package/plugins/support/admin/lib/email.js +191 -0
  30. package/plugins/support/admin/views/desk.js +4 -1
  31. package/plugins/support/admin/views/inbox.js +6 -2
  32. package/plugins/support/plugin.json +2 -2
  33. package/plugins/support/tests/email.test.js +69 -0
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Email someone from this Tool: Email Pro's compose window when the user can
3
+ * send from it, otherwise the device's mail program through `mailto:`.
4
+ *
5
+ * Core makes the choice (`/admin/js/lib/mail-compose.js`, CMS 1.6.61+). It is
6
+ * imported at RUN time, never statically, so this Tool still loads on an older
7
+ * core - where every action keeps the plain `mailto:` it always had.
8
+ *
9
+ * `emailTo()` is for menu actions; `routeMailLinks()` is for a visible
10
+ * `<a href="mailto:…">` - the link stays a link (copy, hover, middle-click all
11
+ * still work) and a plain click goes the same way as the menu action.
12
+ *
13
+ * @module blog/admin/lib/email
14
+ */
15
+
16
+ const CORE = '/admin/js/lib/mail-compose.js';
17
+ let core = null;
18
+
19
+ /** The core module, or null on a core without it. Asked once. */
20
+ const loadCore = () => (core ??= import(CORE).catch(() => null));
21
+
22
+ /** Longest subject or body carried (as core's). */
23
+ const MAX_TEXT = 2000;
24
+ /** Longest mailto: handed to the device - mail programs cut or refuse longer ones. */
25
+ const MAX_MAILTO = 1800;
26
+
27
+ /**
28
+ * Something that can only be an email address: one @, no spaces or line
29
+ * breaks, nothing that would start another recipient or a query.
30
+ *
31
+ * @param {*} value
32
+ * @returns {boolean}
33
+ */
34
+ export function looksLikeAddress(value) {
35
+ return typeof value === 'string' && /^[^\s@<>,;"?&]+@[^\s@<>,;"?&]+$/.test(value);
36
+ }
37
+
38
+ /** Valid addresses only, once each (ignoring case), from a string, `{address}`/`{email}`, or a list. */
39
+ function addressesOf(list) {
40
+ const seen = new Set();
41
+ return (Array.isArray(list) ? list : list == null ? [] : [list])
42
+ .map(x => String(typeof x === 'string' ? x : (x?.address ?? x?.email ?? '')).trim())
43
+ .filter(a => looksLikeAddress(a) && !seen.has(a.toLowerCase()) && seen.add(a.toLowerCase()));
44
+ }
45
+
46
+ /** Trim and cap; a subject loses its line breaks (they would be a header). */
47
+ function cleanText(value, {oneLine = false} = {}) {
48
+ let text = String(value ?? '');
49
+ if (oneLine) text = text.replace(/[\r\n]+/g, ' ');
50
+ return text.slice(0, MAX_TEXT).trim();
51
+ }
52
+
53
+ /**
54
+ * The request as a `mailto:` link (the fallback on an older core).
55
+ *
56
+ * @param {{to?: *, cc?: *, bcc?: *, subject?: string, body?: string}} request
57
+ * @returns {string}
58
+ */
59
+ export function mailtoHref({to, cc, bcc, subject, body} = {}) {
60
+ const enc = (list) => addressesOf(list).map(a => encodeURIComponent(a).replace(/%40/g, '@')).join(',');
61
+ const s = cleanText(subject, {oneLine: true});
62
+ const b = cleanText(body);
63
+ const query = [];
64
+ if (enc(cc)) query.push(`cc=${enc(cc)}`);
65
+ if (enc(bcc)) query.push(`bcc=${enc(bcc)}`);
66
+ if (s) query.push(`subject=${encodeURIComponent(s)}`);
67
+ if (b) query.push(`body=${encodeURIComponent(b)}`);
68
+ return `mailto:${enc(to)}${query.length ? `?${query.join('&')}` : ''}`;
69
+ }
70
+
71
+ /** Copy text: the clipboard, else the old copy command, else a box to copy it from by hand. */
72
+ async function copyText(text) {
73
+ try {
74
+ await navigator.clipboard.writeText(text);
75
+ return true;
76
+ } catch { /* next */ }
77
+ const box = document.createElement('textarea');
78
+ box.className = 'form-input';
79
+ box.readOnly = true;
80
+ box.rows = 6;
81
+ box.value = text;
82
+ try {
83
+ box.style.position = 'fixed';
84
+ box.style.opacity = '0';
85
+ document.body.appendChild(box);
86
+ box.select();
87
+ if (document.execCommand('copy')) return true;
88
+ } catch { /* next */ } finally {
89
+ box.remove();
90
+ box.style.position = '';
91
+ box.style.opacity = '';
92
+ }
93
+ const modal = E.modal({title: 'Copy the addresses', size: 'medium', buttons: [{id: 'close', text: 'Close', variant: 'secondary'}]});
94
+ modal.element.appendChild(box); // light DOM: setContent would strip the textarea
95
+ modal.open();
96
+ box.select();
97
+ return false;
98
+ }
99
+
100
+ /**
101
+ * Hand the request to the device's mail program - unless the link would be
102
+ * too long for it, when the addresses are copied instead and the toast says
103
+ * what did not go.
104
+ */
105
+ async function openMailto(request) {
106
+ const href = mailtoHref(request);
107
+ if (href.length <= MAX_MAILTO) {
108
+ location.href = href;
109
+ return 'mailto';
110
+ }
111
+ const all = addressesOf([...addressesOf(request.to), ...addressesOf(request.cc), ...addressesOf(request.bcc)]);
112
+ const copied = all.length ? await copyText(all.join(', ')) : false;
113
+ const lost = [cleanText(request.subject) && 'the subject', cleanText(request.body) && 'the message'].filter(Boolean);
114
+ E.toast(`Too long for your mail program to open. ${all.length
115
+ ? `${copied ? 'The' : 'Copy the'} ${all.length} address${all.length === 1 ? '' : 'es'}${copied ? ' are copied' : ''} - paste them into Bcc of a new email.` : ''}${lost.length ? ` Not carried over: ${lost.join(' and ')}.` : ''}`,
116
+ {type: 'warning', duration: 9000});
117
+ return 'copied';
118
+ }
119
+
120
+ const decode = (s) => { try { return decodeURIComponent(s); } catch { return s; } };
121
+
122
+ /**
123
+ * A `mailto:` link read back into a request (what a visible link carries).
124
+ * When the address part holds anything that is not an address, the query
125
+ * is ignored: an address stored as `me@x.com?body=…` must not prefill a message.
126
+ *
127
+ * @param {string} href
128
+ * @returns {null|{to: string[], cc: string[], bcc: string[], subject: string, body: string}}
129
+ */
130
+ export function parseMailto(href) {
131
+ const m = String(href ?? '').match(/^mailto:([^?]*)(?:\?(.*))?$/i);
132
+ if (!m) return null;
133
+ const split = (s) => decode(s || '').split(/[,;]/).map(x => x.trim()).filter(Boolean);
134
+ const named = split(m[1]);
135
+ const out = {to: addressesOf(named), cc: [], bcc: [], subject: '', body: ''};
136
+ if (named.some(a => !looksLikeAddress(a))) return out;
137
+ for (const pair of (m[2] || '').split('&')) {
138
+ const i = pair.indexOf('=');
139
+ if (i < 1) continue;
140
+ const key = pair.slice(0, i).toLowerCase();
141
+ const value = pair.slice(i + 1);
142
+ if (key === 'to') out.to = addressesOf([...out.to, ...split(value)]);
143
+ else if (key === 'cc' || key === 'bcc') out[key] = addressesOf([...out[key], ...split(value)]);
144
+ else if (key === 'subject') out.subject = cleanText(decode(value), {oneLine: true});
145
+ else if (key === 'body') out.body = cleanText(decode(value));
146
+ }
147
+ return out;
148
+ }
149
+
150
+ /**
151
+ * Email someone. Recipients are `{name, address}`, `{name, email}` or bare
152
+ * addresses; several people belong in `bcc`, so nobody sees the others.
153
+ * With nobody to address (a link to pass on) compose still opens, To empty.
154
+ *
155
+ * @param {{to?: *, cc?: *, bcc?: *, subject?: string, body?: string}} request
156
+ * @returns {Promise<'compose'|'mailto'|'copied'|'none'>}
157
+ */
158
+ export async function emailTo(request = {}) {
159
+ const mail = await loadCore();
160
+ if (!mail) return openMailto(request);
161
+ const r = mail.composeRequest(request);
162
+ if (r.to.length || r.cc.length || r.bcc.length) return mail.openEmail(r);
163
+ if (await mail.emailReady()) {
164
+ location.hash = mail.composeHash(r);
165
+ return 'compose';
166
+ }
167
+ location.href = mail.mailtoHref(r);
168
+ return 'mailto';
169
+ }
170
+
171
+ /**
172
+ * Send plain clicks on the `mailto:` links inside `root` through `emailTo()`.
173
+ * A modified click (new tab/window) or one already handled is left alone.
174
+ *
175
+ * @param {Element} root
176
+ * @returns {() => void} removes the listener
177
+ */
178
+ export function routeMailLinks(root) {
179
+ if (!root) return () => {};
180
+ const onClick = (e) => {
181
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
182
+ const a = e.target?.closest?.('a[href^="mailto:" i]');
183
+ if (!a || !root.contains(a)) return;
184
+ const request = parseMailto(a.getAttribute('href'));
185
+ if (!request) return;
186
+ e.preventDefault();
187
+ emailTo(request);
188
+ };
189
+ root.addEventListener('click', onClick);
190
+ return () => root.removeEventListener('click', onClick);
191
+ }
@@ -216,7 +216,9 @@ export const commentsView = {
216
216
  {label: 'Open the post', icon: 'edit', visible: Boolean(c.postId) && posts.peek().some(p => p.id === c.postId),
217
217
  action: () => R.navigate(`#/plugins/blog/posts/${c.postId}`)},
218
218
  {label: 'Reply by email', icon: 'mail', visible: Boolean(c.authorEmail),
219
- action: () => { location.href = `mailto:${encodeURIComponent(c.authorEmail)}`; }},
219
+ // Email Pro's compose when this user can send from it, else the device's mail program.
220
+ action: () => import(`../lib/email.js?v=${ASSET_VERSION}`).then(m => m.emailTo({to: [{name: c.authorName, address: c.authorEmail}]}))
221
+ .catch(() => { location.href = `mailto:${encodeURIComponent(c.authorEmail)}`; })},
220
222
  {type: 'divider'},
221
223
  {label: 'Delete', icon: 'trash', danger: true, action: () => remove(c.id)}
222
224
  ]);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "blog",
3
3
  "displayName": "Blog",
4
- "version": "1.10.0",
4
+ "version": "1.10.1",
5
5
  "tier": "free",
6
6
  "description": "Public-facing blog with posts, categories and comments - layouts and listings built from editable blocks.",
7
7
  "author": "Domma CMS",
@@ -91,7 +91,7 @@
91
91
  "exportName": "categoriesView"
92
92
  },
93
93
  "plugin-blog-comments": {
94
- "entry": "blog/admin/views/comments.js?v=11",
94
+ "entry": "blog/admin/views/comments.js?v=12",
95
95
  "exportName": "commentsView"
96
96
  },
97
97
  "plugin-blog-settings": {
@@ -24,7 +24,7 @@ const __dirname = fileURLToPath(new URL('.', import.meta.url));
24
24
  const TEMPLATES_DIR = path.join(__dirname, 'templates');
25
25
 
26
26
  /** Bumped with the plugin, so a release is never served a stale script. */
27
- const ASSET_V = '1.10.0';
27
+ const ASSET_V = '1.10.1';
28
28
 
29
29
  /**
30
30
  * Above this many posts a listing pages on the server instead: the browser
@@ -0,0 +1,69 @@
1
+ /**
2
+ * admin/lib/email.js - the mailto: fallback and link reading (node has no
3
+ * /admin/js/lib/mail-compose.js, so emailTo() here is the older-core path).
4
+ */
5
+ import {test} from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import {emailTo, looksLikeAddress, mailtoHref, parseMailto} from '../admin/lib/email.js';
8
+
9
+ test('mailtoHref: one person in To, subject and body encoded, @ readable', () => {
10
+ assert.equal(mailtoHref({to: [{name: 'Ann', address: 'ann+x@example.test'}], subject: 'Hi & bye', body: 'Line 1\nLine 2'}),
11
+ 'mailto:ann%2Bx@example.test?subject=Hi%20%26%20bye&body=Line%201%0ALine%202');
12
+ });
13
+
14
+ test('mailtoHref: several people in Bcc, strings and contacts alike', () => {
15
+ assert.equal(mailtoHref({bcc: ['a@x.test', {email: 'b@x.test'}], subject: 'S'}), 'mailto:?bcc=a@x.test,b@x.test&subject=S');
16
+ });
17
+
18
+ test('parseMailto reads back what mailtoHref writes, and plain links', () => {
19
+ const r = parseMailto(mailtoHref({to: 'a@x.test', cc: ['c@x.test'], bcc: ['b@x.test', 'd@x.test'], subject: 'Hi + there', body: 'Join: https://x.test/?a=1&b=2'}));
20
+ assert.deepEqual(r, {to: ['a@x.test'], cc: ['c@x.test'], bcc: ['b@x.test', 'd@x.test'], subject: 'Hi + there', body: 'Join: https://x.test/?a=1&b=2'});
21
+ assert.deepEqual(parseMailto('mailto:ann@example.test'), {to: ['ann@example.test'], cc: [], bcc: [], subject: '', body: ''});
22
+ assert.equal(parseMailto('https://example.test'), null);
23
+ });
24
+
25
+ test('emailTo on a core without mail-compose.js keeps the old mailto:', async () => {
26
+ const saved = globalThis.location;
27
+ globalThis.location = {href: '', hash: ''};
28
+ try {
29
+ assert.equal(await emailTo({to: [{name: 'Ann', address: 'ann@example.test'}], subject: 'Hello'}), 'mailto');
30
+ assert.equal(globalThis.location.href, 'mailto:ann@example.test?subject=Hello');
31
+ assert.equal(globalThis.location.hash, '');
32
+ } finally {
33
+ globalThis.location = saved;
34
+ }
35
+ });
36
+
37
+ test('fallback hardening: bad addresses dropped, repeats once, subject one line, text capped', () => {
38
+ for (const bad of ['a b@x.test', 'a@x.test\r\nBcc: c@x.test', '<a@x.test>', 'a@x.test,b@x.test', 'a@x.test?body=hi', 'nobody']) assert.equal(looksLikeAddress(bad), false, bad);
39
+ const href = mailtoHref({to: ['A@x.test', 'a@x.test', 'a b@x.test', 'me@x.test?body=evil'], subject: 'Hi\r\nBcc: c@x.test', body: 'x'.repeat(3000)});
40
+ assert.ok(href.startsWith('mailto:A@x.test?subject=Hi%20Bcc%3A%20c%40x.test&body='), href);
41
+ assert.equal(decodeURIComponent(href.split('body=')[1]).length, 2000);
42
+ });
43
+
44
+ test('parseMailto ignores the query when the address part is not an address', () => {
45
+ // An address stored as "me@x.com?body=..." and encoded into a link.
46
+ assert.deepEqual(parseMailto(`mailto:${encodeURIComponent('me@x.test?body=Pay now')}`), {to: [], cc: [], bcc: [], subject: '', body: ''});
47
+ assert.deepEqual(parseMailto('mailto:me@x.test%0D%0Abcc:z@x.test?subject=Hi&bcc=y@x.test'), {to: [], cc: [], bcc: [], subject: '', body: ''});
48
+ assert.deepEqual(parseMailto('mailto:?subject=Join&body=link').subject, 'Join');
49
+ });
50
+
51
+ test('emailTo on an old core: a mailto over 1800 characters is not opened - the addresses are copied', async () => {
52
+ const saved = {location: globalThis.location, E: globalThis.E, nav: Object.getOwnPropertyDescriptor(globalThis, 'navigator')};
53
+ let copied = '';
54
+ const toasts = [];
55
+ globalThis.location = {href: '', hash: ''};
56
+ globalThis.E = {toast: (m) => toasts.push(m)};
57
+ Object.defineProperty(globalThis, 'navigator', {value: {clipboard: {writeText: async (t) => { copied = t; }}}, configurable: true});
58
+ try {
59
+ const bcc = Array.from({length: 120}, (_, i) => `person${i}@example.test`);
60
+ assert.equal(await emailTo({bcc, subject: 'News'}), 'copied');
61
+ assert.equal(globalThis.location.href, '');
62
+ assert.equal(copied, bcc.join(', '));
63
+ assert.match(toasts[0], /120 addresses are copied.*Not carried over: the subject/);
64
+ } finally {
65
+ globalThis.location = saved.location;
66
+ globalThis.E = saved.E;
67
+ if (saved.nav) Object.defineProperty(globalThis, 'navigator', saved.nav); else delete globalThis.navigator;
68
+ }
69
+ });
@@ -193,3 +193,7 @@ only to roles that hold it.
193
193
  cannot tell Escape from Cancel). Booking Pro's sections are not drafted - the section contract cannot put values back.
194
194
  - First loads use core skeletons through `kit.whileLoading` (`.bk-loading-slot`) on the host, Bookings and the Diary.
195
195
  - No ContextMenu-key handler in wireRows: Windows Chrome opens its own menu on that key too. Shift+F10 only.
196
+
197
+ ## 1.7.1
198
+
199
+ - **Email (openEmail).** Email actions go through `admin/lib/email.js`: `emailTo()` for menu actions (several people always in Bcc), `routeMailLinks(root)` for visible `mailto:` links. Core's `/admin/js/lib/mail-compose.js` (CMS 1.6.61+) opens Email Pro's compose window when the user has a mailbox there; older cores keep a cleaned, capped `mailto:` (over 1800 chars the addresses are copied instead). Stored addresses are encoded into links, or shown as text when invalid. Never set `location.href = 'mailto:…'` directly.
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Email someone from this Tool: Email Pro's compose window when the user can
3
+ * send from it, otherwise the device's mail program through `mailto:`.
4
+ *
5
+ * Core makes the choice (`/admin/js/lib/mail-compose.js`, CMS 1.6.61+). It is
6
+ * imported at RUN time, never statically, so this Tool still loads on an older
7
+ * core - where every action keeps the plain `mailto:` it always had.
8
+ *
9
+ * `emailTo()` is for menu actions; `routeMailLinks()` is for a visible
10
+ * `<a href="mailto:…">` - the link stays a link (copy, hover, middle-click all
11
+ * still work) and a plain click goes the same way as the menu action.
12
+ *
13
+ * @module booking/admin/lib/email
14
+ */
15
+
16
+ const CORE = '/admin/js/lib/mail-compose.js';
17
+ let core = null;
18
+
19
+ /** The core module, or null on a core without it. Asked once. */
20
+ const loadCore = () => (core ??= import(CORE).catch(() => null));
21
+
22
+ /** Longest subject or body carried (as core's). */
23
+ const MAX_TEXT = 2000;
24
+ /** Longest mailto: handed to the device - mail programs cut or refuse longer ones. */
25
+ const MAX_MAILTO = 1800;
26
+
27
+ /**
28
+ * Something that can only be an email address: one @, no spaces or line
29
+ * breaks, nothing that would start another recipient or a query.
30
+ *
31
+ * @param {*} value
32
+ * @returns {boolean}
33
+ */
34
+ export function looksLikeAddress(value) {
35
+ return typeof value === 'string' && /^[^\s@<>,;"?&]+@[^\s@<>,;"?&]+$/.test(value);
36
+ }
37
+
38
+ /** Valid addresses only, once each (ignoring case), from a string, `{address}`/`{email}`, or a list. */
39
+ function addressesOf(list) {
40
+ const seen = new Set();
41
+ return (Array.isArray(list) ? list : list == null ? [] : [list])
42
+ .map(x => String(typeof x === 'string' ? x : (x?.address ?? x?.email ?? '')).trim())
43
+ .filter(a => looksLikeAddress(a) && !seen.has(a.toLowerCase()) && seen.add(a.toLowerCase()));
44
+ }
45
+
46
+ /** Trim and cap; a subject loses its line breaks (they would be a header). */
47
+ function cleanText(value, {oneLine = false} = {}) {
48
+ let text = String(value ?? '');
49
+ if (oneLine) text = text.replace(/[\r\n]+/g, ' ');
50
+ return text.slice(0, MAX_TEXT).trim();
51
+ }
52
+
53
+ /**
54
+ * The request as a `mailto:` link (the fallback on an older core).
55
+ *
56
+ * @param {{to?: *, cc?: *, bcc?: *, subject?: string, body?: string}} request
57
+ * @returns {string}
58
+ */
59
+ export function mailtoHref({to, cc, bcc, subject, body} = {}) {
60
+ const enc = (list) => addressesOf(list).map(a => encodeURIComponent(a).replace(/%40/g, '@')).join(',');
61
+ const s = cleanText(subject, {oneLine: true});
62
+ const b = cleanText(body);
63
+ const query = [];
64
+ if (enc(cc)) query.push(`cc=${enc(cc)}`);
65
+ if (enc(bcc)) query.push(`bcc=${enc(bcc)}`);
66
+ if (s) query.push(`subject=${encodeURIComponent(s)}`);
67
+ if (b) query.push(`body=${encodeURIComponent(b)}`);
68
+ return `mailto:${enc(to)}${query.length ? `?${query.join('&')}` : ''}`;
69
+ }
70
+
71
+ /** Copy text: the clipboard, else the old copy command, else a box to copy it from by hand. */
72
+ async function copyText(text) {
73
+ try {
74
+ await navigator.clipboard.writeText(text);
75
+ return true;
76
+ } catch { /* next */ }
77
+ const box = document.createElement('textarea');
78
+ box.className = 'form-input';
79
+ box.readOnly = true;
80
+ box.rows = 6;
81
+ box.value = text;
82
+ try {
83
+ box.style.position = 'fixed';
84
+ box.style.opacity = '0';
85
+ document.body.appendChild(box);
86
+ box.select();
87
+ if (document.execCommand('copy')) return true;
88
+ } catch { /* next */ } finally {
89
+ box.remove();
90
+ box.style.position = '';
91
+ box.style.opacity = '';
92
+ }
93
+ const modal = E.modal({title: 'Copy the addresses', size: 'medium', buttons: [{id: 'close', text: 'Close', variant: 'secondary'}]});
94
+ modal.element.appendChild(box); // light DOM: setContent would strip the textarea
95
+ modal.open();
96
+ box.select();
97
+ return false;
98
+ }
99
+
100
+ /**
101
+ * Hand the request to the device's mail program - unless the link would be
102
+ * too long for it, when the addresses are copied instead and the toast says
103
+ * what did not go.
104
+ */
105
+ async function openMailto(request) {
106
+ const href = mailtoHref(request);
107
+ if (href.length <= MAX_MAILTO) {
108
+ location.href = href;
109
+ return 'mailto';
110
+ }
111
+ const all = addressesOf([...addressesOf(request.to), ...addressesOf(request.cc), ...addressesOf(request.bcc)]);
112
+ const copied = all.length ? await copyText(all.join(', ')) : false;
113
+ const lost = [cleanText(request.subject) && 'the subject', cleanText(request.body) && 'the message'].filter(Boolean);
114
+ E.toast(`Too long for your mail program to open. ${all.length
115
+ ? `${copied ? 'The' : 'Copy the'} ${all.length} address${all.length === 1 ? '' : 'es'}${copied ? ' are copied' : ''} - paste them into Bcc of a new email.` : ''}${lost.length ? ` Not carried over: ${lost.join(' and ')}.` : ''}`,
116
+ {type: 'warning', duration: 9000});
117
+ return 'copied';
118
+ }
119
+
120
+ const decode = (s) => { try { return decodeURIComponent(s); } catch { return s; } };
121
+
122
+ /**
123
+ * A `mailto:` link read back into a request (what a visible link carries).
124
+ * When the address part holds anything that is not an address, the query
125
+ * is ignored: an address stored as `me@x.com?body=…` must not prefill a message.
126
+ *
127
+ * @param {string} href
128
+ * @returns {null|{to: string[], cc: string[], bcc: string[], subject: string, body: string}}
129
+ */
130
+ export function parseMailto(href) {
131
+ const m = String(href ?? '').match(/^mailto:([^?]*)(?:\?(.*))?$/i);
132
+ if (!m) return null;
133
+ const split = (s) => decode(s || '').split(/[,;]/).map(x => x.trim()).filter(Boolean);
134
+ const named = split(m[1]);
135
+ const out = {to: addressesOf(named), cc: [], bcc: [], subject: '', body: ''};
136
+ if (named.some(a => !looksLikeAddress(a))) return out;
137
+ for (const pair of (m[2] || '').split('&')) {
138
+ const i = pair.indexOf('=');
139
+ if (i < 1) continue;
140
+ const key = pair.slice(0, i).toLowerCase();
141
+ const value = pair.slice(i + 1);
142
+ if (key === 'to') out.to = addressesOf([...out.to, ...split(value)]);
143
+ else if (key === 'cc' || key === 'bcc') out[key] = addressesOf([...out[key], ...split(value)]);
144
+ else if (key === 'subject') out.subject = cleanText(decode(value), {oneLine: true});
145
+ else if (key === 'body') out.body = cleanText(decode(value));
146
+ }
147
+ return out;
148
+ }
149
+
150
+ /**
151
+ * Email someone. Recipients are `{name, address}`, `{name, email}` or bare
152
+ * addresses; several people belong in `bcc`, so nobody sees the others.
153
+ * With nobody to address (a link to pass on) compose still opens, To empty.
154
+ *
155
+ * @param {{to?: *, cc?: *, bcc?: *, subject?: string, body?: string}} request
156
+ * @returns {Promise<'compose'|'mailto'|'copied'|'none'>}
157
+ */
158
+ export async function emailTo(request = {}) {
159
+ const mail = await loadCore();
160
+ if (!mail) return openMailto(request);
161
+ const r = mail.composeRequest(request);
162
+ if (r.to.length || r.cc.length || r.bcc.length) return mail.openEmail(r);
163
+ if (await mail.emailReady()) {
164
+ location.hash = mail.composeHash(r);
165
+ return 'compose';
166
+ }
167
+ location.href = mail.mailtoHref(r);
168
+ return 'mailto';
169
+ }
170
+
171
+ /**
172
+ * Send plain clicks on the `mailto:` links inside `root` through `emailTo()`.
173
+ * A modified click (new tab/window) or one already handled is left alone.
174
+ *
175
+ * @param {Element} root
176
+ * @returns {() => void} removes the listener
177
+ */
178
+ export function routeMailLinks(root) {
179
+ if (!root) return () => {};
180
+ const onClick = (e) => {
181
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
182
+ const a = e.target?.closest?.('a[href^="mailto:" i]');
183
+ if (!a || !root.contains(a)) return;
184
+ const request = parseMailto(a.getAttribute('href'));
185
+ if (!request) return;
186
+ e.preventDefault();
187
+ emailTo(request);
188
+ };
189
+ root.addEventListener('click', onClick);
190
+ return () => root.removeEventListener('click', onClick);
191
+ }
@@ -14,6 +14,7 @@ import {
14
14
  import {atWallClock, isDate, toMinutes, wallClock} from '/plugins/booking/public/lib/time.js';
15
15
  import {answerRows, placesLabel, sourceLabel, withNames} from '../lib/details.js';
16
16
  import {mountSections} from '../lib/extension-sections.js';
17
+ import {emailTo, looksLikeAddress, routeMailLinks} from '../lib/email.js';
17
18
 
18
19
  /** Places per session a service takes (Booking Pro's classes); 1 for an appointment. */
19
20
  const capacityOf = (svc) => Math.max(1, Number(svc?.ext?.['booking-pro']?.capacity) || 1);
@@ -45,7 +46,7 @@ export function bookingMenu(ctx, b) {
45
46
  {label: 'Mark as no-show', icon: 'user-remove', disabled: () => !live || b.status === 'no-show', action: () => setStatus(ctx, b, 'no-show')},
46
47
  {label: 'Back to booked', icon: 'rotate-ccw', disabled: () => !live || b.status === 'confirmed', action: () => setStatus(ctx, b, 'confirmed')},
47
48
  {type: 'divider'},
48
- {label: 'Email the customer', icon: 'mail', disabled: () => !b.email, action: () => { location.href = `mailto:${encodeURIComponent(b.email)}?subject=${encodeURIComponent(`Your booking: ${b.serviceName}`)}`; }},
49
+ {label: 'Email the customer', icon: 'mail', disabled: () => !b.email, action: () => emailTo({to: [{name: b.name, address: b.email}], subject: `Your booking: ${b.serviceName}`})},
49
50
  ...(b.contactId && ctx.boot.contacts ? [{label: 'Open Contacts', icon: 'users', action: () => { location.hash = '#/contacts'; }}] : []),
50
51
  {type: 'divider'},
51
52
  live
@@ -510,6 +511,7 @@ export async function openBooking(ctx, id) {
510
511
  const answers = answerRows(b.ext?.answers, ctx.boot.services.find(x => x.id === b.serviceId));
511
512
  let panel = null;
512
513
  let sections = null;
514
+ let unrouteMail = () => {};
513
515
  const act = (fn) => async () => { const r = await fn(); if (r) panel?.close(); };
514
516
  panel = await openPanel({
515
517
  title: `${b.serviceName}: ${b.name}`,
@@ -522,8 +524,10 @@ export async function openBooking(ctx, id) {
522
524
  values: () => ({staffNote: staffNote.peek()}),
523
525
  apply: (v) => { if (typeof v.staffNote === 'string') staffNote.value = v.staffNote; }
524
526
  },
525
- cleanup: () => sections?.destroy(),
527
+ cleanup: () => { sections?.destroy(); unrouteMail(); },
526
528
  before: (el) => {
529
+ // The customer's address stays a link; a click goes to Email Pro's compose when it can.
530
+ unrouteMail = routeMailLinks(el);
527
531
  sections = mountSections(el.querySelector('[data-part="ext"]'), 'bookingPanel', {boot: ctx.boot, booking: b,
528
532
  refresh: () => { panel?.close(true); ctx.openBooking ? ctx.openBooking(b.id) : openBooking(ctx, b.id); }});
529
533
  },
@@ -537,7 +541,7 @@ export async function openBooking(ctx, id) {
537
541
  ${detail('With', withNames(b))}
538
542
  ${b.online ? detail('Where', 'Online - a video call') : ''}
539
543
  ${detail('Customer', b.name)}
540
- ${detail('Email', b.email, b.email ? `mailto:${b.email}` : '')}
544
+ ${detail('Email', b.email, looksLikeAddress(b.email) ? `mailto:${encodeURIComponent(b.email)}` : '')}
541
545
  ${detail('Phone', b.phone, b.phone ? `tel:${b.phone.replace(/[^+\d]/g, '')}` : '')}
542
546
  ${detail('Their notes', b.notes)}
543
547
  ${detail('Booked', `${sourceLabel(b.source)} · ${fmtDateTime(b.createdAt || b.history?.[0]?.at)}`)}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "booking",
3
3
  "displayName": "Booking",
4
- "version": "1.7.0",
4
+ "version": "1.7.1",
5
5
  "tier": "free",
6
6
  "description": "Let people book appointments with you or your team, and rooms or equipment, from a booking page on your site. Opening hours, days off and buffers; confirmation and reminder emails with a link to change or cancel; a diary in the admin. Book straight from a contact or an email.",
7
7
  "author": "Domma CMS",
@@ -0,0 +1,69 @@
1
+ /**
2
+ * admin/lib/email.js - the mailto: fallback and link reading (node has no
3
+ * /admin/js/lib/mail-compose.js, so emailTo() here is the older-core path).
4
+ */
5
+ import {test} from 'node:test';
6
+ import assert from 'node:assert/strict';
7
+ import {emailTo, looksLikeAddress, mailtoHref, parseMailto} from '../admin/lib/email.js';
8
+
9
+ test('mailtoHref: one person in To, subject and body encoded, @ readable', () => {
10
+ assert.equal(mailtoHref({to: [{name: 'Ann', address: 'ann+x@example.test'}], subject: 'Hi & bye', body: 'Line 1\nLine 2'}),
11
+ 'mailto:ann%2Bx@example.test?subject=Hi%20%26%20bye&body=Line%201%0ALine%202');
12
+ });
13
+
14
+ test('mailtoHref: several people in Bcc, strings and contacts alike', () => {
15
+ assert.equal(mailtoHref({bcc: ['a@x.test', {email: 'b@x.test'}], subject: 'S'}), 'mailto:?bcc=a@x.test,b@x.test&subject=S');
16
+ });
17
+
18
+ test('parseMailto reads back what mailtoHref writes, and plain links', () => {
19
+ const r = parseMailto(mailtoHref({to: 'a@x.test', cc: ['c@x.test'], bcc: ['b@x.test', 'd@x.test'], subject: 'Hi + there', body: 'Join: https://x.test/?a=1&b=2'}));
20
+ assert.deepEqual(r, {to: ['a@x.test'], cc: ['c@x.test'], bcc: ['b@x.test', 'd@x.test'], subject: 'Hi + there', body: 'Join: https://x.test/?a=1&b=2'});
21
+ assert.deepEqual(parseMailto('mailto:ann@example.test'), {to: ['ann@example.test'], cc: [], bcc: [], subject: '', body: ''});
22
+ assert.equal(parseMailto('https://example.test'), null);
23
+ });
24
+
25
+ test('emailTo on a core without mail-compose.js keeps the old mailto:', async () => {
26
+ const saved = globalThis.location;
27
+ globalThis.location = {href: '', hash: ''};
28
+ try {
29
+ assert.equal(await emailTo({to: [{name: 'Ann', address: 'ann@example.test'}], subject: 'Hello'}), 'mailto');
30
+ assert.equal(globalThis.location.href, 'mailto:ann@example.test?subject=Hello');
31
+ assert.equal(globalThis.location.hash, '');
32
+ } finally {
33
+ globalThis.location = saved;
34
+ }
35
+ });
36
+
37
+ test('fallback hardening: bad addresses dropped, repeats once, subject one line, text capped', () => {
38
+ for (const bad of ['a b@x.test', 'a@x.test\r\nBcc: c@x.test', '<a@x.test>', 'a@x.test,b@x.test', 'a@x.test?body=hi', 'nobody']) assert.equal(looksLikeAddress(bad), false, bad);
39
+ const href = mailtoHref({to: ['A@x.test', 'a@x.test', 'a b@x.test', 'me@x.test?body=evil'], subject: 'Hi\r\nBcc: c@x.test', body: 'x'.repeat(3000)});
40
+ assert.ok(href.startsWith('mailto:A@x.test?subject=Hi%20Bcc%3A%20c%40x.test&body='), href);
41
+ assert.equal(decodeURIComponent(href.split('body=')[1]).length, 2000);
42
+ });
43
+
44
+ test('parseMailto ignores the query when the address part is not an address', () => {
45
+ // An address stored as "me@x.com?body=..." and encoded into a link.
46
+ assert.deepEqual(parseMailto(`mailto:${encodeURIComponent('me@x.test?body=Pay now')}`), {to: [], cc: [], bcc: [], subject: '', body: ''});
47
+ assert.deepEqual(parseMailto('mailto:me@x.test%0D%0Abcc:z@x.test?subject=Hi&bcc=y@x.test'), {to: [], cc: [], bcc: [], subject: '', body: ''});
48
+ assert.deepEqual(parseMailto('mailto:?subject=Join&body=link').subject, 'Join');
49
+ });
50
+
51
+ test('emailTo on an old core: a mailto over 1800 characters is not opened - the addresses are copied', async () => {
52
+ const saved = {location: globalThis.location, E: globalThis.E, nav: Object.getOwnPropertyDescriptor(globalThis, 'navigator')};
53
+ let copied = '';
54
+ const toasts = [];
55
+ globalThis.location = {href: '', hash: ''};
56
+ globalThis.E = {toast: (m) => toasts.push(m)};
57
+ Object.defineProperty(globalThis, 'navigator', {value: {clipboard: {writeText: async (t) => { copied = t; }}}, configurable: true});
58
+ try {
59
+ const bcc = Array.from({length: 120}, (_, i) => `person${i}@example.test`);
60
+ assert.equal(await emailTo({bcc, subject: 'News'}), 'copied');
61
+ assert.equal(globalThis.location.href, '');
62
+ assert.equal(copied, bcc.join(', '));
63
+ assert.match(toasts[0], /120 addresses are copied.*Not carried over: the subject/);
64
+ } finally {
65
+ globalThis.location = saved.location;
66
+ globalThis.E = saved.E;
67
+ if (saved.nav) Object.defineProperty(globalThis, 'navigator', saved.nav); else delete globalThis.navigator;
68
+ }
69
+ });