domma-cms 1.78.0 → 1.80.0

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 (89) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/admin/js/templates/docs/usage-site-settings.html +29 -1
  3. package/docs/DommaFeatures.md +62 -54
  4. package/docs/plans/2026-11-19-brand-kit-design.md +58 -0
  5. package/package.json +1 -1
  6. package/plugins/_lib/admin/mail/attach-arrange.js +303 -0
  7. package/plugins/_lib/admin/mail/body-menu.js +1 -1
  8. package/plugins/_lib/admin/mail/cms-attach.js +340 -0
  9. package/plugins/_lib/admin/mail/cms-host.js +10 -3
  10. package/plugins/_lib/admin/mail/compose-window.js +47 -1
  11. package/plugins/_lib/admin/mail/contacts.js +1 -1
  12. package/plugins/_lib/admin/mail/diagnostics-section.js +1 -1
  13. package/plugins/_lib/admin/mail/drag-drop.js +33 -1
  14. package/plugins/_lib/admin/mail/folder-tree.js +1 -1
  15. package/plugins/_lib/admin/mail/font-controls.js +1 -1
  16. package/plugins/_lib/admin/mail/fonts.js +1 -1
  17. package/plugins/_lib/admin/mail/host-context.js +1 -1
  18. package/plugins/_lib/admin/mail/identity.js +1 -1
  19. package/plugins/_lib/admin/mail/image-senders-section.js +1 -1
  20. package/plugins/_lib/admin/mail/keyboard.js +1 -1
  21. package/plugins/_lib/admin/mail/mail.html +1 -1
  22. package/plugins/_lib/admin/mail/message-actions.js +1 -1
  23. package/plugins/_lib/admin/mail/oauth-panel.js +1 -1
  24. package/plugins/_lib/admin/mail/panes.js +1 -1
  25. package/plugins/_lib/admin/mail/reader-kit.js +1 -1
  26. package/plugins/_lib/admin/mail/reader-runtime.js +119 -63
  27. package/plugins/_lib/admin/mail/reader-view.js +1 -1
  28. package/plugins/_lib/admin/mail/resizable.js +1 -1
  29. package/plugins/_lib/admin/mail/restore-spam.js +1 -1
  30. package/plugins/_lib/admin/mail/rules.js +1 -1
  31. package/plugins/_lib/admin/mail/scheduling.js +1 -1
  32. package/plugins/_lib/admin/mail/section-kit.js +1 -1
  33. package/plugins/_lib/admin/mail/security-note.js +1 -1
  34. package/plugins/_lib/admin/mail/settings-section.js +6 -3
  35. package/plugins/_lib/admin/mail/templates.js +1 -1
  36. package/plugins/_lib/admin/mail/threads.js +1 -1
  37. package/plugins/_lib/admin/mail/vacation.js +1 -1
  38. package/plugins/_lib/admin/mail/when-closed.js +1 -1
  39. package/plugins/_lib/admin/ui/dates.js +1 -1
  40. package/plugins/_lib/admin/ui/resizable.js +1 -1
  41. package/plugins/_lib/admin/ui/rich-field.js +1 -1
  42. package/plugins/_lib/domma-mail.lock.json +85 -83
  43. package/plugins/_lib/mail/accountFileStore.js +1 -1
  44. package/plugins/_lib/mail/accountRepository.js +41 -2
  45. package/plugins/_lib/mail/accountRoutes.js +1 -1
  46. package/plugins/_lib/mail/bodyTokenProvider.js +1 -1
  47. package/plugins/_lib/mail/bodyTokens.js +1 -1
  48. package/plugins/_lib/mail/compose.js +1 -1
  49. package/plugins/_lib/mail/defaults.js +1 -1
  50. package/plugins/_lib/mail/envelope.js +1 -1
  51. package/plugins/_lib/mail/folderActions.js +1 -1
  52. package/plugins/_lib/mail/folderRuntime.js +1 -1
  53. package/plugins/_lib/mail/folders.js +1 -1
  54. package/plugins/_lib/mail/imapPoolRuntime.js +1 -1
  55. package/plugins/_lib/mail/mbox.js +1 -1
  56. package/plugins/_lib/mail/message-action.js +1 -1
  57. package/plugins/_lib/mail/messageSecurity.js +1 -1
  58. package/plugins/_lib/mail/messageSecurityProvider.js +1 -1
  59. package/plugins/_lib/mail/networkAddresses.js +1 -1
  60. package/plugins/_lib/mail/networkPolicy.js +1 -1
  61. package/plugins/_lib/mail/oauthAccounts.js +1 -1
  62. package/plugins/_lib/mail/oauthRouteRuntime.js +1 -1
  63. package/plugins/_lib/mail/oauthRuntime.js +1 -1
  64. package/plugins/_lib/mail/pollSchedule.js +1 -1
  65. package/plugins/_lib/mail/poller.js +1 -1
  66. package/plugins/_lib/mail/pollerRuntime.js +1 -1
  67. package/plugins/_lib/mail/priority.js +1 -1
  68. package/plugins/_lib/mail/publicMailbox.js +1 -1
  69. package/plugins/_lib/mail/readRuntime.js +1 -1
  70. package/plugins/_lib/mail/render.js +1 -1
  71. package/plugins/_lib/mail/ruleRunner.js +1 -1
  72. package/plugins/_lib/mail/schedulerRuntime.js +1 -1
  73. package/plugins/_lib/mail/secretProvider.js +1 -1
  74. package/plugins/_lib/mail/secretbox.js +1 -1
  75. package/plugins/_lib/mail/senderAuth.js +1 -1
  76. package/plugins/_lib/mail/sieve.js +1 -1
  77. package/plugins/_lib/mail/smtpService.js +1 -1
  78. package/plugins/_lib/mail/snoozeRuntime.js +1 -1
  79. package/plugins/_lib/mail/store.js +1 -1
  80. package/plugins/_lib/mail/subscriptions.js +1 -1
  81. package/plugins/_lib/mail/syncPlan.js +1 -1
  82. package/plugins/_lib/mail/syncRuntime.js +1 -1
  83. package/plugins/_lib/mail/syncSelection.js +1 -1
  84. package/plugins/_lib/mail/unreadBadge.js +1 -1
  85. package/plugins/_lib/mail/unsubscribe.js +1 -1
  86. package/plugins/_lib/mail/vacationRuntime.js +1 -1
  87. package/plugins/_lib/mail/write.js +1 -1
  88. package/plugins/_lib/public/rich-text.mjs +1 -1
  89. package/plugins/_lib/rich-text.js +1 -1
@@ -0,0 +1,303 @@
1
+ // Source: @domma-mail/core 0.38.0, packages/core/src/admin/mail/attach-arrange.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ /**
4
+ * Attachments from somewhere other than this computer: the pure part.
5
+ *
6
+ * The compose window can be given "attachment sources" by its host (the CMS offers Media and the File Store).
7
+ * A source is trusted to open its own chooser, but what comes back is checked here before it is attached, and
8
+ * the lists a chooser shows are shaped here so the screen only ever draws plain records.
9
+ *
10
+ * @module _lib/admin/mail/attach-arrange
11
+ */
12
+
13
+ /** The most files one visit to a chooser may add. */
14
+ export const MAX_PICK = 25;
15
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
16
+
17
+ /** Bytes a base64 string decodes to. */
18
+ export function base64Bytes(content) {
19
+ const text = String(content ?? '');
20
+ if (!text) return 0;
21
+ const pad = text.endsWith('==') ? 2 : text.endsWith('=') ? 1 : 0;
22
+ return Math.max(0, Math.floor(text.length * 3 / 4) - pad);
23
+ }
24
+
25
+ /** A file name fit to put on an attachment: no folders, no control characters, never empty. */
26
+ export function safeName(name) {
27
+ // Controls go, and so do the direction overrides that can make "exe.png" read as "gnp.exe".
28
+ const base = String(name ?? '').split(/[\\/]/).pop().replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, ' ')
29
+ .replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '').replace(/\s+/g, ' ').trim();
30
+ return (base === '.' || base === '..' ? '' : base).slice(0, 200) || 'attachment';
31
+ }
32
+
33
+ /** A content type as a header value, or the catch-all. */
34
+ export function safeType(type) {
35
+ const text = String(type ?? '').split(';')[0].trim().toLowerCase();
36
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]{0,60}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,90}$/.test(text) ? text : 'application/octet-stream';
37
+ }
38
+
39
+ /**
40
+ * What a source handed back, as attachments: only well-formed ones, with the size worked out from the content
41
+ * itself rather than taken on trust.
42
+ *
43
+ * @param {unknown} items
44
+ * @returns {Array<{filename: string, contentType: string, content: string, bytes: number}>}
45
+ */
46
+ export function cleanPicked(items, {max = MAX_PICK} = {}) {
47
+ const out = [];
48
+ for (const item of Array.isArray(items) ? items : []) {
49
+ if (!item || typeof item !== 'object' || typeof item.content !== 'string') continue;
50
+ // An empty file is a file: '' is its content.
51
+ if (item.content.length % 4 !== 0 || !BASE64.test(item.content)) continue;
52
+ out.push({filename: safeName(item.filename), contentType: safeType(item.contentType), content: item.content, bytes: base64Bytes(item.content)});
53
+ if (out.length === max) break;
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /** The sources a host offers, checked: an id, a short label and a function. */
59
+ export function cleanSources(list) {
60
+ const seen = new Set();
61
+ const out = [];
62
+ for (const s of Array.isArray(list) ? list : []) {
63
+ const id = String(s?.id ?? '');
64
+ if (!/^[a-z][a-z0-9-]{0,30}$/.test(id) || seen.has(id) || typeof s.pick !== 'function') continue;
65
+ const label = String(s.label ?? '').replace(/\s+/g, ' ').trim().slice(0, 40);
66
+ if (!label) continue;
67
+ seen.add(id);
68
+ out.push({id, label, title: String(s.title ?? label).replace(/\s+/g, ' ').trim().slice(0, 120), pick: s.pick});
69
+ if (out.length === 6) break;
70
+ }
71
+ return out;
72
+ }
73
+
74
+ /** 1536 -> "1.5 KB". */
75
+ export function formatSize(bytes) {
76
+ const n = Number(bytes) || 0;
77
+ if (n < 1024) return `${n} B`;
78
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(n < 10 * 1024 ? 1 : 0)} KB`;
79
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
80
+ }
81
+
82
+ /**
83
+ * A Media address as a path on this site (`/media/...`), or '' for anything else. The chooser fetches only
84
+ * these: an address from a list is data, and must not be able to send the browser somewhere else.
85
+ */
86
+ export function mediaPath(url, origin = 'https://site.invalid') {
87
+ let u;
88
+ try { u = new URL(String(url ?? ''), origin); } catch { return ''; }
89
+ if (u.origin !== new URL(origin).origin || !u.pathname.startsWith('/media/') || u.pathname.includes('//')) return '';
90
+ // An encoded slash, backslash or null has no business in a file's address.
91
+ if (/%2f|%5c|%00/i.test(u.pathname)) return '';
92
+ return u.pathname;
93
+ }
94
+
95
+ /** A size from a list: never negative, never not a number. */
96
+ const sizeOf = (v) => Math.max(0, Number(v) || 0);
97
+ const dirOf = (path) => (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '');
98
+
99
+ /**
100
+ * Media, as the chooser's records. Takes the built-in list (an array of top-level files) or Media Pro's library
101
+ * (`{files, folders}`, where a file has a `path` inside its folders).
102
+ *
103
+ * @returns {{files: Array<{id, name, folder, size, url}>, folders: string[]}}
104
+ */
105
+ export function mediaEntries(payload, origin) {
106
+ const raw = Array.isArray(payload) ? payload : Array.isArray(payload?.files) ? payload.files : [];
107
+ const files = [];
108
+ const folders = new Set();
109
+ for (const f of raw.slice(0, 20000)) {
110
+ if (!f || typeof f !== 'object') continue;
111
+ const path = String(f.path ?? f.name ?? '').replace(/^\/+/, '');
112
+ // The address is made here from the path, each part encoded: a list's own `url` is not, and a name with
113
+ // a `#`, `?` or `%` in it would otherwise be fetched as some other file.
114
+ const url = mediaPath(`/media/${path.split('/').map(encodeURIComponent).join('/')}`, origin);
115
+ if (!path || !url) continue;
116
+ const folder = dirOf(path);
117
+ files.push({id: `m:${path}`, name: path.split('/').pop(), folder, size: sizeOf(f.size), url});
118
+ }
119
+ const add = (path) => { for (let p = String(path || ''); p; p = dirOf(p)) folders.add(p); };
120
+ for (const f of files) add(f.folder);
121
+ for (const d of Array.isArray(payload?.folders) ? payload.folders.slice(0, 5000) : []) add(typeof d === 'string' ? d : d?.path);
122
+ return {files: files.sort((a, b) => a.name.localeCompare(b.name)), folders: [...folders].sort((a, b) => a.localeCompare(b))};
123
+ }
124
+
125
+ /**
126
+ * One screen of Media: the folders directly inside `folder` and its files - or, when searching, every file whose
127
+ * name matches, wherever it is.
128
+ */
129
+ export function mediaView({files, folders}, {folder = '', query = ''} = {}) {
130
+ const q = String(query).trim().toLowerCase();
131
+ if (q) return {folders: [], files: files.filter(f => f.name.toLowerCase().includes(q)).map(f => ({...f, where: f.folder || 'Top level'}))};
132
+ return {
133
+ folders: folders.filter(p => dirOf(p) === folder).map(p => ({id: p, name: p.split('/').pop()})),
134
+ files: files.filter(f => f.folder === folder).map(f => ({...f, where: ''}))
135
+ };
136
+ }
137
+
138
+ /** The way back up from a Media folder: [{id: '', name: 'Media'}, {id: 'a', name: 'a'}, ...]. */
139
+ export function mediaCrumbs(folder) {
140
+ const out = [{id: '', name: 'Media'}];
141
+ let at = '';
142
+ for (const part of String(folder || '').split('/').filter(Boolean)) { at = at ? `${at}/${part}` : part; out.push({id: at, name: part}); }
143
+ return out;
144
+ }
145
+
146
+ /** The File Store's answer to "what is here", as the chooser's records. */
147
+ export function storeView(payload, {place = 'mine'} = {}) {
148
+ const p = payload && typeof payload === 'object' ? payload : {};
149
+ const text = (v, max) => String(v ?? '').slice(0, max);
150
+ const id = (v) => (/^[0-9a-f]{24}$/.test(String(v)) ? String(v) : '');
151
+ return {
152
+ folders: (Array.isArray(p.folders) ? p.folders : []).filter(f => id(f?.id)).map(f => ({id: f.id, name: text(f.name, 200)})),
153
+ files: (Array.isArray(p.files) ? p.files : []).filter(f => id(f?.id)).map(f => ({id: `f:${f.id}`, fileId: f.id, name: text(f.name, 200), size: sizeOf(f.size),
154
+ where: text(f.path, 300) || (place === 'shared' ? text(f.owner?.name ?? f.owner, 80) : '')})),
155
+ crumbs: [{id: '', name: place === 'shared' ? 'Shared with me' : 'My files'}, ...(Array.isArray(p.crumbs) ? p.crumbs : []).filter(c => id(c?.id)).map(c => ({id: c.id, name: text(c.name, 200)}))]
156
+ };
157
+ }
158
+
159
+ /**
160
+ * The line under a chooser's list, and whether Attach may be pressed.
161
+ *
162
+ * @param {Array<{size: number}>} chosen
163
+ * @param {number} room - bytes left in the message before its limit (Infinity when unknown)
164
+ */
165
+ export function choiceSummary(chosen, room = Infinity, {canLink = false} = {}) {
166
+ const n = chosen.length;
167
+ const total = chosen.reduce((sum, f) => sum + sizeOf(f.size), 0);
168
+ if (!n) return {text: 'Tick the files to attach.', ok: false, over: false, linkOk: false};
169
+ const many = n > MAX_PICK;
170
+ const over = Number.isFinite(room) && total > room;
171
+ const base = `${n} file${n === 1 ? '' : 's'}, ${formatSize(total)}`;
172
+ return {
173
+ text: many ? `${base}. No more than ${MAX_PICK} at a time.` : over ? `${base} - more than the ${formatSize(Math.max(0, room))} this message has room for.${canLink ? ' Send them as links instead.' : ''}` : base,
174
+ ok: !many && !over, over: over || many,
175
+ // Links carry no bytes, so only the count limits them.
176
+ linkOk: canLink && !many
177
+ };
178
+ }
179
+
180
+ const escHtml = (v) => String(v ?? '').replace(/[&<>"']/g, c => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'}[c]));
181
+
182
+ /**
183
+ * Links a source handed back instead of files (a file too big to attach, shared from where it is kept): only
184
+ * http(s) addresses, with a plain name.
185
+ *
186
+ * @returns {Array<{name: string, url: string, size: number}>}
187
+ */
188
+ export function cleanLinks(items, {max = MAX_PICK} = {}) {
189
+ const out = [];
190
+ for (const item of Array.isArray(items) ? items : []) {
191
+ if (!item || typeof item !== 'object') continue;
192
+ let u;
193
+ try { u = new URL(String(item.url ?? '')); } catch { continue; }
194
+ if (!/^https?:$/.test(u.protocol) || u.username || u.password) continue;
195
+ out.push({name: safeName(item.name), url: u.href, size: sizeOf(item.size)});
196
+ if (out.length === max) break;
197
+ }
198
+ return out;
199
+ }
200
+
201
+ /** "19 December 2026" from an ISO date, or '' when there is none or it cannot be read. */
202
+ export function linkDay(iso) {
203
+ // An ISO date and nothing looser: Date.parse reads "5" as a day in 2001.
204
+ const t = /^\d{4}-\d\d-\d\dT/.test(String(iso ?? '')) ? Date.parse(String(iso)) : NaN;
205
+ return Number.isFinite(t) ? new Date(t).toLocaleDateString('en-GB', {day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC'}) : '';
206
+ }
207
+
208
+ /**
209
+ * The paragraph a message gets for links: as HTML for the editor and as plain text for a plain body. Every name
210
+ * and address is escaped; `links` is what cleanLinks() returned.
211
+ */
212
+ export function linkBlock(links, {expiresAt = ''} = {}) {
213
+ if (!links.length) return {html: '', text: ''};
214
+ const many = links.length > 1;
215
+ const until = linkDay(expiresAt);
216
+ // Said plainly, and true whether the file was too large to attach or simply better sent this way.
217
+ const lead = many ? 'Here are links to download the files:' : 'Here is a link to download the file:';
218
+ const tail = until ? `${many ? 'The links work' : 'The link works'} until ${until}.` : '';
219
+ const size = (l) => (l.size ? ` (${formatSize(l.size)})` : '');
220
+ return {
221
+ // The address itself is the link's text: it survives into the plain-text part of the mail, and a name that
222
+ // looks like another address cannot dress up where the link goes.
223
+ html: `<p>${lead}</p><ul>${links.map(l => `<li>${escHtml(l.name)}${escHtml(size(l))}: <a href="${escHtml(l.url)}">${escHtml(l.url)}</a></li>`).join('')}</ul>${tail ? `<p>${tail}</p>` : ''}`,
224
+ text: [lead, ...links.map(l => `- ${l.name}${size(l)}: ${l.url}`), ...(tail ? [tail] : [])].join('\n')
225
+ };
226
+ }
227
+
228
+ /** The words in a piece of HTML, with tags, spaces and non-breaking spaces gone: '' means "nothing a person wrote". */
229
+ const wordsIn = (html) => String(html).replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;|\s/g, '');
230
+
231
+ const SIGNATURE = /<div\b[^>]*\bclass=(["'])[^"']*\bdm-mail-signature\b[^"']*\1[^>]*>/gi;
232
+
233
+ /** Where each top-level blockquote starts and ends, and how deep in blockquotes any index is. */
234
+ function quotesOf(html) {
235
+ const tops = [];
236
+ const marks = [];
237
+ let depth = 0;
238
+ let start = -1;
239
+ for (const m of html.matchAll(/<(\/?)blockquote\b[^>]*>/gi)) {
240
+ if (!m[1]) { if (depth === 0) start = m.index; depth++; }
241
+ else if (depth > 0) { depth--; if (depth === 0) tops.push({start, end: m.index + m[0].length}); }
242
+ marks.push({at: m.index, depth});
243
+ }
244
+ const depthAt = (i) => { let d = 0; for (const k of marks) { if (k.at >= i) break; d = k.depth; } return d; };
245
+ return {tops, depthAt};
246
+ }
247
+
248
+ /**
249
+ * A message's HTML with a block put where the writer's own words end.
250
+ *
251
+ * - A reply or forward written above the quoted message (the usual way): before the line that introduces the
252
+ * quote ("On 3 Nov, Sam wrote:") - or before the writer's signature, if that comes first.
253
+ * - Otherwise before the writer's signature, if there is one outside any quotation (a signature inside quoted
254
+ * text is the other person's).
255
+ * - Otherwise at the end. That covers a new message, an answer written under the quote, and a quotation the
256
+ * writer put in the middle of their own text.
257
+ */
258
+ export function placeBlock(html, block) {
259
+ const body = String(html ?? '');
260
+ if (!block) return body;
261
+ const {tops, depthAt} = quotesOf(body);
262
+ const sig = [...body.matchAll(SIGNATURE)].map(m => m.index).find(i => depthAt(i) === 0) ?? -1;
263
+ const put = (at) => body.slice(0, at) + block + body.slice(at);
264
+ const last = tops.at(-1);
265
+ if (last) {
266
+ // Nothing of the writer's after the quote (their signature aside): the message was written above it.
267
+ const after = sig >= last.end ? body.slice(last.end, sig) : body.slice(last.end);
268
+ if (!wordsIn(after)) {
269
+ let at = last.start;
270
+ const lead = /(?:<p>(?:<br\s*\/?>|\s|&nbsp;)*<\/p>\s*)?<p>(?:(?!<\/p>)[\s\S])*<\/p>\s*$/i.exec(body.slice(0, at));
271
+ if (lead && wordsIn(lead[0])) at = lead.index;
272
+ return put(sig >= 0 && sig < at ? sig : at);
273
+ }
274
+ }
275
+ return sig >= 0 ? put(sig) : body + block;
276
+ }
277
+
278
+ /** The same for a plain-text body: above the line introducing quoted text, or above the "-- " signature, or at the end. */
279
+ export function placeText(body, block) {
280
+ const text = String(body ?? '');
281
+ if (!block) return text;
282
+ const lines = text.split('\n');
283
+ const isQuote = (l) => l.startsWith('>');
284
+ const sig = lines.findIndex(l => l === '-- ' || l === '--');
285
+ const first = lines.findIndex(isQuote);
286
+ const lastQuote = lines.findLastIndex(isQuote);
287
+ const put = (at) => {
288
+ const head = lines.slice(0, at).join('\n').replace(/\s+$/, '');
289
+ const tail = lines.slice(at).join('\n');
290
+ return `${head}${head ? '\n\n' : ''}${block}${tail ? `\n\n${tail}` : '\n'}`;
291
+ };
292
+ if (first >= 0) {
293
+ const end = sig > lastQuote ? sig : lines.length;
294
+ const wroteBelow = lines.slice(lastQuote + 1, end).some(l => l.trim());
295
+ if (!wroteBelow) {
296
+ // Step back over the line that introduces the quote ("On 3 Nov, Sam wrote:").
297
+ let at = first;
298
+ if (at > 0 && lines[at - 1].trim()) at--;
299
+ return put(sig >= 0 && sig < at ? sig : at);
300
+ }
301
+ }
302
+ return put(sig >= 0 ? sig : lines.length);
303
+ }
@@ -1,4 +1,4 @@
1
- // Source: @domma-mail/core 0.35.0, packages/core/src/admin/mail/body-menu.js.
1
+ // Source: @domma-mail/core 0.38.0, packages/core/src/admin/mail/body-menu.js.
2
2
  // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
3
  /**
4
4
  * The reading pane's right-click menu - the pure parts.
@@ -0,0 +1,340 @@
1
+ // Source: @domma-mail/core 0.38.0, packages/core/src/admin/mail/cms-attach.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ /**
4
+ * Attachments from the CMS: Media and the File Store. CMS shell boundary - only cms-host.js imports this, and
5
+ * standalone Domma Mail never does.
6
+ *
7
+ * One chooser, two places to look. Each "provider" only knows how to list a place and how to fetch a file's bytes,
8
+ * through the admin APIs those Tools already have, as the signed-in person: a file they may not open is not
9
+ * listed, and the server checks again when its bytes are asked for. Nothing here is told to the compose window but
10
+ * the files chosen. Names come from other people's uploads, so they reach the screen as text, never as markup.
11
+ *
12
+ * @module _lib/admin/mail/cms-attach
13
+ */
14
+ const version = new URL(import.meta.url).searchParams.get('v') ?? '1';
15
+ const {choiceSummary, formatSize, mediaCrumbs, mediaEntries, mediaPath, mediaView, storeView} =
16
+ await import(new URL(`./attach-arrange.js?v=${version}`, import.meta.url).href);
17
+
18
+ const STORE = '/api/plugins/file-store';
19
+ const STORE_PRO = '/api/plugins/file-store-pro';
20
+ /** How long a link made from compose lasts, in days: the choices offered, the first the default. */
21
+ const LINK_DAYS = [30, 7, 90];
22
+
23
+ function el(tag, attrs = {}, ...kids) {
24
+ const node = document.createElement(tag);
25
+ for (const [k, v] of Object.entries(attrs)) {
26
+ if (v == null || v === false) continue;
27
+ if (k === 'class') node.className = v;
28
+ else if (k === 'text') node.textContent = v;
29
+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);
30
+ else if (k in node) node[k] = v;
31
+ else node.setAttribute(k, v === true ? '' : v);
32
+ }
33
+ node.append(...kids.flat().filter(x => x != null && x !== false));
34
+ return node;
35
+ }
36
+
37
+ function asBase64(blob) {
38
+ return new Promise((resolve, reject) => {
39
+ const reader = new FileReader();
40
+ reader.onload = () => resolve(String(reader.result).split(',')[1] ?? '');
41
+ reader.onerror = () => reject(new Error('A file could not be read.'));
42
+ reader.readAsDataURL(blob);
43
+ });
44
+ }
45
+
46
+ /**
47
+ * Can this person use a source? true, false (the Tool is off or not theirs: 403, 404), or null when the question
48
+ * could not be answered (the network), so that it is asked again next time rather than remembered as a no.
49
+ */
50
+ async function probe(host, url) {
51
+ try { await host.api(url); return true; }
52
+ catch (err) { return err?.status === 403 || err?.status === 404 ? false : null; }
53
+ }
54
+
55
+ /** Media: Media Pro's library when it is there (folders), the built-in list when it is not. */
56
+ function mediaProvider(host) {
57
+ let library = null;
58
+ return {
59
+ id: 'media', label: 'From Media', title: 'Attach from Media', places: [{id: 'media', name: 'Media'}],
60
+ available: () => probe(host, '/api/media/_count'),
61
+ /** Media is read afresh each time the chooser opens: files come and go between visits. */
62
+ reset() { library = null; },
63
+ async browse({folder, query}) {
64
+ if (!library) {
65
+ let payload;
66
+ try { payload = await host.api('/api/plugins/media-pro/library'); } catch { payload = await host.api('/api/media'); }
67
+ library = mediaEntries(payload, location.origin);
68
+ }
69
+ return {...mediaView(library, {folder, query}), crumbs: query ? [{id: '', name: 'Media'}] : mediaCrumbs(folder)};
70
+ },
71
+ async bytes(file, signal) {
72
+ const path = mediaPath(file.url, location.origin);
73
+ if (!path) throw new Error(`${file.name} is not in Media.`);
74
+ const res = await host.fetch(path, {credentials: 'same-origin', redirect: 'error', signal});
75
+ if (!res.ok) throw new Error(`${file.name} could not be fetched (${res.status}).`);
76
+ return res.blob();
77
+ }
78
+ };
79
+ }
80
+
81
+ /** The File Store: the person's own files and folders, and what has been shared with them. */
82
+ function storeProvider(host) {
83
+ return {
84
+ id: 'file-store', label: 'From File Store', title: 'Attach from the File Store',
85
+ places: [{id: 'mine', name: 'My files'}, {id: 'shared', name: 'Shared with me'}],
86
+ available: () => probe(host, `${STORE}/status`),
87
+ async browse({place, folder, query}) {
88
+ const params = new URLSearchParams({place});
89
+ if (folder && place === 'mine') params.set('folder', folder);
90
+ if (query) params.set('q', query);
91
+ return storeView(await host.api(`${STORE}/files?${params}`), {place});
92
+ },
93
+ async bytes(file, signal) {
94
+ const res = await host.fetch(`${STORE}/files/${encodeURIComponent(file.fileId)}/download`, {headers: host.authHeaders(), redirect: 'error', signal});
95
+ if (!res.ok) throw new Error(`${file.name} could not be fetched (${res.status}).`);
96
+ return res.blob();
97
+ },
98
+ /**
99
+ * Share links, where File Store Pro is on and this person may make them: a file too big to attach goes as
100
+ * a link to where it already is. Asked each time the chooser opens; a failure only means no button.
101
+ */
102
+ async linking() {
103
+ try {
104
+ const st = await host.api(`${STORE_PRO}/status`);
105
+ if (!st?.ready || !st?.can?.share) return null;
106
+ const max = Number(st.maxDays) > 0 ? Number(st.maxDays) : LINK_DAYS[0];
107
+ return {days: [...new Set(LINK_DAYS.map(d => Math.min(d, max)))]};
108
+ } catch { return null; }
109
+ },
110
+ /** One share link for one file. File Store Pro decides: only the file's owner (or a manager) may make one. */
111
+ async link(file, days) {
112
+ const made = await host.api(`${STORE_PRO}/links`, 'POST', {kind: 'share', fileId: file.fileId, expiresDays: days, note: 'Sent by email'});
113
+ // A share link's own shape and nothing else: `/_share/../x` would be some other page of the site.
114
+ if (typeof made?.path !== 'string' || !/^\/_share\/[A-Za-z0-9_-]{16,64}$/.test(made.path)) throw new Error('The link could not be made.');
115
+ return {id: String(made.id || ''), name: file.name, size: file.size, url: new URL(made.path, location.origin).href, expiresAt: made.expiresAt || ''};
116
+ },
117
+ /** Take back a link that will not be used (the chooser was closed before its message got it). */
118
+ async unlink(id) {
119
+ if (/^[A-Za-z0-9_-]{1,64}$/.test(String(id))) await host.api(`${STORE_PRO}/links/${encodeURIComponent(id)}`, 'DELETE');
120
+ }
121
+ };
122
+ }
123
+
124
+ const STYLE = `
125
+ .mail-pick { display: flex; flex-direction: column; gap: .6rem; padding: 1rem; height: 100%; min-height: 0; }
126
+ .mail-pick-bar { display: flex; gap: .5rem; flex-wrap: wrap; align-items: center; }
127
+ .mail-pick-bar .form-input { flex: 1 1 12rem; }
128
+ .mail-pick-places { display: inline-flex; gap: .25rem; }
129
+ .mail-pick-crumbs { display: flex; flex-wrap: wrap; gap: .15rem; align-items: center; font-size: var(--dm-text-sm, .875rem); }
130
+ .mail-pick-crumb { background: none; border: 0; padding: .1rem .3rem; color: var(--dm-primary); cursor: pointer; font: inherit; border-radius: var(--dm-radius-sm, .25rem); }
131
+ .mail-pick-crumb[aria-current="true"] { color: inherit; font-weight: 600; cursor: default; }
132
+ .mail-pick-list { flex: 1; min-height: 8rem; overflow-y: auto; border: 1px solid var(--dm-border); border-radius: var(--dm-radius-md, .5rem); }
133
+ .mail-pick-row { display: flex; align-items: center; gap: .6rem; width: 100%; padding: .45rem .7rem; border: 0; border-bottom: 1px solid var(--dm-border); background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }
134
+ .mail-pick-row:last-child { border-bottom: 0; }
135
+ .mail-pick-row:hover { background: var(--dm-surface-raised, rgba(127,127,127,.1)); }
136
+ .mail-pick-row:focus-visible, .mail-pick-crumb:focus-visible { outline: 2px solid var(--dm-primary); outline-offset: -2px; }
137
+ .mail-pick-tick { flex: none; width: 1.1rem; height: 1.1rem; border: 1.5px solid var(--dm-border); border-radius: var(--dm-radius-sm, .25rem); display: inline-flex; align-items: center; justify-content: center; font-size: .8rem; line-height: 1; }
138
+ .mail-pick-row[aria-checked="true"] .mail-pick-tick { background: var(--dm-primary); border-color: var(--dm-primary); color: var(--dm-primary-text, #fff); }
139
+ .mail-pick-list:focus-visible { outline: 2px solid var(--dm-primary); outline-offset: -2px; }
140
+ .mail-pick-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
141
+ .mail-pick-meta { flex: none; font-size: var(--dm-text-xs, .75rem); color: var(--dm-text-muted); white-space: nowrap; max-width: 45%; overflow: hidden; text-overflow: ellipsis; }
142
+ .mail-pick-note { padding: 1rem; margin: 0; color: var(--dm-text-muted); font-size: var(--dm-text-sm, .875rem); }
143
+ .mail-pick-foot { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; }
144
+ .mail-pick-days { width: auto; flex: none; }
145
+ .mail-pick-foot [hidden] { display: none !important; }
146
+ .mail-pick-sum { flex: 1; font-size: var(--dm-text-sm, .875rem); color: var(--dm-text-muted); }
147
+ .mail-pick-sum[data-over="true"] { color: var(--dm-danger); }
148
+ `;
149
+
150
+ /**
151
+ * The chooser: a slideover over the compose window. Resolves with the attachments chosen (possibly none).
152
+ *
153
+ * @param {object} host - the mail host
154
+ * @param {object} provider
155
+ * @param {{remainingBytes?: number}} opts
156
+ * @returns {Promise<Array<{filename, contentType, content}>|{attachments: [], links: Array<{name, url, size}>, expiresAt: string}>}
157
+ * files to attach, or - from "Send as links" - links for the message's body
158
+ */
159
+ function choose(host, provider, {remainingBytes = Infinity} = {}) {
160
+ const {E} = host;
161
+ return new Promise((resolve) => {
162
+ let settled = false;
163
+ const done = (list) => { if (!settled) { settled = true; resolve(list); } };
164
+ const so = E.slideover({title: provider.title, size: 'md', position: 'right'});
165
+ const chosen = new Map(); // id -> record (with the place it was ticked in), kept as the person moves between folders and places
166
+ let place = provider.places[0].id;
167
+ let folder = '';
168
+ let query = '';
169
+ let visit = 0; // a slow answer for a place already left is dropped
170
+ let fetching = false;
171
+ let closedByUs = false;
172
+ const stop = new AbortController(); // closing the chooser stops a download in hand
173
+ provider.reset?.();
174
+
175
+ const search = el('input', {type: 'search', class: 'form-input', placeholder: 'Search by name', 'aria-label': 'Search by name'});
176
+ const places = el('div', {class: 'mail-pick-places', role: 'group', 'aria-label': 'Where to look'});
177
+ const crumbs = el('nav', {class: 'mail-pick-crumbs', 'aria-label': 'Folder'});
178
+ const list = el('div', {class: 'mail-pick-list', tabIndex: -1});
179
+ const sum = el('span', {class: 'mail-pick-sum', 'aria-live': 'polite'});
180
+ const attach = el('button', {type: 'button', class: 'btn btn-primary btn-sm', text: 'Attach', disabled: true});
181
+ const cancel = el('button', {type: 'button', class: 'btn btn-ghost btn-sm', text: 'Cancel', onclick: () => so.close()});
182
+ // "Send as links": drawn only once the provider has said this person can make them.
183
+ let linking = null;
184
+ const linkDays = el('select', {class: 'form-select mail-pick-days', 'aria-label': 'How long the links last', hidden: true});
185
+ const asLinks = el('button', {type: 'button', class: 'btn btn-outline btn-sm', text: 'Send as links', hidden: true, disabled: true,
186
+ title: 'Instead of attaching, put a link to each file in the message. For files too large to attach.'});
187
+ const panel = el('div', {class: 'mail-pick'},
188
+ el('div', {class: 'mail-pick-bar'}, provider.places.length > 1 ? places : null, search), crumbs, list,
189
+ el('div', {class: 'mail-pick-foot'}, sum, linkDays, cancel, asLinks, attach));
190
+
191
+ const drawSum = () => {
192
+ // Only a person's own files can be shared by link: the button is there while every ticked file is one of theirs.
193
+ const all = [...chosen.values()];
194
+ const canLink = Boolean(linking) && (all.length ? all.every(f => f.from === 'mine') : place === 'mine');
195
+ const s = choiceSummary([...chosen.values()], remainingBytes, {canLink});
196
+ sum.textContent = fetching ? sum.textContent : s.text;
197
+ sum.dataset.over = String(s.over && !s.linkOk);
198
+ attach.disabled = fetching || !s.ok;
199
+ asLinks.hidden = linkDays.hidden = !canLink;
200
+ asLinks.disabled = fetching || !s.linkOk;
201
+ asLinks.textContent = chosen.size > 1 ? `Send ${chosen.size} as links` : 'Send as a link';
202
+ attach.textContent = chosen.size > 1 ? `Attach ${chosen.size} files` : 'Attach';
203
+ };
204
+
205
+ // Made once and only re-marked, so the button just pressed keeps the focus.
206
+ const placeButtons = provider.places.map(p => el('button', {type: 'button', class: 'btn btn-sm btn-ghost', text: p.name, 'data-place': p.id,
207
+ onclick: () => { if (p.id !== place && !fetching) { place = p.id; folder = ''; load(); } }}));
208
+ places.replaceChildren(...placeButtons);
209
+ const drawPlaces = () => {
210
+ for (const b of placeButtons) {
211
+ const on = b.dataset.place === place;
212
+ b.classList.toggle('btn-primary', on); b.classList.toggle('btn-ghost', !on);
213
+ b.setAttribute('aria-pressed', String(on));
214
+ }
215
+ };
216
+
217
+ async function load({focus = false} = {}) {
218
+ const mine = ++visit;
219
+ drawPlaces();
220
+ drawSum();
221
+ list.replaceChildren(el('p', {class: 'mail-pick-note', text: 'Loading…'}));
222
+ let view;
223
+ try { view = await provider.browse({place, folder, query}); }
224
+ catch (err) { if (mine === visit) list.replaceChildren(el('p', {class: 'mail-pick-note', text: `That could not be listed: ${err?.message || 'the request failed'}.`})); return; }
225
+ if (mine !== visit || settled) return;
226
+ crumbs.replaceChildren(...view.crumbs.flatMap((c, i) => [i ? el('span', {text: '›', 'aria-hidden': 'true'}) : null,
227
+ el('button', {type: 'button', class: 'mail-pick-crumb', text: c.name, 'aria-current': String(i === view.crumbs.length - 1 && !query),
228
+ onclick: () => { if ((folder !== c.id || query) && !fetching) { folder = c.id; query = ''; search.value = ''; load({focus: true}); } }})]));
229
+ const rows = [
230
+ ...view.folders.map(f => el('button', {type: 'button', class: 'mail-pick-row', onclick: () => { if (fetching) return; folder = f.id; query = ''; search.value = ''; load({focus: true}); }},
231
+ el('span', {'aria-hidden': 'true', text: '📁'}), el('span', {class: 'mail-pick-name', text: f.name}), el('span', {class: 'mail-pick-meta', text: 'Folder'}))),
232
+ ...view.files.map(f => {
233
+ const box = el('span', {class: 'mail-pick-tick', 'aria-hidden': 'true', text: chosen.has(f.id) ? '✓' : ''});
234
+ const row = el('button', {type: 'button', class: 'mail-pick-row', role: 'checkbox', 'aria-checked': String(chosen.has(f.id)), onclick: () => {
235
+ // What is being fetched is what was ticked when Attach was pressed.
236
+ if (fetching) return;
237
+ if (chosen.has(f.id)) chosen.delete(f.id); else chosen.set(f.id, {...f, from: place});
238
+ box.textContent = chosen.has(f.id) ? '✓' : ''; row.setAttribute('aria-checked', String(chosen.has(f.id)));
239
+ drawSum();
240
+ }}, box, el('span', {class: 'mail-pick-name', text: f.name, title: f.name}), el('span', {class: 'mail-pick-meta', text: [f.where, formatSize(f.size)].filter(Boolean).join(' · ')}));
241
+ return row;
242
+ })
243
+ ];
244
+ list.replaceChildren(...(rows.length ? rows : [el('p', {class: 'mail-pick-note', text: query ? 'Nothing here has that in its name.' : 'There is nothing here.'})]));
245
+ // After going into a folder or back up, the keyboard is at the top of what is now showing.
246
+ if (focus) (rows[0] || list).focus();
247
+ }
248
+
249
+ let typing = 0;
250
+ search.addEventListener('input', () => { clearTimeout(typing); typing = setTimeout(() => { query = search.value.trim(); load(); }, 250); });
251
+
252
+ attach.addEventListener('click', async () => {
253
+ if (fetching) return;
254
+ fetching = true; drawSum();
255
+ const out = [];
256
+ const files = [...chosen.values()];
257
+ try {
258
+ let total = 0;
259
+ for (const [i, f] of files.entries()) {
260
+ sum.textContent = `Fetching ${i + 1} of ${files.length}: ${f.name}`;
261
+ const blob = await provider.bytes(f, stop.signal);
262
+ if (settled) return;
263
+ // The list's sizes were a promise; this is the file. Checked before it is turned into text, which doubles it.
264
+ total += blob.size;
265
+ if (total > remainingBytes) throw new Error(`${f.name} is ${formatSize(blob.size)}: with it, these are more than this message has room for.`);
266
+ out.push({filename: f.name, contentType: blob.type || 'application/octet-stream', content: await asBase64(blob)});
267
+ }
268
+ if (settled) return;
269
+ done(out);
270
+ closedByUs = true;
271
+ so.close();
272
+ } catch (err) {
273
+ if (settled) return; // closed part way: nothing to say
274
+ fetching = false; drawSum();
275
+ E.toast(err?.message || 'A file could not be fetched.', {type: 'error'});
276
+ }
277
+ });
278
+
279
+ asLinks.addEventListener('click', async () => {
280
+ if (fetching || !linking) return;
281
+ fetching = true; drawSum();
282
+ const files = [...chosen.values()];
283
+ const days = Number(linkDays.value) || linking.days[0];
284
+ const links = [];
285
+ const refused = [];
286
+ // A link is live the moment it is made, so one that will reach no message is taken back.
287
+ const takeBack = () => { for (const l of links) provider.unlink?.(l.id).catch(() => {}); };
288
+ cancel.disabled = true;
289
+ for (const [i, f] of files.entries()) {
290
+ sum.textContent = `Making link ${i + 1} of ${files.length}: ${f.name}`;
291
+ try { links.push(await provider.link(f, days)); } catch (err) { refused.push({name: f.name, why: err?.status === 404 ? 'only its owner can share it' : (err?.message || 'the request failed')}); }
292
+ if (settled) { takeBack(); return; }
293
+ }
294
+ cancel.disabled = false;
295
+ if (refused.length) E.toast(refused.length === 1 ? `${refused[0].name} was not shared by link: ${refused[0].why}.` : `${refused.length} files were not shared by link. The first: ${refused[0].why}.`, {type: 'warning'});
296
+ if (!links.length) { fetching = false; drawSum(); return; }
297
+ done({attachments: [], links: links.map(({name, url, size}) => ({name, url, size})), expiresAt: links[0].expiresAt});
298
+ closedByUs = true;
299
+ so.close();
300
+ });
301
+
302
+ const style = el('style', {text: STYLE});
303
+ so.element.append(panel, style);
304
+ const closed = () => { clearTimeout(typing); visit++; done([]); if (!closedByUs) stop.abort(); };
305
+ // The CMS's onceClosed takes the panel away itself; without it, this does.
306
+ if (typeof host.helpers?.onceClosed === 'function') host.helpers.onceClosed(so, closed);
307
+ else so.element.addEventListener('dm:slideover:close', () => { closed(); setTimeout(() => { try { so.destroy?.(); so.element?.remove(); } catch { /* gone */ } }, 400); }, {once: true});
308
+ so.open();
309
+ drawSum();
310
+ load();
311
+ if (typeof provider.linking === 'function') {
312
+ provider.linking().then((answer) => {
313
+ if (settled || !answer) return;
314
+ linking = answer;
315
+ linkDays.replaceChildren(...answer.days.map(d => el('option', {value: String(d), text: `Links last ${d} ${d === 1 ? 'day' : 'days'}`})));
316
+ drawSum();
317
+ }).catch(() => {});
318
+ }
319
+ setTimeout(() => search.focus(), 60);
320
+ });
321
+ }
322
+
323
+ /**
324
+ * The attachment sources the CMS offers the compose window: those the signed-in person can use, found out once.
325
+ *
326
+ * @param {object} host - the mail host (api, fetch, authHeaders, E, helpers)
327
+ * @returns {() => Promise<Array<{id, label, title, pick}>>}
328
+ */
329
+ export function createCmsAttachmentSources(host) {
330
+ const providers = [mediaProvider(host), storeProvider(host)];
331
+ let found = null;
332
+ return async () => {
333
+ if (found) return found;
334
+ const answers = await Promise.all(providers.map(p => p.available()));
335
+ const list = providers.filter((p, i) => answers[i] === true).map(p => ({id: p.id, label: p.label, title: p.title, pick: (opts) => choose(host, p, opts)}));
336
+ // Remembered only when every source gave a real answer: a network blip must not hide one for the session.
337
+ if (!answers.includes(null)) found = list;
338
+ return list;
339
+ };
340
+ }