domma-cms 1.28.4 → 1.29.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 (98) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/admin/js/lib/contacts-arrange.js +1 -1
  3. package/docs/DommaFeatures.md +5 -3
  4. package/package.json +4 -1
  5. package/plugins/_lib/admin/mail/body-menu.js +2 -0
  6. package/plugins/_lib/admin/mail/cms-host.js +22 -0
  7. package/plugins/_lib/admin/mail/compose-window.js +1027 -1021
  8. package/plugins/_lib/admin/mail/contacts.js +10 -8
  9. package/plugins/_lib/admin/mail/diagnostics-section.js +2 -0
  10. package/plugins/_lib/admin/mail/drag-drop.js +46 -0
  11. package/plugins/_lib/admin/mail/folder-tree.js +2 -0
  12. package/plugins/_lib/admin/mail/font-controls.js +6 -4
  13. package/plugins/_lib/admin/mail/fonts.js +1 -1
  14. package/plugins/_lib/admin/mail/host-context.js +87 -0
  15. package/plugins/_lib/admin/mail/identity.js +2 -0
  16. package/plugins/_lib/admin/mail/image-senders-section.js +2 -0
  17. package/plugins/_lib/admin/mail/keyboard.js +2 -0
  18. package/plugins/_lib/admin/mail/mail.css +1 -1
  19. package/plugins/_lib/admin/mail/mail.html +4 -0
  20. package/plugins/_lib/admin/mail/message-actions.js +2 -0
  21. package/plugins/_lib/admin/mail/oauth-panel.js +2 -0
  22. package/plugins/_lib/admin/mail/panes.js +2 -0
  23. package/plugins/_lib/admin/mail/reader-kit.js +2 -0
  24. package/plugins/_lib/admin/mail/reader-runtime.js +6534 -0
  25. package/plugins/_lib/admin/mail/reader-view.js +9 -6380
  26. package/plugins/_lib/admin/mail/resizable.js +2 -0
  27. package/plugins/_lib/admin/mail/restore-spam.js +13 -0
  28. package/plugins/_lib/admin/mail/rules.js +14 -0
  29. package/plugins/_lib/admin/mail/scheduling.js +4 -1
  30. package/plugins/_lib/admin/mail/section-kit.js +4 -1
  31. package/plugins/_lib/admin/mail/security-note.js +2 -0
  32. package/plugins/_lib/admin/mail/settings-section.js +11 -10
  33. package/plugins/_lib/admin/mail/templates.js +5 -2
  34. package/plugins/_lib/admin/mail/threads.js +2 -0
  35. package/plugins/_lib/admin/mail/vacation.js +16 -2
  36. package/plugins/_lib/admin/mail/when-closed.js +24 -2
  37. package/plugins/_lib/admin/ui/dates.js +2 -0
  38. package/plugins/_lib/admin/ui/resizable.js +7 -5
  39. package/plugins/_lib/contacts/mailContact.js +69 -0
  40. package/plugins/_lib/contacts/model.js +199 -0
  41. package/plugins/_lib/domma-mail-contacts.lock.json +10 -0
  42. package/plugins/_lib/domma-mail.lock.json +85 -0
  43. package/plugins/_lib/mail/accountFileStore.js +66 -0
  44. package/plugins/_lib/mail/accountRepository.js +617 -0
  45. package/plugins/_lib/mail/accountRoutes.js +130 -0
  46. package/plugins/_lib/mail/accounts.js +66 -940
  47. package/plugins/_lib/mail/automationLock.js +10 -0
  48. package/plugins/_lib/mail/bodyTokenProvider.js +36 -0
  49. package/plugins/_lib/mail/bodyTokens.js +5 -99
  50. package/plugins/_lib/mail/compose.js +5 -3
  51. package/plugins/_lib/mail/defaults.js +2 -0
  52. package/plugins/_lib/mail/envelope.js +3 -1
  53. package/plugins/_lib/mail/folderActions.js +83 -0
  54. package/plugins/_lib/mail/folderRuntime.js +109 -0
  55. package/plugins/_lib/mail/folders.js +4 -9
  56. package/plugins/_lib/mail/imapPool.js +11 -389
  57. package/plugins/_lib/mail/imapPoolRuntime.js +396 -0
  58. package/plugins/_lib/mail/mbox.js +2 -0
  59. package/plugins/_lib/mail/message-action.js +2 -0
  60. package/plugins/_lib/mail/messageSecurity.js +4 -111
  61. package/plugins/_lib/mail/messageSecurityProvider.js +116 -0
  62. package/plugins/_lib/mail/networkAddresses.js +77 -0
  63. package/plugins/_lib/mail/networkPolicy.js +62 -0
  64. package/plugins/_lib/mail/oauth.js +3 -451
  65. package/plugins/_lib/mail/oauthAccounts.js +178 -0
  66. package/plugins/_lib/mail/oauthRouteRuntime.js +282 -0
  67. package/plugins/_lib/mail/oauthRoutes.js +7 -289
  68. package/plugins/_lib/mail/oauthRuntime.js +456 -0
  69. package/plugins/_lib/mail/pollSchedule.js +2 -0
  70. package/plugins/_lib/mail/poller.js +4 -136
  71. package/plugins/_lib/mail/pollerRuntime.js +150 -0
  72. package/plugins/_lib/mail/priority.js +2 -0
  73. package/plugins/_lib/mail/publicMailbox.js +27 -0
  74. package/plugins/_lib/mail/readRoutes.js +14 -827
  75. package/plugins/_lib/mail/readRuntime.js +701 -0
  76. package/plugins/_lib/mail/render.js +2 -0
  77. package/plugins/_lib/mail/ruleRunner.js +27 -10
  78. package/plugins/_lib/mail/scheduler.js +11 -279
  79. package/plugins/_lib/mail/schedulerRuntime.js +259 -0
  80. package/plugins/_lib/mail/secretProvider.js +112 -0
  81. package/plugins/_lib/mail/secretbox.js +12 -225
  82. package/plugins/_lib/mail/send.js +21 -537
  83. package/plugins/_lib/mail/sieve.js +211 -0
  84. package/plugins/_lib/mail/sieveHost.js +24 -0
  85. package/plugins/_lib/mail/smtpService.js +553 -0
  86. package/plugins/_lib/mail/snoozeRuntime.js +60 -0
  87. package/plugins/_lib/mail/store.js +122 -64
  88. package/plugins/_lib/mail/subscriptions.js +11 -0
  89. package/plugins/_lib/mail/sync.js +64 -290
  90. package/plugins/_lib/mail/syncPlan.js +2 -0
  91. package/plugins/_lib/mail/syncRuntime.js +255 -0
  92. package/plugins/_lib/mail/syncSelection.js +2 -0
  93. package/plugins/_lib/mail/unreadBadge.js +2 -0
  94. package/plugins/_lib/mail/unsubscribe.js +2 -0
  95. package/plugins/_lib/mail/vacationRunner.js +3 -116
  96. package/plugins/_lib/mail/vacationRuntime.js +70 -0
  97. package/plugins/_lib/mail/write.js +44 -13
  98. package/server/routes/api/contacts.js +2 -196
@@ -1,1085 +1,1091 @@
1
- /**
2
- * The compose window.
3
- *
4
- * A slideover built as real DOM and appended to `slideover.element`: passing
5
- * markup through setContent strips inputs and buttons, which is the single
6
- * most expensive thing to rediscover in this codebase.
7
- *
8
- * @module _lib/admin/mail/compose-window
9
- */
10
-
11
- /**
12
- * Render an address list into something editable.
13
- *
14
- * @param {Array<{name?: string, address?: string}>|undefined} list
15
- * @returns {string}
16
- */
17
- function addressesToText(list) {
18
- return (list ?? [])
19
- .map(entry => (entry.name ? `${entry.name} <${entry.address}>` : entry.address))
20
- .filter(Boolean)
21
- .join(', ');
22
- }
23
-
24
- /**
25
- * Parse what was typed back into addresses.
26
- *
27
- * Accepts "Name <a@b>" as well as bare addresses, because both are what
28
- * people paste.
29
- *
30
- * @param {string} text
31
- * @returns {{name: string, address: string}[]}
32
- */
33
- function textToAddresses(text) {
34
- return String(text ?? '')
35
- .split(/[,;]/)
36
- .map(part => part.trim())
37
- .filter(Boolean)
38
- .map(part => {
39
- const match = part.match(/^(.*?)\s*<([^>]+)>$/);
40
- return match
41
- ? {name: match[1].replace(/^["']|["']$/g, '').trim(), address: match[2].trim()}
42
- : {name: '', address: part};
43
- });
44
- }
45
-
46
- /**
47
- * Open a compose window.
48
- *
49
- * @param {{draft?: object, base: string, accountId: string, api: Function,
50
- * onSent?: (result: object) => void}} options
51
- * @returns {void}
52
- */
53
- /**
54
- * Human-readable byte size.
55
- *
56
- * @param {number} bytes
57
- * @returns {string}
58
- */
59
- function formatSize(bytes) {
60
- if (bytes < 1024) return `${bytes} B`;
61
- const units = ['KB', 'MB'];
62
- let value = bytes / 1024;
63
- let unit = 0;
64
- while (value >= 1024 && unit < units.length - 1) {
65
- value /= 1024;
66
- unit += 1;
67
- }
68
- return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
69
- }
70
-
71
- import {applyIdentity, findIdentity, identityFrom, swapSignature} from './identity.js';
72
- import {describeWhen, quickTimes, sendQuestion} from './scheduling.js';
73
- import {isSendShortcut} from './keyboard.js';
74
- import {fmtDateTime, fmtTime} from '../ui/dates.js';
75
- import {applyTemplate, expandTemplate} from './templates.js';
76
- import {makeResizable} from './resizable.js';
77
- import {whenClosed} from './when-closed.js';
78
- import {esc} from './reader-kit.js';
79
- import {installFontControls} from './font-controls.js';
80
- import {
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/compose-window.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ const MAIL_MODULE_VERSION = new URL(import.meta.url).searchParams.get('v') ?? '1';
4
+ const {createMailHost} = await import(new URL(`./host-context.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
5
+ const {applyIdentity, findIdentity, identityFrom, swapSignature} = await import(new URL(`./identity.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
6
+ const {describeWhen, quickTimes, sendQuestion} = await import(new URL(`./scheduling.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
7
+ const {isSendShortcut} = await import(new URL(`./keyboard.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
8
+ const {fmtDateTime, fmtTime} = await import(new URL(`../ui/dates.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
9
+ const {applyTemplate, expandTemplate} = await import(new URL(`./templates.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
10
+ const {makeResizable} = await import(new URL(`./resizable.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
11
+ const {whenClosed} = await import(new URL(`./when-closed.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
12
+ const {esc} = await import(new URL(`./reader-kit.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
13
+ const {installFontControls} = await import(new URL(`./font-controls.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
14
+ const {
81
15
  collectGroups,
82
16
  currentFragment,
83
17
  expandGroup,
84
18
  formatRecipient,
85
19
  replaceFragment,
86
20
  suggest
87
- } from './contacts.js';
88
-
89
- // Admin helpers by run-time import: a static import of /admin would take the
90
- // window down on an admin that predates them, so each has a stand-in.
91
- const toolKit = await import('/admin/js/lib/tool-kit.js').catch(() => ({}));
92
- const helpPopovers = (await import('/admin/js/lib/help-popover.js').catch(() => ({}))).helpPopovers ?? (() => () => {});
93
- const openMenuAt = toolKit.openMenuAt ?? ((el) => {
94
- const r = el.getBoundingClientRect();
95
- el.dispatchEvent(new MouseEvent('contextmenu', {bubbles: true, cancelable: true, clientX: r.left, clientY: r.bottom, view: window}));
96
- });
97
-
98
- /**
99
- * Turn plain text into the minimal HTML that preserves its line breaks.
100
- *
101
- * Used when opening the rich editor on a draft that only has a text version.
102
- *
103
- * @param {string} text
104
- * @returns {string}
105
- */
106
- function textToHtml(text) {
107
- const escaped = String(text ?? '')
108
- .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
109
- return escaped
110
- .split(/\n{2,}/)
111
- .map(block => `<p>${block.replace(/\n/g, '<br>')}</p>`)
112
- .join('');
113
- }
114
-
115
- /**
116
- * Read a file as base64, without the data-URL preamble.
117
- *
118
- * @param {File} file
119
- * @returns {Promise<string>}
120
- */
121
- function readAsBase64(file) {
122
- return new Promise((resolve, reject) => {
123
- const reader = new FileReader();
124
- reader.onload = () => resolve(String(reader.result).split(',')[1] ?? '');
125
- reader.onerror = () => reject(new Error(`${file.name} could not be read.`));
126
- reader.readAsDataURL(file);
127
- });
128
- }
129
-
130
- /**
131
- * Offer contact suggestions on one recipient field.
132
- *
133
- * Domma's own autocomplete rather than a bespoke dropdown - it already has the
134
- * keyboard handling, the positioning and the outside-click close, and three of
135
- * those are where a hand-rolled one goes wrong.
136
- *
137
- * The one thing it does not know is that this field holds a LIST. Its filter
138
- * is handed the whole input, and selecting an item replaces the whole input,
139
- * so both are re-pointed at the fragment after the last comma.
140
- *
141
- * @param {HTMLInputElement} input
142
- * @param {object[]} contacts
143
- * @param {object[]} groups
144
- * @returns {object|null} the instance, for teardown
145
- */
146
- function attachSuggestions(input, contacts, groups) {
147
- try {
148
- // The component assigns its own value to the field BEFORE calling
149
- // onSelect, so by then what was typed is gone. Kept here on every
150
- // keystroke, which is the only moment it is still true.
151
- input.dataset.mailValue = input.value;
152
- input.addEventListener('input', () => { input.dataset.mailValue = input.value; });
153
-
154
- return E.autocomplete(input, {
155
- minChars: 1,
156
- maxResults: 8,
157
- // Instant: the list is already in memory, and a delay on local
158
- // filtering is a delay for nothing.
159
- debounce: 0,
160
- emptyMessage: 'No matching contacts',
161
- // `dataSource` rather than `data` + `filterFn`, because a filter
162
- // is only a predicate: it decides who appears, not in what order,
163
- // and the component keeps the address book's own ordering. That
164
- // put "rob@samsung-parts.com" above "Sam Archer" for the query
165
- // "sam". Returning the list puts the ranking back in charge.
166
- //
167
- // `query` is the whole field. What is being typed is only ever the
168
- // part after the last separator; everything before it is a
169
- // recipient already chosen, and so must not be offered twice.
170
- dataSource: (query) => {
171
- const fragment = currentFragment(query);
172
- const chosen = textToAddresses(query.slice(0, query.length - fragment.length))
173
- .map(a => a.address);
174
- return suggest(contacts, groups, fragment, {exclude: chosen});
175
- },
176
- renderItem: entry => {
177
- const row = document.createElement('div');
178
- row.className = 'mail-suggest-row';
179
- const title = document.createElement('span');
180
- const detail = document.createElement('span');
181
- detail.className = 'text-xs mail-suggest-detail';
182
-
183
- if (entry.kind === 'group') {
184
- // Said plainly, because picking one puts several addresses
185
- // in the field at once and that should not be a surprise.
186
- const count = entry.members.length;
187
- title.textContent = `\u{1F465} ${entry.name}`;
188
- detail.textContent = `Group \u00b7 ${count} ${count === 1 ? 'person' : 'people'}`;
189
- } else {
190
- title.textContent = entry.favourite && entry.name
191
- ? `\u2605 ${entry.name}`
192
- : (entry.name || entry.email);
193
- detail.textContent = entry.name ? entry.email : '';
194
- }
21
+ } = await import(new URL(`./contacts.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
22
+ export function createComposeWindow(mailHost) {
23
+ const {M, E, Domma} = mailHost;
24
+ const {helpPopovers, openMenuAt} = mailHost.helpers;
25
+ /**
26
+ * The compose window.
27
+ *
28
+ * A slideover built as real DOM and appended to `slideover.element`: passing
29
+ * markup through setContent strips inputs and buttons, which is the single
30
+ * most expensive thing to rediscover in this codebase.
31
+ *
32
+ * @module _lib/admin/mail/compose-window
33
+ */
195
34
 
196
- row.appendChild(title);
197
- if (detail.textContent) row.appendChild(detail);
198
- return row;
199
- },
200
- // The component has already overwritten the field with its own
201
- // idea of the value by the time this runs, so this puts the list
202
- // back and appends rather than replaces.
203
- onSelect: (entry, {target}) => {
204
- const before = target.dataset.mailValue ?? '';
205
- const fragment = currentFragment(before);
206
- const chosen = textToAddresses(before.slice(0, before.length - fragment.length))
207
- .map(a => a.address);
208
-
209
- const replacement = entry.kind === 'group'
210
- ? expandGroup(entry, {exclude: chosen})
211
- : formatRecipient(entry);
212
-
213
- target.value = replaceFragment(before, replacement);
214
- target.dataset.mailValue = target.value;
215
- target.setSelectionRange(target.value.length, target.value.length);
216
- }
217
- });
218
- } catch {
219
- // An older Domma without it, or a shape it does not like. The field is
220
- // a plain text input either way.
221
- return null;
35
+ /**
36
+ * Render an address list into something editable.
37
+ *
38
+ * @param {Array<{name?: string, address?: string}>|undefined} list
39
+ * @returns {string}
40
+ */
41
+ function addressesToText(list) {
42
+ return (list ?? [])
43
+ .map(entry => (entry.name ? `${entry.name} <${entry.address}>` : entry.address))
44
+ .filter(Boolean)
45
+ .join(', ');
222
46
  }
223
- }
224
-
225
- /**
226
- * The compose window's markup. Built as a string and parsed into a `<div>` this
227
- * module owns, never passed through `setContent` (which strips inputs and
228
- * buttons). View state is bound with domma-reactive; the inputs themselves are
229
- * read directly, because the editor, the address suggestions and the template
230
- * picker all work on the live field.
231
- *
232
- * No `{{…}}` in the attachment row but the key: Domma's `data-each` compiler
233
- * drops the whitespace beside an interpolation, so labels come from JS.
234
- */
235
- const FORM = `
236
- <div class="mail-compose-form">
237
- <div class="form-group" data-bind-hidden="!hasFrom">
238
- <label class="form-label">From
239
- <span data-help-title="From" data-help="Which of this mailbox's identities sends the message. Changing it swaps the signature in the message for the new one's, where the old signature can still be found unchanged."></span>
240
- </label>
241
- <select class="form-select" data-ref="from"></select>
242
- </div>
243
- <div>
244
- <label class="form-label">To
245
- <span data-help-title="Recipients" data-help="Separate several addresses with commas. Name <address> works as well as a bare address. Start typing to pick from Contacts; a group puts all of its members in at once."></span>
246
- </label>
247
- <input type="text" class="form-input" data-ref="to" placeholder="someone@example.com">
248
- <button type="button" class="btn btn-sm btn-ghost mail-extras-toggle" data-on-click="toggleExtras"
249
- data-bind-text="extrasLabel.value" data-bind-aria-expanded="extrasAria.value"></button>
250
- </div>
251
- <div data-bind-hidden="!extrasOpen.value">
252
- <label class="form-label">Cc</label>
253
- <input type="text" class="form-input" data-ref="cc">
254
- </div>
255
- <div data-bind-hidden="!extrasOpen.value">
256
- <label class="form-label">Bcc
257
- <span data-help="Bcc recipients get the message, but nobody else sees that they did - not even the other Bcc recipients."></span>
258
- </label>
259
- <input type="text" class="form-input" data-ref="bcc">
260
- </div>
261
- <div data-bind-hidden="!extrasOpen.value">
262
- <label class="form-label">Priority
263
- <span data-help="Marks the message as urgent or unimportant in the recipient's mail client. Most show it as a flag or an icon; none sends it any faster."></span>
264
- </label>
265
- <select class="form-select" data-ref="priority">
266
- <option value="normal">Normal</option>
267
- <option value="high">High</option>
268
- <option value="low">Low</option>
269
- </select>
270
- </div>
271
- <div>
272
- <label class="form-label">Subject</label>
273
- <input type="text" class="form-input" data-ref="subject">
274
- </div>
275
- <div class="mail-compose-body">
276
- <label class="form-label">Message</label>
277
- <div class="flex items-center gap-2 mail-template-row" data-bind-hidden="!hasTemplates">
278
- <select class="form-select form-select-sm mail-template-picker" data-ref="template">
279
- <option value="">Insert a template…</option>
280
- </select>
281
- <span data-help-title="Templates" data-help="Canned text from Mail Settings. Choosing one adds it above what is already written, fills in the recipient's name and your own, and sets the subject if it is empty."></span>
282
- </div>
283
- <div class="mail-compose-editor" data-ref="editor"></div>
284
- </div>
285
- <div class="flex items-center gap-3 flex-wrap mail-compose-options">
286
- <span class="flex items-center gap-1">
287
- <label class="form-check">
288
- <input type="checkbox" class="form-check-input" data-ref="receipt">
289
- <span class="form-check-label">Read receipt</span>
290
- </label>
291
- <span data-help-title="Read receipts" data-help="Asks the recipient's mail program to say when the message is opened. A request, not a guarantee: many ignore it, or ask the recipient first - so no receipt does not mean the message is unread."></span>
292
- </span>
293
- <span class="flex items-center gap-1">
294
- <label class="form-check">
295
- <input type="checkbox" class="form-check-input" data-ref="delivery">
296
- <span class="form-check-label">Delivery receipt</span>
297
- </label>
298
- <span data-help-title="Delivery receipts" data-help="Asks the mail servers on the way to report when the message reaches each recipient's mailbox (a delivery status notification). Arrives as an email from the server. Only servers that support it reply, so silence proves nothing either way."></span>
299
- </span>
300
- <span class="flex items-center gap-2" data-bind-hidden="!showSecurity">
301
- <label class="form-check">
302
- <input type="checkbox" class="form-check-input" data-ref="sign">
303
- <span class="form-check-label">Sign</span>
304
- </label>
305
- <label class="form-check">
306
- <input type="checkbox" class="form-check-input" data-ref="encrypt">
307
- <span class="form-check-label">Encrypt</span>
308
- </label>
309
- <span data-help-title="Sign and encrypt (S/MIME)" data-help="Sign adds your certificate's digital signature, so recipients can see the message is from you and unchanged. Encrypt makes it readable only by the recipients (and you): it needs a certificate for every recipient, which you get when they send you a signed message or add in Settings > Security. Subjects are never encrypted."></span>
310
- </span>
311
- </div>
312
- <div class="flex items-center gap-2 flex-wrap">
313
- <button type="button" class="btn btn-sm btn-ghost" data-on-click="pickFiles">Attach files</button>
314
- <span data-bind-class="attachTone.value" data-bind-text="attachSummary.value"></span>
315
- <span data-help-title="Attachments" data-help="The running total is shown as you add files, and turns red over this mailbox's limit - a message that large cannot be sent. Right-click a file (or use its ⋮, or Shift+F10) to remove it."></span>
316
- </div>
317
- <input type="file" multiple hidden data-ref="files">
318
- <div class="mail-attach-list" data-each="attachRows.value key=key"></div>
319
- <div data-bind-class="statusClass.value" data-bind-text="statusText.value"></div>
320
- <div class="flex justify-end items-center gap-2">
321
- <button type="button" class="btn btn-sm btn-ghost" data-on-click="discard">Discard</button>
322
- <button type="button" class="btn btn-sm btn-ghost" data-on-click="saveDraft" data-bind-disabled="saving.value">Save draft</button>
323
- <button type="button" class="btn btn-sm btn-ghost" data-on-click="later" title="Send this at a time you choose">Later…</button>
324
- <button type="button" class="btn btn-sm btn-primary" data-on-click="send"
325
- data-bind-disabled="cannotSend.value" data-bind-text="sendLabel.value" data-bind-title="sendTitle.value"></button>
326
- <span data-help-title="Sending" data-help="Ctrl+Enter (Cmd+Enter on a Mac) sends too, after asking first. Later… sends at a time you choose, and the button then says when. With an undo delay set in Mail Settings, Send holds the message for those seconds so you can take it back; it has not gone until they pass."></span>
327
- </div>
328
- </div>`;
329
-
330
- /** One attachment. Only the key is interpolated; see FORM. */
331
- const ATTACH_ROW = `
332
- <div class="mail-box-row mail-attach-row" data-key="{{key}}" tabindex="0">
333
- <span class="flex-1 text-sm mail-ellipsis" data-bind-text="label"></span>
334
- <button type="button" class="btn btn-sm btn-ghost mail-attach-kebab" aria-label="Attachment actions" title="Actions">⋮</button>
335
- </div>`;
336
-
337
- export function openCompose({
338
- draft: opened = {}, base, accountId, api, maxAttachmentBytes = 20_000_000,
339
- onSent = () => {}, onSaved = () => {}, onQueued = () => {}, contacts = [],
340
- identities = [], mailboxAddress = '', templates = [], undoSeconds = 0,
341
- mode = 'new', defaults = null, security = null, prefs = {}
342
- }) {
343
- // How this message was started, decided once. A reopened draft is never
344
- // treated as new: it already carries the signature it was written with,
345
- // and adding another on reopen is how a draft edited four times goes out
346
- // with four.
347
- const openedAs = opened.savedUid ? 'edit' : mode;
348
-
349
- /** Which identity is sending. Changeable while the window is open. */
350
- let currentIdentity = findIdentity(identities, opened.identityId) ?? null;
351
-
352
- // The one place all four ways of starting a message meet - new, reply,
353
- // forward and reopened draft - so it is the one place the signature goes
354
- // on. `applyIdentity` decides whether this mode gets one.
355
- const draft = applyIdentity(opened, currentIdentity, openedAs);
356
-
357
- const slideover = E.slideover({
358
- title: draft.savedUid
359
- ? 'Draft'
360
- // From the mode, not the subject: a new message can arrive with
361
- // a subject already in it (Contacts' "Send birthday wishes").
362
- : (draft.inReplyTo ? 'Reply' : (openedAs === 'forward' ? 'Forward' : 'New message')),
363
- size: 'lg',
364
- position: 'right'
365
- });
366
-
367
- const host = document.createElement('div');
368
- host.innerHTML = FORM;
369
- const form = host.firstElementChild;
370
- /** @param {string} name @returns {HTMLElement} */
371
- const ref = (name) => form.querySelector(`[data-ref="${name}"]`);
372
-
373
- const fromSelect = ref('from');
374
- const toInput = ref('to');
375
- const ccInput = ref('cc');
376
- const bccInput = ref('bcc');
377
- const prioritySelect = ref('priority');
378
- const receiptInput = ref('receipt');
379
- const deliveryInput = ref('delivery');
380
- const signInput = ref('sign');
381
- const encryptInput = ref('encrypt');
382
- const subjectInput = ref('subject');
383
- const picker = ref('template');
384
- const editorHost = ref('editor');
385
- const fileInput = ref('files');
386
-
387
- // ---- View state ------------------------------------------------------
388
-
389
- /** A time this message should go at, rather than now. */
390
- const scheduledAt = M.observable(null);
391
-
392
- // Cc, Bcc and priority are folded away until wanted. Most messages use
393
- // none of them, and empty rows between the recipient and the subject are
394
- // rows of nothing in the part of the window someone looks at first.
395
- //
396
- // Opened when the draft already carries any of them: a reply-all or a
397
- // reopened draft with a hidden Cc would be a message quietly going
398
- // somewhere the sender cannot see, and a reopened urgent draft with the
399
- // picker folded away would look ordinary.
400
- const extrasOpen = M.observable(Boolean(
401
- draft.cc?.length || draft.bcc?.length || ['high', 'low'].includes(draft.priority)
402
- ));
403
- const extrasLabel = M.observable('');
404
- // A string: a bound boolean becomes an empty attribute, and aria-expanded needs "true"/"false".
405
- const extrasAria = M.observable('false');
406
-
407
- // Attachments, seeded from the draft so reopening one keeps its files -
408
- // normalised to the picker's shape on the way in. The server calls the
409
- // length `size` and the picker calls it `bytes`, and seeding the server's
410
- // shape verbatim renders "notes.txt (undefined)" with a NaN running total.
411
- // Falling back to the base64 length is the honest measure anyway: that is
412
- // what will actually be sent.
413
- let nextKey = 0;
414
- const attachments = M.observable((draft.attachments ?? []).map(file => ({
415
- key: `a${nextKey++}`,
416
- filename: file.filename,
417
- contentType: file.contentType,
418
- content: file.content,
419
- bytes: file.bytes ?? file.size ?? Math.floor(String(file.content ?? '').length * 3 / 4)
420
- })));
421
- const attachRows = M.observable([]);
422
- const attachSummary = M.observable('');
423
- const attachTone = M.observable('text-xs text-muted');
424
- const overLimit = M.observable(false);
425
-
426
- const statusText = M.observable('');
427
- const statusClass = M.observable('text-sm mail-status text-muted');
428
- const saving = M.observable(false);
429
- const sending = M.observable(false);
430
- const cannotSend = M.observable(false);
431
- const sendLabel = M.observable('Send');
432
- const sendTitle = M.observable('');
433
-
434
- const effects = [
435
- M.effect(() => {
436
- extrasLabel.value = extrasOpen.value ? 'Hide Cc and Bcc' : 'Cc / Bcc';
437
- extrasAria.value = String(extrasOpen.value);
438
- }),
439
- // The total is shown as it grows rather than only on send, because
440
- // being told a message is too large after writing it is a poor moment
441
- // to find out - and red once it is over, which is the only reason the
442
- // number is on screen at all.
443
- M.effect(() => {
444
- const list = attachments.value;
445
- const total = list.reduce((n, a) => n + a.bytes, 0);
446
- overLimit.value = total > maxAttachmentBytes;
447
- attachSummary.value = list.length
448
- ? `${list.length} file${list.length === 1 ? '' : 's'}, ${formatSize(total)} of ${formatSize(maxAttachmentBytes)}`
449
- : '';
450
- attachTone.value = overLimit.value ? 'text-xs text-danger' : 'text-xs text-muted';
451
- attachRows.value = list.map(a => ({key: a.key, label: `${a.filename} (${formatSize(a.bytes)})`}));
452
- }),
453
- M.effect(() => {
454
- cannotSend.value = sending.value || overLimit.value;
455
- }),
456
- // Three different things wear the Send button: send now, hold briefly
457
- // so it can be taken back, and send at a chosen time. Calling all
458
- // three "Send" is how someone finds out about the ten second hold by
459
- // watching a message not arrive.
460
- M.effect(() => {
461
- const at = scheduledAt.value;
462
- sendLabel.value = at ? `Send ${describeWhen(at)}` : 'Send';
463
- sendTitle.value = at
464
- ? fmtDateTime(at)
465
- : (undoSeconds > 0 ? `Held for ${undoSeconds} seconds so you can take it back.` : '');
466
- })
467
- ];
468
47
 
469
48
  /**
470
- * Say something under the message, in the right colour. A class rather
471
- * than `style.color`, so the colour follows the theme.
49
+ * Parse what was typed back into addresses.
50
+ *
51
+ * Accepts "Name <a@b>" as well as bare addresses, because both are what
52
+ * people paste.
472
53
  *
473
54
  * @param {string} text
474
- * @param {'ok'|'bad'|'quiet'} [tone]
475
- * @returns {void}
55
+ * @returns {{name: string, address: string}[]}
476
56
  */
477
- function say(text, tone = 'quiet') {
478
- statusText.value = text ?? '';
479
- statusClass.value = 'text-sm mail-status '
480
- + ({ok: 'text-success', bad: 'text-danger'}[tone] ?? 'text-muted');
481
- }
482
-
483
- // ---- Fields ------------------------------------------------------------
484
-
485
- toInput.value = addressesToText(draft.to);
486
- ccInput.value = addressesToText(draft.cc);
487
- bccInput.value = addressesToText(draft.bcc);
488
- subjectInput.value = draft.subject ?? '';
489
- prioritySelect.value = ['high', 'low'].includes(draft.priority) ? draft.priority : 'normal';
490
-
491
- // The ticks. A reopened draft keeps what it was saved with; anything else
492
- // starts from the mailbox's choices (Settings > Composing), unless the
493
- // caller already said - a message handed back by Undo carries its own.
494
- const tick = key => (openedAs === 'edit' ? draft[key] === true : (draft[key] ?? defaults?.[key]) === true);
495
- receiptInput.checked = tick('readReceipt');
496
- deliveryInput.checked = tick('deliveryReceipt');
497
- // Signing and encrypting where this edition can (Email Pro) and the
498
- // mailbox has a certificate. A message that ASKED for them (a reopened
499
- // draft, Undo, the mailbox's default) keeps the tick even when they cannot
500
- // be done now - an expired certificate, a profile that did not load - so
501
- // the server refuses it with the reason rather than it quietly going out
502
- // in the clear. Only an unticked box that cannot be used is greyed.
503
- const wanted = {sign: tick('sign'), encrypt: tick('encrypt')};
504
- const showSecurity = security?.available === true || wanted.sign || wanted.encrypt;
505
- for (const [input, can, key] of [[signInput, security?.canSign, 'sign'], [encryptInput, security?.canEncrypt, 'encrypt']]) {
506
- input.checked = wanted[key];
507
- input.disabled = can !== true && !wanted[key];
508
- if (can !== true && security?.reason) input.closest('label').title = security.reason;
509
- // Once unticked, a box that cannot be used is greyed for good.
510
- input.addEventListener('change', () => { if (!input.checked && can !== true) input.disabled = true; });
57
+ function textToAddresses(text) {
58
+ return String(text ?? '')
59
+ .split(/[,;]/)
60
+ .map(part => part.trim())
61
+ .filter(Boolean)
62
+ .map(part => {
63
+ const match = part.match(/^(.*?)\s*<([^>]+)>$/);
64
+ return match
65
+ ? {name: match[1].replace(/^["']|["']$/g, '').trim(), address: match[2].trim()}
66
+ : {name: '', address: part};
67
+ });
511
68
  }
512
69
 
513
70
  /**
514
- * Does this identity have a signature that would have been added?
71
+ * Open a compose window.
515
72
  *
516
- * @param {object|null} entry
517
- * @returns {boolean}
73
+ * @param {{draft?: object, base: string, accountId: string, api: Function,
74
+ * onSent?: (result: object) => void}} options
75
+ * @returns {void}
518
76
  */
519
- function hasSignatureFor(entry) {
520
- return Boolean(entry?.signatureHtml || entry?.signatureText);
521
- }
522
-
523
- // The From picker, and only when there is a choice to make. One identity
524
- // is not a choice, and a row saying so on every message is a row nobody
525
- // reads.
526
- const hasFrom = identities.length > 1;
527
- if (hasFrom) {
528
- for (const entry of identities) {
529
- const option = document.createElement('option');
530
- option.value = entry.id;
531
- // The address as it will appear, not the label alone - the label
532
- // is what the owner called it and the address is what the
533
- // recipient will see, and those are the two different questions
534
- // "which of these am I?" asks.
535
- const shown = identityFrom(entry, mailboxAddress);
536
- option.textContent = entry.label === shown ? shown : `${entry.label} — ${shown}`;
537
- fromSelect.appendChild(option);
538
- }
539
- fromSelect.value = currentIdentity?.id ?? identities[0].id;
540
-
541
- fromSelect.addEventListener('change', () => {
542
- currentIdentity = findIdentity(identities, fromSelect.value);
543
- // The signature in the body belongs to whoever was sending a
544
- // moment ago. Swapped where it can be found and left alone where
545
- // it cannot - see `swapSignature`.
546
- if (editor) {
547
- const {html, swapped} = swapSignature(editor.getValue(), currentIdentity, openedAs);
548
- if (swapped) editor.setValue(html);
549
- else if (hasSignatureFor(currentIdentity)) {
550
- E.toast(
551
- 'The sender changed, but the signature already in this message was left as it is.',
552
- {type: 'info'}
553
- );
554
- }
555
- }
556
- });
557
- }
558
-
559
- // Suggest recipients from the Contacts plugin, if this site has it. The
560
- // address book is passed in rather than fetched here: the view already
561
- // holds it for its own "add sender" action, and two windows open at once
562
- // should not mean two requests for the same unchanging list.
563
- const suggesters = [];
564
- if (contacts.length && typeof E?.autocomplete === 'function') {
565
- const groups = collectGroups(contacts);
566
- for (const input of [toInput, ccInput, bccInput]) {
567
- const suggester = attachSuggestions(input, contacts, groups);
568
- if (suggester) suggesters.push(suggester);
569
- }
570
- }
571
-
572
- // Canned responses, and only when this mailbox has any. A picker offering
573
- // nothing is a picker that has to explain itself.
574
- const hasTemplates = templates.length > 0;
575
- for (const template of templates) {
576
- const option = document.createElement('option');
577
- option.value = template.id;
578
- option.textContent = template.name;
579
- picker.appendChild(option);
580
- }
581
- picker.addEventListener('change', () => {
582
- const chosen = templates.find(t => t.id === picker.value);
583
- // Back to the placeholder straight away: the picker is an action, not
584
- // a setting, and leaving the last-used one showing reads as "this
585
- // message is that template".
586
- picker.value = '';
587
- if (!chosen) return;
588
-
589
- const expanded = expandTemplate(chosen, {
590
- to: textToAddresses(toInput.value),
591
- subject: subjectInput.value,
592
- identity: currentIdentity,
593
- fromAddress: mailboxAddress
594
- });
595
-
596
- const current = {
597
- subject: subjectInput.value,
598
- html: editor ? editor.getValue() : '',
599
- body: editor ? editor.getText() : bodyInput.value
600
- };
601
- const next = applyTemplate(current, expanded);
602
-
603
- subjectInput.value = next.subject;
604
- if (editor) editor.setValue(next.html);
605
- else bodyInput.value = next.body;
606
- });
607
-
608
- // Domma's own editor, in rich mode. A plain textarea is kept as the
609
- // fallback rather than assumed away: the editor is a component that may
610
- // not be present in an older Domma, and a compose window that cannot type
611
- // is worse than one without bold.
612
- const bodyInput = document.createElement('textarea');
613
- bodyInput.className = 'form-textarea mail-compose-textarea';
614
- bodyInput.value = draft.body ?? '';
615
-
616
- let editor = null;
617
- let fontControls = null;
618
- // Rich unless this browser chose plain text - but a draft written with
619
- // formatting reopens with it, or saving it again would strip it.
620
- const wantRich = prefs?.editor !== 'plain' || (openedAs === 'edit' && Boolean(draft.html));
621
- if (wantRich && typeof E?.editor === 'function') {
622
- try {
623
- editor = E.editor(editorHost, {mode: 'rich', height: '34vh'});
624
- editor.setValue(draft.html || textToHtml(draft.body ?? ''));
625
- try { fontControls = installFontControls(editor); } catch { fontControls = null; }
626
- } catch {
627
- editor = null;
628
- }
629
- }
630
- if (!editor) editorHost.replaceWith(bodyInput);
631
-
632
- // Spelling: the browser's own checker, on the fields that hold words.
633
- // Never on addresses - every one would be underlined.
634
- const spell = prefs?.spellcheck !== false;
635
- for (const input of [toInput, ccInput, bccInput]) input.spellcheck = false;
636
- for (const input of [subjectInput, bodyInput]) input.spellcheck = spell;
637
- for (const el of editorHost.querySelectorAll('[contenteditable]')) el.spellcheck = spell;
638
-
639
- // ---- Attachments -------------------------------------------------------
640
-
641
- fileInput.addEventListener('change', async () => {
642
- const chosen = [...fileInput.files];
643
- fileInput.value = '';
644
- const added = [];
645
- for (const file of chosen) {
646
- try {
647
- added.push({
648
- key: `a${nextKey++}`,
649
- filename: file.name,
650
- contentType: file.type || 'application/octet-stream',
651
- content: await readAsBase64(file),
652
- bytes: file.size
653
- });
654
- } catch (err) {
655
- E.toast(err.message, {type: 'error'});
656
- }
77
+ /**
78
+ * Human-readable byte size.
79
+ *
80
+ * @param {number} bytes
81
+ * @returns {string}
82
+ */
83
+ function formatSize(bytes) {
84
+ if (bytes < 1024) return `${bytes} B`;
85
+ const units = ['KB', 'MB'];
86
+ let value = bytes / 1024;
87
+ let unit = 0;
88
+ while (value >= 1024 && unit < units.length - 1) {
89
+ value /= 1024;
90
+ unit += 1;
657
91
  }
658
- if (added.length) attachments.value = [...attachments.peek(), ...added];
659
- });
660
-
661
- /** @param {string} key */
662
- function removeAttachment(key) {
663
- attachments.value = attachments.peek().filter(a => a.key !== key);
92
+ return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
664
93
  }
665
94
 
666
- // ---- Draft and close guard ---------------------------------------------
667
-
668
- // The UID of this draft's previous version, once it has been saved once,
669
- // so a second save replaces rather than accumulates.
670
- let savedUid = draft.savedUid ?? null;
671
-
672
- /** What the message says now - compared with the last saved (or opened) state. */
673
- function snapshot() {
674
- const current = editor ? editor.getText() : bodyInput.value;
675
- return JSON.stringify([subjectInput.value.trim(), current.trim(), toInput.value.trim(),
676
- ccInput.value.trim(), bccInput.value.trim(), attachments.peek().length]);
677
- }
678
- let savedSnapshot = null; // set once the window is built (below)
679
- // The last state written to Drafts by either kind of save, so the timer
680
- // does not save the same text twice.
681
- let persistedSnapshot = null;
682
- let savedByHand = false;
683
- /** A save in flight - Send waits for it, so `replaces` names the draft it wrote. */
684
- let savePromise = null;
685
- // Only automatic saves so far, of a message that was not a draft when it
686
- // opened: discarding it then takes the automatic draft away too, as
687
- // every mail program with autosave does.
688
- let autoOnly = false;
689
95
 
690
96
  /**
691
- * Whether closing now would lose something.
97
+ * Turn plain text into the minimal HTML that preserves its line breaks.
98
+ *
99
+ * Used when opening the rich editor on a draft that only has a text version.
692
100
  *
693
- * Compared with the last saved state, or what the window opened with - so
694
- * a reopened draft closed unchanged does not ask, and a reply or forward,
695
- * which opens with `Re:` / `Fwd:` and a quote already in it, does not
696
- * count as unsaved work until the reader actually changes something.
101
+ * @param {string} text
102
+ * @returns {string}
697
103
  */
698
- function unsaved() {
699
- if (savedSnapshot === null) return false;
700
- const now = snapshot();
701
- if (now === savedSnapshot) return false;
702
- // Written by an automatic save into a draft that stays: nothing to lose.
703
- return !(now === persistedSnapshot && !autoOnly);
704
- }
705
-
706
- /** The question the close guard asks, for what would be lost. */
707
- function discardQuestion() {
708
- return savedUid
709
- ? 'Close without saving? The changes since you last saved this draft will be lost.'
710
- : 'Discard this message? It has not been saved as a draft.';
104
+ function textToHtml(text) {
105
+ const escaped = String(text ?? '')
106
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
107
+ return escaped
108
+ .split(/\n{2,}/)
109
+ .map(block => `<p>${block.replace(/\n/g, '<br>')}</p>`)
110
+ .join('');
711
111
  }
712
112
 
713
113
  /**
714
- * The message as it currently stands.
114
+ * Read a file as base64, without the data-URL preamble.
715
115
  *
716
- * @returns {object}
116
+ * @param {File} file
117
+ * @returns {Promise<string>}
717
118
  */
718
- function collect() {
719
- // Both parts, always: the HTML for clients that render it and the text
720
- // for those that do not. Taking the text from the editor rather than
721
- // stripping tags means it reads as prose rather than as markup with
722
- // the angle brackets removed.
723
- const html = editor ? editor.getValue() : null;
724
- const text = editor ? editor.getText() : bodyInput.value;
725
-
726
- return {
727
- to: textToAddresses(toInput.value),
728
- cc: textToAddresses(ccInput.value),
729
- bcc: textToAddresses(bccInput.value),
730
- priority: prioritySelect.value,
731
- readReceipt: receiptInput.checked,
732
- deliveryReceipt: deliveryInput.checked,
733
- sign: signInput.checked,
734
- encrypt: encryptInput.checked,
735
- // Which of the mailbox's identities is sending. Null where there
736
- // is only one, which is what the server reads as "the default".
737
- identityId: currentIdentity?.id ?? null,
738
- subject: subjectInput.value,
739
- body: text,
740
- html,
741
- inReplyTo: draft.inReplyTo ?? null,
742
- references: draft.references ?? [],
743
- sourceMessage: draft.sourceMessage ?? null,
744
- attachments: attachments.peek().map(({filename, contentType, content}) =>
745
- ({filename, contentType, content}))
746
- };
119
+ function readAsBase64(file) {
120
+ return new Promise((resolve, reject) => {
121
+ const reader = new FileReader();
122
+ reader.onload = () => resolve(String(reader.result).split(',')[1] ?? '');
123
+ reader.onerror = () => reject(new Error(`${file.name} could not be read.`));
124
+ reader.readAsDataURL(file);
125
+ });
747
126
  }
748
127
 
749
128
  /**
750
- * Save this message to the mailbox's Drafts folder - the button, and what
751
- * leaving the screen does with a message that has changed.
129
+ * Offer contact suggestions on one recipient field.
752
130
  *
753
- * @returns {Promise<object|null>} the server's answer, or null if it failed
131
+ * Domma's own autocomplete rather than a bespoke dropdown - it already has the
132
+ * keyboard handling, the positioning and the outside-click close, and three of
133
+ * those are where a hand-rolled one goes wrong.
134
+ *
135
+ * The one thing it does not know is that this field holds a LIST. Its filter
136
+ * is handed the whole input, and selecting an item replaces the whole input,
137
+ * so both are re-pointed at the fragment after the last comma.
138
+ *
139
+ * @param {HTMLInputElement} input
140
+ * @param {object[]} contacts
141
+ * @param {object[]} groups
142
+ * @returns {object|null} the instance, for teardown
754
143
  */
755
- async function saveDraft({auto = false} = {}) {
756
- // One save at a time, in order - a chain, so two waiting saves cannot
757
- // start together with the same `replaces` and leave two drafts. Send
758
- // waits on the tail, so it names the latest draft.
759
- const run = (savePromise ?? Promise.resolve()).catch(() => {}).then(() => saveDraftNow({auto}));
760
- savePromise = run;
761
- try { return await run; } finally { if (savePromise === run) savePromise = null; }
762
- }
763
-
764
- async function saveDraftNow({auto = false} = {}) {
765
- saving.value = true;
766
- if (!auto) say('Saving…');
144
+ function attachSuggestions(input, contacts, groups) {
767
145
  try {
768
- const params = new URLSearchParams({account: accountId});
769
- const taken = snapshot();
770
- const result = await api(`${base}/drafts?${params}`, 'POST', {
771
- ...collect(),
772
- replaces: savedUid
146
+ // The component assigns its own value to the field BEFORE calling
147
+ // onSelect, so by then what was typed is gone. Kept here on every
148
+ // keystroke, which is the only moment it is still true.
149
+ input.dataset.mailValue = input.value;
150
+ input.addEventListener('input', () => { input.dataset.mailValue = input.value; });
151
+
152
+ return E.autocomplete(input, {
153
+ minChars: 1,
154
+ maxResults: 8,
155
+ // Instant: the list is already in memory, and a delay on local
156
+ // filtering is a delay for nothing.
157
+ debounce: 0,
158
+ emptyMessage: 'No matching contacts',
159
+ // `dataSource` rather than `data` + `filterFn`, because a filter
160
+ // is only a predicate: it decides who appears, not in what order,
161
+ // and the component keeps the address book's own ordering. That
162
+ // put "rob@samsung-parts.com" above "Sam Archer" for the query
163
+ // "sam". Returning the list puts the ranking back in charge.
164
+ //
165
+ // `query` is the whole field. What is being typed is only ever the
166
+ // part after the last separator; everything before it is a
167
+ // recipient already chosen, and so must not be offered twice.
168
+ dataSource: (query) => {
169
+ const fragment = currentFragment(query);
170
+ const chosen = textToAddresses(query.slice(0, query.length - fragment.length))
171
+ .map(a => a.address);
172
+ return suggest(contacts, groups, fragment, {exclude: chosen});
173
+ },
174
+ renderItem: entry => {
175
+ const row = document.createElement('div');
176
+ row.className = 'mail-suggest-row';
177
+ const title = document.createElement('span');
178
+ const detail = document.createElement('span');
179
+ detail.className = 'text-xs mail-suggest-detail';
180
+
181
+ if (entry.kind === 'group') {
182
+ // Said plainly, because picking one puts several addresses
183
+ // in the field at once and that should not be a surprise.
184
+ const count = entry.members.length;
185
+ title.textContent = `\u{1F465} ${entry.name}`;
186
+ detail.textContent = `Group \u00b7 ${count} ${count === 1 ? 'person' : 'people'}`;
187
+ } else {
188
+ title.textContent = entry.favourite && entry.name
189
+ ? `\u2605 ${entry.name}`
190
+ : (entry.name || entry.email);
191
+ detail.textContent = entry.name ? entry.email : '';
192
+ }
193
+
194
+ row.appendChild(title);
195
+ if (detail.textContent) row.appendChild(detail);
196
+ return row;
197
+ },
198
+ // The component has already overwritten the field with its own
199
+ // idea of the value by the time this runs, so this puts the list
200
+ // back and appends rather than replaces.
201
+ onSelect: (entry, {target}) => {
202
+ const before = target.dataset.mailValue ?? '';
203
+ const fragment = currentFragment(before);
204
+ const chosen = textToAddresses(before.slice(0, before.length - fragment.length))
205
+ .map(a => a.address);
206
+
207
+ const replacement = entry.kind === 'group'
208
+ ? expandGroup(entry, {exclude: chosen})
209
+ : formatRecipient(entry);
210
+
211
+ target.value = replaceFragment(before, replacement);
212
+ target.dataset.mailValue = target.value;
213
+ target.setSelectionRange(target.value.length, target.value.length);
214
+ }
773
215
  });
774
- savedUid = result.uid ?? savedUid;
775
- persistedSnapshot = taken;
776
- if (auto) {
777
- // NOT the close question's baseline: an automatic save is a
778
- // safety net, and closing still asks whether to keep it.
779
- autoOnly = !savedByHand && !opened.savedUid;
780
- say(`Draft saved automatically at ${fmtTime(new Date())}.`);
781
- } else {
782
- // Saved is the new baseline: closing now loses nothing.
783
- savedSnapshot = taken;
784
- savedByHand = true;
785
- autoOnly = false;
786
- say(`Saved to ${result.savedTo}.`, 'ok');
787
- }
788
- // The Drafts folder now holds a different set of UIDs, so a list
789
- // showing it is out of date whether or not the window closes.
790
- onSaved(result);
791
- return result;
792
- } catch (err) {
793
- say(err.message, 'bad');
216
+ } catch {
217
+ // An older Domma without it, or a shape it does not like. The field is
218
+ // a plain text input either way.
794
219
  return null;
795
- } finally {
796
- saving.value = false;
797
220
  }
798
221
  }
799
222
 
800
- // ---- Sending -----------------------------------------------------------
801
-
802
223
  /**
803
- * Choose a time to send at.
804
- *
805
- * The quick choices come from the same module the server validates
806
- * against, so a time offered here cannot be refused there.
224
+ * The compose window's markup. Built as a string and parsed into a `<div>` this
225
+ * module owns, never passed through `setContent` (which strips inputs and
226
+ * buttons). View state is bound with domma-reactive; the inputs themselves are
227
+ * read directly, because the editor, the address suggestions and the template
228
+ * picker all work on the live field.
807
229
  *
808
- * @returns {void}
230
+ * No `{{…}}` in the attachment row but the key: Domma's `data-each` compiler
231
+ * drops the whitespace beside an interpolation, so labels come from JS.
809
232
  */
810
- function openScheduler() {
811
- const modal = E.modal({title: 'Send later', size: 'sm'});
812
- const panel = document.createElement('div');
813
- panel.innerHTML = `
814
- <div class="flex flex-col gap-2">
815
- <div class="flex flex-wrap gap-1" data-ref="choices"></div>
816
- <label class="form-label">Or pick a time</label>
817
- <input type="datetime-local" class="form-input" data-ref="exact">
818
- <div class="flex justify-end gap-2 mt-2">
819
- <button type="button" class="btn btn-sm btn-ghost" data-ref="clear" hidden>Send normally instead</button>
820
- <button type="button" class="btn btn-sm btn-primary" data-ref="use">Use this time</button>
821
- </div>
822
- </div>`;
823
- const pick = (name) => panel.querySelector(`[data-ref="${name}"]`);
824
-
825
- /** @param {string|null} at */
826
- const choose = (at) => {
827
- scheduledAt.value = at;
828
- modal.close();
829
- };
233
+ const FORM = `
234
+ <div class="mail-compose-form">
235
+ <div class="form-group" data-bind-hidden="!hasFrom">
236
+ <label class="form-label">From
237
+ <span data-help-title="From" data-help="Which of this mailbox's identities sends the message. Changing it swaps the signature in the message for the new one's, where the old signature can still be found unchanged."></span>
238
+ </label>
239
+ <select class="form-select" data-ref="from"></select>
240
+ </div>
241
+ <div>
242
+ <label class="form-label">To
243
+ <span data-help-title="Recipients" data-help="Separate several addresses with commas. Name <address> works as well as a bare address. Start typing to pick from Contacts; a group puts all of its members in at once."></span>
244
+ </label>
245
+ <input type="text" class="form-input" data-ref="to" placeholder="someone@example.com">
246
+ <button type="button" class="btn btn-sm btn-ghost mail-extras-toggle" data-on-click="toggleExtras"
247
+ data-bind-text="extrasLabel.value" data-bind-aria-expanded="extrasAria.value"></button>
248
+ </div>
249
+ <div data-bind-hidden="!extrasOpen.value">
250
+ <label class="form-label">Cc</label>
251
+ <input type="text" class="form-input" data-ref="cc">
252
+ </div>
253
+ <div data-bind-hidden="!extrasOpen.value">
254
+ <label class="form-label">Bcc
255
+ <span data-help="Bcc recipients get the message, but nobody else sees that they did - not even the other Bcc recipients."></span>
256
+ </label>
257
+ <input type="text" class="form-input" data-ref="bcc">
258
+ </div>
259
+ <div data-bind-hidden="!extrasOpen.value">
260
+ <label class="form-label">Priority
261
+ <span data-help="Marks the message as urgent or unimportant in the recipient's mail client. Most show it as a flag or an icon; none sends it any faster."></span>
262
+ </label>
263
+ <select class="form-select" data-ref="priority">
264
+ <option value="normal">Normal</option>
265
+ <option value="high">High</option>
266
+ <option value="low">Low</option>
267
+ </select>
268
+ </div>
269
+ <div>
270
+ <label class="form-label">Subject</label>
271
+ <input type="text" class="form-input" data-ref="subject">
272
+ </div>
273
+ <div class="mail-compose-body">
274
+ <label class="form-label">Message</label>
275
+ <div class="flex items-center gap-2 mail-template-row" data-bind-hidden="!hasTemplates">
276
+ <select class="form-select form-select-sm mail-template-picker" data-ref="template">
277
+ <option value="">Insert a template…</option>
278
+ </select>
279
+ <span data-help-title="Templates" data-help="Canned text from Mail Settings. Choosing one adds it above what is already written, fills in the recipient's name and your own, and sets the subject if it is empty."></span>
280
+ </div>
281
+ <div class="mail-compose-editor" data-ref="editor"></div>
282
+ </div>
283
+ <div class="flex items-center gap-3 flex-wrap mail-compose-options">
284
+ <span class="flex items-center gap-1">
285
+ <label class="form-check">
286
+ <input type="checkbox" class="form-check-input" data-ref="receipt">
287
+ <span class="form-check-label">Read receipt</span>
288
+ </label>
289
+ <span data-help-title="Read receipts" data-help="Asks the recipient's mail program to say when the message is opened. A request, not a guarantee: many ignore it, or ask the recipient first - so no receipt does not mean the message is unread."></span>
290
+ </span>
291
+ <span class="flex items-center gap-1">
292
+ <label class="form-check">
293
+ <input type="checkbox" class="form-check-input" data-ref="delivery">
294
+ <span class="form-check-label">Delivery receipt</span>
295
+ </label>
296
+ <span data-help-title="Delivery receipts" data-help="Asks the mail servers on the way to report when the message reaches each recipient's mailbox (a delivery status notification). Arrives as an email from the server. Only servers that support it reply, so silence proves nothing either way."></span>
297
+ </span>
298
+ <span class="flex items-center gap-2" data-bind-hidden="!showSecurity">
299
+ <label class="form-check">
300
+ <input type="checkbox" class="form-check-input" data-ref="sign">
301
+ <span class="form-check-label">Sign</span>
302
+ </label>
303
+ <label class="form-check">
304
+ <input type="checkbox" class="form-check-input" data-ref="encrypt">
305
+ <span class="form-check-label">Encrypt</span>
306
+ </label>
307
+ <span data-help-title="Sign and encrypt (S/MIME)" data-help="Sign adds your certificate's digital signature, so recipients can see the message is from you and unchanged. Encrypt makes it readable only by the recipients (and you): it needs a certificate for every recipient, which you get when they send you a signed message or add in Settings > Security. Subjects are never encrypted."></span>
308
+ </span>
309
+ </div>
310
+ <div class="flex items-center gap-2 flex-wrap">
311
+ <button type="button" class="btn btn-sm btn-ghost" data-on-click="pickFiles">Attach files</button>
312
+ <span data-bind-class="attachTone.value" data-bind-text="attachSummary.value"></span>
313
+ <span data-help-title="Attachments" data-help="The running total is shown as you add files, and turns red over this mailbox's limit - a message that large cannot be sent. Right-click a file (or use its ⋮, or Shift+F10) to remove it."></span>
314
+ </div>
315
+ <input type="file" multiple hidden data-ref="files">
316
+ <div class="mail-attach-list" data-each="attachRows.value key=key"></div>
317
+ <div data-bind-class="statusClass.value" data-bind-text="statusText.value"></div>
318
+ <div class="flex justify-end items-center gap-2">
319
+ <button type="button" class="btn btn-sm btn-ghost" data-on-click="discard">Discard</button>
320
+ <button type="button" class="btn btn-sm btn-ghost" data-on-click="saveDraft" data-bind-disabled="saving.value">Save draft</button>
321
+ <button type="button" class="btn btn-sm btn-ghost" data-on-click="later" title="Send this at a time you choose">Later…</button>
322
+ <button type="button" class="btn btn-sm btn-primary" data-on-click="send"
323
+ data-bind-disabled="cannotSend.value" data-bind-text="sendLabel.value" data-bind-title="sendTitle.value"></button>
324
+ <span data-help-title="Sending" data-help="Ctrl+Enter (Cmd+Enter on a Mac) sends too, after asking first. Later… sends at a time you choose, and the button then says when. With an undo delay set in Mail Settings, Send holds the message for those seconds so you can take it back; it has not gone until they pass."></span>
325
+ </div>
326
+ </div>`;
327
+
328
+ /** One attachment. Only the key is interpolated; see FORM. */
329
+ const ATTACH_ROW = `
330
+ <div class="mail-box-row mail-attach-row" data-key="{{key}}" tabindex="0">
331
+ <span class="flex-1 text-sm mail-ellipsis" data-bind-text="label"></span>
332
+ <button type="button" class="btn btn-sm btn-ghost mail-attach-kebab" aria-label="Attachment actions" title="Actions">⋮</button>
333
+ </div>`;
334
+
335
+ function openComposeImpl({
336
+ draft: opened = {}, base, accountId, api, maxAttachmentBytes = 20_000_000,
337
+ onSent = () => {}, onSaved = () => {}, onQueued = () => {}, contacts = [],
338
+ identities = [], mailboxAddress = '', templates = [], undoSeconds = 0,
339
+ mode = 'new', defaults = null, security = null, prefs = {}, capabilities = {}
340
+ }) {
341
+ // How this message was started, decided once. A reopened draft is never
342
+ // treated as new: it already carries the signature it was written with,
343
+ // and adding another on reopen is how a draft edited four times goes out
344
+ // with four.
345
+ const openedAs = opened.savedUid ? 'edit' : mode;
346
+
347
+ /** Which identity is sending. Changeable while the window is open. */
348
+ let currentIdentity = findIdentity(identities, opened.identityId) ?? null;
349
+
350
+ // The one place all four ways of starting a message meet - new, reply,
351
+ // forward and reopened draft - so it is the one place the signature goes
352
+ // on. `applyIdentity` decides whether this mode gets one.
353
+ const draft = applyIdentity(opened, currentIdentity, openedAs);
354
+
355
+ const slideover = E.slideover({
356
+ title: draft.savedUid
357
+ ? 'Draft'
358
+ // From the mode, not the subject: a new message can arrive with
359
+ // a subject already in it (Contacts' "Send birthday wishes").
360
+ : (draft.inReplyTo ? 'Reply' : (openedAs === 'forward' ? 'Forward' : 'New message')),
361
+ size: 'lg',
362
+ position: 'right'
363
+ });
830
364
 
831
- for (const option of quickTimes()) {
832
- const button = document.createElement('button');
833
- button.type = 'button';
834
- button.className = 'btn btn-sm btn-ghost';
835
- button.textContent = option.label;
836
- button.title = fmtDateTime(option.at);
837
- button.addEventListener('click', () => choose(option.at));
838
- pick('choices').appendChild(button);
365
+ const host = document.createElement('div');
366
+ host.innerHTML = FORM;
367
+ const form = host.firstElementChild;
368
+ /** @param {string} name @returns {HTMLElement} */
369
+ const ref = (name) => form.querySelector(`[data-ref="${name}"]`);
370
+
371
+ const fromSelect = ref('from');
372
+ const toInput = ref('to');
373
+ const ccInput = ref('cc');
374
+ const bccInput = ref('bcc');
375
+ const prioritySelect = ref('priority');
376
+ const receiptInput = ref('receipt');
377
+ const deliveryInput = ref('delivery');
378
+ const signInput = ref('sign');
379
+ const encryptInput = ref('encrypt');
380
+ const subjectInput = ref('subject');
381
+ const picker = ref('template');
382
+ const editorHost = ref('editor');
383
+ const fileInput = ref('files');
384
+
385
+ // ---- View state ------------------------------------------------------
386
+
387
+ /** A time this message should go at, rather than now. */
388
+ const scheduledAt = M.observable(null);
389
+
390
+ // Cc, Bcc and priority are folded away until wanted. Most messages use
391
+ // none of them, and empty rows between the recipient and the subject are
392
+ // rows of nothing in the part of the window someone looks at first.
393
+ //
394
+ // Opened when the draft already carries any of them: a reply-all or a
395
+ // reopened draft with a hidden Cc would be a message quietly going
396
+ // somewhere the sender cannot see, and a reopened urgent draft with the
397
+ // picker folded away would look ordinary.
398
+ const extrasOpen = M.observable(Boolean(
399
+ draft.cc?.length || draft.bcc?.length || ['high', 'low'].includes(draft.priority)
400
+ ));
401
+ const extrasLabel = M.observable('');
402
+ // A string: a bound boolean becomes an empty attribute, and aria-expanded needs "true"/"false".
403
+ const extrasAria = M.observable('false');
404
+
405
+ // Attachments, seeded from the draft so reopening one keeps its files -
406
+ // normalised to the picker's shape on the way in. The server calls the
407
+ // length `size` and the picker calls it `bytes`, and seeding the server's
408
+ // shape verbatim renders "notes.txt (undefined)" with a NaN running total.
409
+ // Falling back to the base64 length is the honest measure anyway: that is
410
+ // what will actually be sent.
411
+ let nextKey = 0;
412
+ const attachments = M.observable((draft.attachments ?? []).map(file => ({
413
+ key: `a${nextKey++}`,
414
+ filename: file.filename,
415
+ contentType: file.contentType,
416
+ content: file.content,
417
+ bytes: file.bytes ?? file.size ?? Math.floor(String(file.content ?? '').length * 3 / 4)
418
+ })));
419
+ const attachRows = M.observable([]);
420
+ const attachSummary = M.observable('');
421
+ const attachTone = M.observable('text-xs text-muted');
422
+ const overLimit = M.observable(false);
423
+
424
+ const statusText = M.observable('');
425
+ const statusClass = M.observable('text-sm mail-status text-muted');
426
+ const saving = M.observable(false);
427
+ const sending = M.observable(false);
428
+ const cannotSend = M.observable(false);
429
+ const sendLabel = M.observable('Send');
430
+ const sendTitle = M.observable('');
431
+
432
+ const effects = [
433
+ M.effect(() => {
434
+ extrasLabel.value = extrasOpen.value ? 'Hide Cc and Bcc' : 'Cc / Bcc';
435
+ extrasAria.value = String(extrasOpen.value);
436
+ }),
437
+ // The total is shown as it grows rather than only on send, because
438
+ // being told a message is too large after writing it is a poor moment
439
+ // to find out - and red once it is over, which is the only reason the
440
+ // number is on screen at all.
441
+ M.effect(() => {
442
+ const list = attachments.value;
443
+ const total = list.reduce((n, a) => n + a.bytes, 0);
444
+ overLimit.value = total > maxAttachmentBytes;
445
+ attachSummary.value = list.length
446
+ ? `${list.length} file${list.length === 1 ? '' : 's'}, ${formatSize(total)} of ${formatSize(maxAttachmentBytes)}`
447
+ : '';
448
+ attachTone.value = overLimit.value ? 'text-xs text-danger' : 'text-xs text-muted';
449
+ attachRows.value = list.map(a => ({key: a.key, label: `${a.filename} (${formatSize(a.bytes)})`}));
450
+ }),
451
+ M.effect(() => {
452
+ cannotSend.value = sending.value || overLimit.value;
453
+ }),
454
+ // Three different things wear the Send button: send now, hold briefly
455
+ // so it can be taken back, and send at a chosen time. Calling all
456
+ // three "Send" is how someone finds out about the ten second hold by
457
+ // watching a message not arrive.
458
+ M.effect(() => {
459
+ const at = scheduledAt.value;
460
+ sendLabel.value = at ? `Send ${describeWhen(at)}` : 'Send';
461
+ sendTitle.value = at
462
+ ? fmtDateTime(at)
463
+ : (undoSeconds > 0 ? `Held for ${undoSeconds} seconds so you can take it back.` : '');
464
+ })
465
+ ];
466
+
467
+ /**
468
+ * Say something under the message, in the right colour. A class rather
469
+ * than `style.color`, so the colour follows the theme.
470
+ *
471
+ * @param {string} text
472
+ * @param {'ok'|'bad'|'quiet'} [tone]
473
+ * @returns {void}
474
+ */
475
+ function say(text, tone = 'quiet') {
476
+ statusText.value = text ?? '';
477
+ statusClass.value = 'text-sm mail-status '
478
+ + ({ok: 'text-success', bad: 'text-danger'}[tone] ?? 'text-muted');
839
479
  }
840
480
 
841
- const clear = pick('clear');
842
- clear.hidden = !scheduledAt.peek();
843
- clear.addEventListener('click', () => choose(null));
481
+ // ---- Fields ------------------------------------------------------------
482
+
483
+ toInput.value = addressesToText(draft.to);
484
+ ccInput.value = addressesToText(draft.cc);
485
+ bccInput.value = addressesToText(draft.bcc);
486
+ subjectInput.value = draft.subject ?? '';
487
+ prioritySelect.value = ['high', 'low'].includes(draft.priority) ? draft.priority : 'normal';
488
+
489
+ // The ticks. A reopened draft keeps what it was saved with; anything else
490
+ // starts from the mailbox's choices (Settings > Composing), unless the
491
+ // caller already said - a message handed back by Undo carries its own.
492
+ const tick = key => (openedAs === 'edit' ? draft[key] === true : (draft[key] ?? defaults?.[key]) === true);
493
+ receiptInput.checked = tick('readReceipt');
494
+ deliveryInput.checked = tick('deliveryReceipt');
495
+ // Signing and encrypting where this edition can (Email Pro) and the
496
+ // mailbox has a certificate. A message that ASKED for them (a reopened
497
+ // draft, Undo, the mailbox's default) keeps the tick even when they cannot
498
+ // be done now - an expired certificate, a profile that did not load - so
499
+ // the server refuses it with the reason rather than it quietly going out
500
+ // in the clear. Only an unticked box that cannot be used is greyed.
501
+ const wanted = {sign: tick('sign'), encrypt: tick('encrypt')};
502
+ const showSecurity = security?.available === true || wanted.sign || wanted.encrypt;
503
+ for (const [input, can, key] of [[signInput, security?.canSign, 'sign'], [encryptInput, security?.canEncrypt, 'encrypt']]) {
504
+ input.checked = wanted[key];
505
+ input.disabled = can !== true && !wanted[key];
506
+ if (can !== true && security?.reason) input.closest('label').title = security.reason;
507
+ // Once unticked, a box that cannot be used is greyed for good.
508
+ input.addEventListener('change', () => { if (!input.checked && can !== true) input.disabled = true; });
509
+ }
844
510
 
845
- const exact = pick('exact');
846
- pick('use').addEventListener('click', () => {
847
- if (!exact.value) return;
848
- // `datetime-local` has no zone, so it is read in the browser's -
849
- // which is the one the person picking it is in.
850
- choose(new Date(exact.value).toISOString());
851
- });
511
+ /**
512
+ * Does this identity have a signature that would have been added?
513
+ *
514
+ * @param {object|null} entry
515
+ * @returns {boolean}
516
+ */
517
+ function hasSignatureFor(entry) {
518
+ return Boolean(entry?.signatureHtml || entry?.signatureText);
519
+ }
852
520
 
853
- modal.element.appendChild(panel);
854
- modal.open();
855
- }
521
+ // The From picker, and only when there is a choice to make. One identity
522
+ // is not a choice, and a row saying so on every message is a row nobody
523
+ // reads.
524
+ const hasFrom = identities.length > 1;
525
+ if (hasFrom) {
526
+ for (const entry of identities) {
527
+ const option = document.createElement('option');
528
+ option.value = entry.id;
529
+ // The address as it will appear, not the label alone - the label
530
+ // is what the owner called it and the address is what the
531
+ // recipient will see, and those are the two different questions
532
+ // "which of these am I?" asks.
533
+ const shown = identityFrom(entry, mailboxAddress);
534
+ option.textContent = entry.label === shown ? shown : `${entry.label} - ${shown}`;
535
+ fromSelect.appendChild(option);
536
+ }
537
+ fromSelect.value = currentIdentity?.id ?? identities[0].id;
538
+
539
+ fromSelect.addEventListener('change', () => {
540
+ currentIdentity = findIdentity(identities, fromSelect.value);
541
+ // The signature in the body belongs to whoever was sending a
542
+ // moment ago. Swapped where it can be found and left alone where
543
+ // it cannot - see `swapSignature`.
544
+ if (editor) {
545
+ const {html, swapped} = swapSignature(editor.getValue(), currentIdentity, openedAs);
546
+ if (swapped) editor.setValue(html);
547
+ else if (hasSignatureFor(currentIdentity)) {
548
+ E.toast(
549
+ 'The sender changed, but the signature already in this message was left as it is.',
550
+ {type: 'info'}
551
+ );
552
+ }
553
+ }
554
+ });
555
+ }
856
556
 
857
- async function send() {
858
- const at = scheduledAt.peek();
859
- sending.value = true;
860
- // An automatic save may be writing a draft right now; sending before
861
- // it lands would leave that draft behind once the message has gone.
862
- if (savePromise) await savePromise.catch(() => {});
863
- say(at ? 'Scheduling…' : 'Sending…');
557
+ // Suggest recipients from the Contacts plugin, if this site has it. The
558
+ // address book is passed in rather than fetched here: the view already
559
+ // holds it for its own "add sender" action, and two windows open at once
560
+ // should not mean two requests for the same unchanging list.
561
+ const suggesters = [];
562
+ if (contacts.length && typeof E?.autocomplete === 'function') {
563
+ const groups = collectGroups(contacts);
564
+ for (const input of [toInput, ccInput, bccInput]) {
565
+ const suggester = attachSuggestions(input, contacts, groups);
566
+ if (suggester) suggesters.push(suggester);
567
+ }
568
+ }
864
569
 
865
- try {
866
- const params = new URLSearchParams({account: accountId});
867
- const result = await api(`${base}/send?${params}`, 'POST', {
868
- ...collect(),
869
- sendAt: at,
870
- // So a sent draft does not stay in Drafts. Saved again since
871
- // opening, this is the latest version's UID, not the original.
872
- replaces: savedUid
570
+ // Canned responses, and only when this mailbox has any. A picker offering
571
+ // nothing is a picker that has to explain itself.
572
+ const hasTemplates = templates.length > 0;
573
+ for (const template of templates) {
574
+ const option = document.createElement('option');
575
+ option.value = template.id;
576
+ option.textContent = template.name;
577
+ picker.appendChild(option);
578
+ }
579
+ picker.addEventListener('change', () => {
580
+ const chosen = templates.find(t => t.id === picker.value);
581
+ // Back to the placeholder straight away: the picker is an action, not
582
+ // a setting, and leaving the last-used one showing reads as "this
583
+ // message is that template".
584
+ picker.value = '';
585
+ if (!chosen) return;
586
+
587
+ const expanded = expandTemplate(chosen, {
588
+ to: textToAddresses(toInput.value),
589
+ subject: subjectInput.value,
590
+ identity: currentIdentity,
591
+ fromAddress: mailboxAddress
873
592
  });
874
593
 
875
- slideover.close(true);
594
+ const current = {
595
+ subject: subjectInput.value,
596
+ html: editor ? editor.getValue() : '',
597
+ body: editor ? editor.getText() : bodyInput.value
598
+ };
599
+ const next = applyTemplate(current, expanded);
876
600
 
877
- // Three outcomes, three different things to say. A message held
878
- // for ten seconds has NOT been sent, and saying it has is how
879
- // someone stops trusting the word.
880
- if (result.queued) {
881
- onQueued(result);
882
- } else {
883
- // Say where the copy went, or that it did not: a sent message
884
- // with no copy is worth knowing about before you look for it
885
- // later.
886
- E.toast(
887
- result.filedTo
888
- ? `Sent, and copied to ${result.filedTo}.`
889
- : 'Sent. No copy could be filed in Sent.',
890
- {type: result.filedTo ? 'success' : 'warning'}
891
- );
892
- if (result.messageAction && !result.messageAction.recorded) {
893
- E.toast('Sent, but the original message could not be marked as replied to or forwarded.', {type: 'warning'});
601
+ subjectInput.value = next.subject;
602
+ if (editor) editor.setValue(next.html);
603
+ else bodyInput.value = next.body;
604
+ });
605
+
606
+ // Domma's own editor, in rich mode. A plain textarea is kept as the
607
+ // fallback rather than assumed away: the editor is a component that may
608
+ // not be present in an older Domma, and a compose window that cannot type
609
+ // is worse than one without bold.
610
+ const bodyInput = document.createElement('textarea');
611
+ bodyInput.className = 'form-textarea mail-compose-textarea';
612
+ bodyInput.value = draft.body ?? '';
613
+
614
+ let editor = null;
615
+ let fontControls = null;
616
+ // Rich unless this browser chose plain text - but a draft written with
617
+ // formatting reopens with it, or saving it again would strip it.
618
+ const wantRich = prefs?.editor !== 'plain' || (openedAs === 'edit' && Boolean(draft.html));
619
+ if (wantRich && typeof E?.editor === 'function') {
620
+ try {
621
+ editor = E.editor(editorHost, {mode: 'rich', height: '34vh'});
622
+ editor.setValue(draft.html || textToHtml(draft.body ?? ''));
623
+ try { fontControls = installFontControls(editor, {attachSmoothCaret: mailHost.helpers.attachSmoothCaret}); } catch { fontControls = null; }
624
+ } catch {
625
+ editor = null;
626
+ }
627
+ }
628
+ if (!editor) editorHost.replaceWith(bodyInput);
629
+
630
+ // Spelling: the browser's own checker, on the fields that hold words.
631
+ // Never on addresses - every one would be underlined.
632
+ const spell = prefs?.spellcheck !== false;
633
+ for (const input of [toInput, ccInput, bccInput]) input.spellcheck = false;
634
+ for (const input of [subjectInput, bodyInput]) input.spellcheck = spell;
635
+ for (const el of editorHost.querySelectorAll('[contenteditable]')) el.spellcheck = spell;
636
+
637
+ // ---- Attachments -------------------------------------------------------
638
+
639
+ fileInput.addEventListener('change', async () => {
640
+ const chosen = [...fileInput.files];
641
+ fileInput.value = '';
642
+ const added = [];
643
+ for (const file of chosen) {
644
+ try {
645
+ added.push({
646
+ key: `a${nextKey++}`,
647
+ filename: file.name,
648
+ contentType: file.type || 'application/octet-stream',
649
+ content: await readAsBase64(file),
650
+ bytes: file.size
651
+ });
652
+ } catch (err) {
653
+ E.toast(err.message, {type: 'error'});
894
654
  }
895
- onSent(result);
896
655
  }
897
- } catch (err) {
898
- say(err.message, 'bad');
899
- sending.value = false;
656
+ if (added.length) attachments.value = [...attachments.peek(), ...added];
657
+ });
658
+
659
+ /** @param {string} key */
660
+ function removeAttachment(key) {
661
+ attachments.value = attachments.peek().filter(a => a.key !== key);
900
662
  }
901
- }
902
663
 
903
- // ---- Bind --------------------------------------------------------------
904
-
905
- // Rows and help markers before binding: data-each needs its row template
906
- // in place, and helpPopovers needs the markers where they will stay.
907
- form.querySelector('.mail-attach-list').innerHTML = ATTACH_ROW;
908
- const stopHelp = helpPopovers(form, {position: 'bottom'});
909
-
910
- const bindings = M.applyBindings({
911
- hasFrom, hasTemplates, showSecurity, extrasOpen, extrasLabel, extrasAria, attachRows, attachSummary, attachTone,
912
- statusText, statusClass, saving, cannotSend, sendLabel, sendTitle
913
- }, form, {
914
- methods: {
915
- toggleExtras: () => {
916
- extrasOpen.value = !extrasOpen.peek();
917
- if (extrasOpen.peek()) ccInput.focus();
918
- },
919
- pickFiles: () => fileInput.click(),
920
- // Discard, the X, Escape and the backdrop all go through
921
- // slideover.close, which asks (see the guard below).
922
- discard: () => { slideover.close(); },
923
- saveDraft: () => { saveDraft(); },
924
- later: () => openScheduler(),
925
- send: () => { send(); }
664
+ // ---- Draft and close guard ---------------------------------------------
665
+
666
+ // The UID of this draft's previous version, once it has been saved once,
667
+ // so a second save replaces rather than accumulates.
668
+ let savedUid = draft.savedUid ?? null;
669
+
670
+ /** What the message says now - compared with the last saved (or opened) state. */
671
+ function snapshot() {
672
+ const current = editor ? editor.getText() : bodyInput.value;
673
+ return JSON.stringify([subjectInput.value.trim(), current.trim(), toInput.value.trim(),
674
+ ccInput.value.trim(), bccInput.value.trim(), attachments.peek().length]);
926
675
  }
927
- });
928
-
929
- // Attachment actions: right-click, the ⋮, Shift+F10 or Delete on a row.
930
- const attachList = form.querySelector('.mail-attach-list');
931
- const attachMenu = typeof E?.contextMenu === 'function'
932
- ? E.contextMenu(attachList, {
933
- cursor: 'glyph', match: '.mail-attach-row', inherit: false, density: 'compact',
934
- items: (row) => [
935
- {label: 'Remove', icon: 'x', action: () => removeAttachment(row.dataset.key)},
936
- {type: 'divider'},
937
- {label: 'Remove all attachments', icon: 'trash', danger: true,
938
- action: () => { attachments.value = []; }}
939
- ]
940
- })
941
- : null;
942
- const onAttachClick = (e) => {
943
- const kebab = e.target.closest('.mail-attach-kebab');
944
- if (kebab) openMenuAt(kebab);
945
- };
946
- const onAttachKey = (e) => {
947
- const row = e.target.closest('.mail-attach-row');
948
- if (!row || e.target !== row) return;
949
- if (e.key === 'F10' && e.shiftKey) { e.preventDefault(); openMenuAt(row); }
950
- else if (e.key === 'Delete') { e.preventDefault(); removeAttachment(row.dataset.key); }
951
- };
952
- attachList.addEventListener('click', onAttachClick);
953
- attachList.addEventListener('keydown', onAttachKey);
954
-
955
- // Ctrl+Enter (Cmd+Enter): send, from anywhere in the window - the editor included - but only
956
- // after "Are you sure?", because the combination is easy to hit while typing.
957
- let askingSend = false;
958
- const onSendKey = async (e) => {
959
- if (!isSendShortcut(e)) return;
960
- e.preventDefault();
961
- e.stopPropagation();
962
- if (askingSend || closed || cannotSend.peek()) return;
963
- askingSend = true;
964
- try {
965
- const q = sendQuestion({...collect(), sendAt: scheduledAt.peek(), undoSeconds});
966
- // The subject and the recipients' names are typed text, and
967
- // E.confirm renders HTML - escaped, or `<b>` in a subject is bold.
968
- const ok = await E.confirm(esc(q.text), {title: esc(q.title), confirmText: q.confirmText, cancelText: 'Keep writing'});
969
- if (ok && !closed && !cannotSend.peek()) await send();
970
- } finally {
971
- askingSend = false;
676
+ let savedSnapshot = null; // set once the window is built (below)
677
+ // The last state written to Drafts by either kind of save, so the timer
678
+ // does not save the same text twice.
679
+ let persistedSnapshot = null;
680
+ let savedByHand = false;
681
+ /** A save in flight - Send waits for it, so `replaces` names the draft it wrote. */
682
+ let savePromise = null;
683
+ // Only automatic saves so far, of a message that was not a draft when it
684
+ // opened: discarding it then takes the automatic draft away too, as
685
+ // every mail program with autosave does.
686
+ let autoOnly = false;
687
+
688
+ /**
689
+ * Whether closing now would lose something.
690
+ *
691
+ * Compared with the last saved state, or what the window opened with - so
692
+ * a reopened draft closed unchanged does not ask, and a reply or forward,
693
+ * which opens with `Re:` / `Fwd:` and a quote already in it, does not
694
+ * count as unsaved work until the reader actually changes something.
695
+ */
696
+ function unsaved() {
697
+ if (savedSnapshot === null) return false;
698
+ const now = snapshot();
699
+ if (now === savedSnapshot) return false;
700
+ // Written by an automatic save into a draft that stays: nothing to lose.
701
+ return !(now === persistedSnapshot && !autoOnly);
972
702
  }
973
- };
974
- slideover.element.addEventListener('keydown', onSendKey, true);
975
-
976
- slideover.element.appendChild(form);
977
- const stopResizing = makeResizable(slideover, {
978
- storageKey: 'domma-mail.compose-width',
979
- defaultWidth: 700
980
- });
981
- slideover.open();
982
-
983
- // A reply already knows who it is going to; a new message does not.
984
- setTimeout(() => {
985
- if (draft.to?.length) {
986
- if (editor) editor.focus();
987
- else bodyInput.focus();
988
- } else {
989
- toInput.focus();
703
+
704
+ /** The question the close guard asks, for what would be lost. */
705
+ function discardQuestion() {
706
+ return savedUid
707
+ ? 'Close without saving? The changes since you last saved this draft will be lost.'
708
+ : 'Discard this message? It has not been saved as a draft.';
990
709
  }
991
- }, 60);
992
-
993
- // The baseline for "changed": what the window opened showing, read back out
994
- // of the thing showing it (taken once the editor has been seeded).
995
- //
996
- // NOT `draft.body`: the editor is seeded from `draft.html` and derives its
997
- // own text from that, so the two already differed on every HTML reply -
998
- // which is why discarding an untouched reply asked whether to lose
999
- // changes nobody had made. A signature makes that worse, since it means
1000
- // even a new message opens "changed". Comparing against what was actually
1001
- // put in front of the person is both the fix and the only baseline that
1002
- // stays true once anything else seeds the body.
1003
- setTimeout(() => {
1004
- if (savedSnapshot === null) savedSnapshot = snapshot();
1005
- if (persistedSnapshot === null) persistedSnapshot = savedSnapshot;
1006
- }, 0);
1007
-
1008
- // Saving as you go, when this browser asked for it (Settings).
1009
- const autosaveMs = Math.max(0, Number(prefs?.autosaveMinutes) || 0) * 60_000;
1010
- const autosaveTimer = autosaveMs ? setInterval(() => {
1011
- if (closed || saving.peek() || sending.peek() || persistedSnapshot === null) return;
1012
- if (snapshot() === persistedSnapshot) return;
1013
- saveDraft({auto: true});
1014
- }, autosaveMs) : null;
1015
-
1016
- /** Take an automatic-only draft away with the discarded message. Best effort. */
1017
- function dropAutoDraft() {
1018
- if (!autoOnly || !savedUid) return;
1019
- const params = new URLSearchParams({account: accountId});
1020
- api(`${base}/drafts/${encodeURIComponent(savedUid)}?${params}`, 'DELETE')
1021
- .then(() => onSaved({uid: null, removed: savedUid}))
1022
- .catch(() => { /* a leftover draft is untidy, not lost work */ });
1023
- }
1024
710
 
1025
- // Every way out asks when something would be lost - Discard, the X, Escape
1026
- // and the backdrop all call close(). Once closed it goes straight through:
1027
- // a later close() (the cleanup below, or the screen being left) must not ask again.
1028
- const rawClose = slideover.close.bind(slideover);
1029
- let closed = false;
1030
- let asking = false;
1031
- const closedListeners = [];
1032
- slideover.close = async (force) => {
1033
- if (!closed && force !== true && unsaved()) {
1034
- if (asking) return undefined;
1035
- asking = true;
1036
- // Two different losses, and saying the wrong one is worse than
1037
- // saying nothing: one has never been saved, the other has changes
1038
- // since it was.
1039
- const ok = await E.confirm(discardQuestion());
1040
- asking = false;
1041
- if (!ok) return undefined;
711
+ /**
712
+ * The message as it currently stands.
713
+ *
714
+ * @returns {object}
715
+ */
716
+ function collect() {
717
+ // Both parts, always: the HTML for clients that render it and the text
718
+ // for those that do not. Taking the text from the editor rather than
719
+ // stripping tags means it reads as prose rather than as markup with
720
+ // the angle brackets removed.
721
+ const html = editor ? editor.getValue() : null;
722
+ const text = editor ? editor.getText() : bodyInput.value;
723
+
724
+ return {
725
+ to: textToAddresses(toInput.value),
726
+ cc: textToAddresses(ccInput.value),
727
+ bcc: textToAddresses(bccInput.value),
728
+ priority: prioritySelect.value,
729
+ readReceipt: receiptInput.checked,
730
+ deliveryReceipt: deliveryInput.checked,
731
+ sign: signInput.checked,
732
+ encrypt: encryptInput.checked,
733
+ // Which of the mailbox's identities is sending. Null where there
734
+ // is only one, which is what the server reads as "the default".
735
+ identityId: currentIdentity?.id ?? null,
736
+ subject: subjectInput.value,
737
+ body: text,
738
+ html,
739
+ inReplyTo: draft.inReplyTo ?? null,
740
+ references: draft.references ?? [],
741
+ sourceMessage: draft.sourceMessage ?? null,
742
+ attachments: attachments.peek().map(({filename, contentType, content}) =>
743
+ ({filename, contentType, content}))
744
+ };
745
+ }
746
+
747
+ /**
748
+ * Save this message to the mailbox's Drafts folder - the button, and what
749
+ * leaving the screen does with a message that has changed.
750
+ *
751
+ * @returns {Promise<object|null>} the server's answer, or null if it failed
752
+ */
753
+ async function saveDraft({auto = false} = {}) {
754
+ // One save at a time, in order - a chain, so two waiting saves cannot
755
+ // start together with the same `replaces` and leave two drafts. Send
756
+ // waits on the tail, so it names the latest draft.
757
+ const run = (savePromise ?? Promise.resolve()).catch(() => {}).then(() => saveDraftNow({auto}));
758
+ savePromise = run;
759
+ try { return await run; } finally { if (savePromise === run) savePromise = null; }
760
+ }
761
+
762
+ async function saveDraftNow({auto = false} = {}) {
763
+ saving.value = true;
764
+ if (!auto) say('Saving…');
765
+ try {
766
+ const params = new URLSearchParams({account: accountId});
767
+ const taken = snapshot();
768
+ const result = await api(`${base}/drafts?${params}`, 'POST', {
769
+ ...collect(),
770
+ replaces: savedUid
771
+ });
772
+ savedUid = result.uid ?? savedUid;
773
+ persistedSnapshot = taken;
774
+ if (auto) {
775
+ // NOT the close question's baseline: an automatic save is a
776
+ // safety net, and closing still asks whether to keep it.
777
+ autoOnly = !savedByHand && !opened.savedUid;
778
+ say(`Draft saved automatically at ${fmtTime(new Date())}.`);
779
+ } else {
780
+ // Saved is the new baseline: closing now loses nothing.
781
+ savedSnapshot = taken;
782
+ savedByHand = true;
783
+ autoOnly = false;
784
+ say(`Saved to ${result.savedTo}.`, 'ok');
785
+ }
786
+ // The Drafts folder now holds a different set of UIDs, so a list
787
+ // showing it is out of date whether or not the window closes.
788
+ onSaved(result);
789
+ return result;
790
+ } catch (err) {
791
+ say(err.message, 'bad');
792
+ return null;
793
+ } finally {
794
+ saving.value = false;
795
+ }
796
+ }
797
+
798
+ // ---- Sending -----------------------------------------------------------
799
+
800
+ /**
801
+ * Choose a time to send at.
802
+ *
803
+ * The quick choices come from the same module the server validates
804
+ * against, so a time offered here cannot be refused there.
805
+ *
806
+ * @returns {void}
807
+ */
808
+ function openScheduler() {
809
+ const modal = E.modal({title: 'Send later', size: 'sm'});
810
+ const panel = document.createElement('div');
811
+ panel.innerHTML = `
812
+ <div class="flex flex-col gap-2">
813
+ <div class="flex flex-wrap gap-1" data-ref="choices"></div>
814
+ <label class="form-label">Or pick a time</label>
815
+ <input type="datetime-local" class="form-input" data-ref="exact">
816
+ <div class="flex justify-end gap-2 mt-2">
817
+ <button type="button" class="btn btn-sm btn-ghost" data-ref="clear" hidden>Send normally instead</button>
818
+ <button type="button" class="btn btn-sm btn-primary" data-ref="use">Use this time</button>
819
+ </div>
820
+ </div>`;
821
+ const pick = (name) => panel.querySelector(`[data-ref="${name}"]`);
822
+
823
+ /** @param {string|null} at */
824
+ const choose = (at) => {
825
+ scheduledAt.value = at;
826
+ modal.close();
827
+ };
828
+
829
+ for (const option of quickTimes()) {
830
+ const button = document.createElement('button');
831
+ button.type = 'button';
832
+ button.className = 'btn btn-sm btn-ghost';
833
+ button.textContent = option.label;
834
+ button.title = fmtDateTime(option.at);
835
+ button.addEventListener('click', () => choose(option.at));
836
+ pick('choices').appendChild(button);
837
+ }
838
+
839
+ const clear = pick('clear');
840
+ clear.hidden = !scheduledAt.peek();
841
+ clear.addEventListener('click', () => choose(null));
842
+
843
+ const exact = pick('exact');
844
+ pick('use').addEventListener('click', () => {
845
+ if (!exact.value) return;
846
+ // `datetime-local` has no zone, so it is read in the browser's -
847
+ // which is the one the person picking it is in.
848
+ choose(new Date(exact.value).toISOString());
849
+ });
850
+
851
+ modal.element.appendChild(panel);
852
+ modal.open();
853
+ }
854
+
855
+ async function send() {
856
+ const at = scheduledAt.peek();
857
+ sending.value = true;
858
+ // An automatic save may be writing a draft right now; sending before
859
+ // it lands would leave that draft behind once the message has gone.
860
+ if (savePromise) await savePromise.catch(() => {});
861
+ say(at ? 'Scheduling…' : 'Sending…');
862
+
863
+ try {
864
+ const params = new URLSearchParams({account: accountId});
865
+ const result = await api(`${base}/send?${params}`, 'POST', {
866
+ ...collect(),
867
+ sendAt: at,
868
+ // So a sent draft does not stay in Drafts. Saved again since
869
+ // opening, this is the latest version's UID, not the original.
870
+ replaces: savedUid
871
+ });
872
+
873
+ slideover.close(true);
874
+
875
+ // Three outcomes, three different things to say. A message held
876
+ // for ten seconds has NOT been sent, and saying it has is how
877
+ // someone stops trusting the word.
878
+ if (result.queued) {
879
+ onQueued(result);
880
+ } else {
881
+ // Say where the copy went, or that it did not: a sent message
882
+ // with no copy is worth knowing about before you look for it
883
+ // later.
884
+ E.toast(
885
+ result.filedTo
886
+ ? `Sent, and copied to ${result.filedTo}.`
887
+ : 'Sent. No copy could be filed in Sent.',
888
+ {type: result.filedTo ? 'success' : 'warning'}
889
+ );
890
+ if (result.messageAction && !result.messageAction.recorded) {
891
+ E.toast('Sent, but the original message could not be marked as replied to or forwarded.', {type: 'warning'});
892
+ }
893
+ onSent(result);
894
+ }
895
+ } catch (err) {
896
+ say(err.message, 'bad');
897
+ sending.value = false;
898
+ }
899
+ }
900
+
901
+ // ---- Bind --------------------------------------------------------------
902
+
903
+ // Rows and help markers before binding: data-each needs its row template
904
+ // in place, and helpPopovers needs the markers where they will stay.
905
+ form.querySelector('.mail-attach-list').innerHTML = ATTACH_ROW;
906
+ if (capabilities.scheduling === false) form.querySelector('[data-on-click="later"]')?.remove();
907
+ const stopHelp = helpPopovers(form, {position: 'bottom'});
908
+
909
+ const bindings = M.applyBindings({
910
+ hasFrom, hasTemplates, showSecurity, extrasOpen, extrasLabel, extrasAria, attachRows, attachSummary, attachTone,
911
+ statusText, statusClass, saving, cannotSend, sendLabel, sendTitle
912
+ }, form, {
913
+ methods: {
914
+ toggleExtras: () => {
915
+ extrasOpen.value = !extrasOpen.peek();
916
+ if (extrasOpen.peek()) ccInput.focus();
917
+ },
918
+ pickFiles: () => fileInput.click(),
919
+ // Discard, the X, Escape and the backdrop all go through
920
+ // slideover.close, which asks (see the guard below).
921
+ discard: () => { slideover.close(); },
922
+ saveDraft: () => { saveDraft(); },
923
+ later: () => openScheduler(),
924
+ send: () => { send(); }
925
+ }
926
+ });
927
+
928
+ // Attachment actions: right-click, the ⋮, Shift+F10 or Delete on a row.
929
+ const attachList = form.querySelector('.mail-attach-list');
930
+ const attachMenu = typeof E?.contextMenu === 'function'
931
+ ? E.contextMenu(attachList, {
932
+ cursor: 'glyph', match: '.mail-attach-row', inherit: false, density: 'compact',
933
+ items: (row) => [
934
+ {label: 'Remove', icon: 'x', action: () => removeAttachment(row.dataset.key)},
935
+ {type: 'divider'},
936
+ {label: 'Remove all attachments', icon: 'trash', danger: true,
937
+ action: () => { attachments.value = []; }}
938
+ ]
939
+ })
940
+ : null;
941
+ const onAttachClick = (e) => {
942
+ const kebab = e.target.closest('.mail-attach-kebab');
943
+ if (kebab) openMenuAt(kebab);
944
+ };
945
+ const onAttachKey = (e) => {
946
+ const row = e.target.closest('.mail-attach-row');
947
+ if (!row || e.target !== row) return;
948
+ if (e.key === 'F10' && e.shiftKey) { e.preventDefault(); openMenuAt(row); }
949
+ else if (e.key === 'Delete') { e.preventDefault(); removeAttachment(row.dataset.key); }
950
+ };
951
+ attachList.addEventListener('click', onAttachClick);
952
+ attachList.addEventListener('keydown', onAttachKey);
953
+
954
+ // Ctrl+Enter (Cmd+Enter): send, from anywhere in the window - the editor included - but only
955
+ // after "Are you sure?", because the combination is easy to hit while typing.
956
+ let askingSend = false;
957
+ const onSendKey = async (e) => {
958
+ if (!isSendShortcut(e)) return;
959
+ e.preventDefault();
960
+ e.stopPropagation();
961
+ if (askingSend || closed || cannotSend.peek()) return;
962
+ askingSend = true;
963
+ try {
964
+ const q = sendQuestion({...collect(), sendAt: scheduledAt.peek(), undoSeconds});
965
+ // The subject and the recipients' names are typed text, and
966
+ // E.confirm renders HTML - escaped, or `<b>` in a subject is bold.
967
+ const ok = await E.confirm(esc(q.text), {title: esc(q.title), confirmText: q.confirmText, cancelText: 'Keep writing'});
968
+ if (ok && !closed && !cannotSend.peek()) await send();
969
+ } finally {
970
+ askingSend = false;
971
+ }
972
+ };
973
+ slideover.element.addEventListener('keydown', onSendKey, true);
974
+
975
+ slideover.element.appendChild(form);
976
+ const stopResizing = makeResizable(slideover, {
977
+ storage: mailHost.storage,
978
+ storageKey: 'domma-mail.compose-width',
979
+ defaultWidth: 700
980
+ });
981
+ slideover.open();
982
+
983
+ // A reply already knows who it is going to; a new message does not.
984
+ setTimeout(() => {
985
+ if (draft.to?.length) {
986
+ if (editor) editor.focus();
987
+ else bodyInput.focus();
988
+ } else {
989
+ toInput.focus();
990
+ }
991
+ }, 60);
992
+
993
+ // The baseline for "changed": what the window opened showing, read back out
994
+ // of the thing showing it (taken once the editor has been seeded).
995
+ //
996
+ // NOT `draft.body`: the editor is seeded from `draft.html` and derives its
997
+ // own text from that, so the two already differed on every HTML reply -
998
+ // which is why discarding an untouched reply asked whether to lose
999
+ // changes nobody had made. A signature makes that worse, since it means
1000
+ // even a new message opens "changed". Comparing against what was actually
1001
+ // put in front of the person is both the fix and the only baseline that
1002
+ // stays true once anything else seeds the body.
1003
+ setTimeout(() => {
1004
+ if (savedSnapshot === null) savedSnapshot = snapshot();
1005
+ if (persistedSnapshot === null) persistedSnapshot = savedSnapshot;
1006
+ }, 0);
1007
+
1008
+ // Saving as you go, when this browser asked for it (Settings).
1009
+ const autosaveMs = Math.max(0, Number(prefs?.autosaveMinutes) || 0) * 60_000;
1010
+ const autosaveTimer = autosaveMs ? setInterval(() => {
1011
+ if (closed || saving.peek() || sending.peek() || persistedSnapshot === null) return;
1012
+ if (snapshot() === persistedSnapshot) return;
1013
+ saveDraft({auto: true});
1014
+ }, autosaveMs) : null;
1015
+
1016
+ /** Take an automatic-only draft away with the discarded message. Best effort. */
1017
+ function dropAutoDraft() {
1018
+ if (!autoOnly || !savedUid) return;
1019
+ const params = new URLSearchParams({account: accountId});
1020
+ api(`${base}/drafts/${encodeURIComponent(savedUid)}?${params}`, 'DELETE')
1021
+ .then(() => onSaved({uid: null, removed: savedUid}))
1022
+ .catch(() => { /* a leftover draft is untidy, not lost work */ });
1042
1023
  }
1043
- // Discarded (asked, or nothing worth asking about): an automatic-only
1044
- // draft goes with it. Not on a forced close - Send and leaving the
1045
- // screen have dealt with the draft themselves.
1046
- if (!closed && force !== true) dropAutoDraft();
1047
- if (closed) return undefined;
1048
- closed = true;
1049
- return rawClose();
1050
- };
1051
-
1052
- // The editor is a live component with its own listeners and autosave.
1053
- whenClosed(slideover, () => {
1054
- closed = true;
1055
- if (autosaveTimer) clearInterval(autosaveTimer);
1056
- // Before the editor: it closes an open menu (left on <body> by a
1057
- // Ctrl+Enter send) and drops its dropdowns and window listener.
1058
- fontControls?.destroy();
1059
- editor?.destroy?.();
1060
- stopResizing();
1061
- for (const suggester of suggesters) suggester.destroy?.();
1062
- bindings?.dispose?.();
1063
- effects.forEach(stop => { try { stop(); } catch { /* gone */ } });
1064
- attachMenu?.destroy?.();
1065
- attachList.removeEventListener('click', onAttachClick);
1066
- attachList.removeEventListener('keydown', onAttachKey);
1067
- slideover.element?.removeEventListener('keydown', onSendKey, true);
1068
- try { stopHelp?.(); } catch { /* gone */ }
1069
- closedListeners.splice(0).forEach(fn => { try { fn(); } catch { /* ignore */ } });
1070
- // Domma hides a closed slideover rather than removing it: every message
1071
- // written would otherwise leave its window behind in the page.
1072
- setTimeout(() => { try { slideover.element?.remove(); } catch { /* gone */ } }, 400);
1073
- });
1074
-
1075
- return {
1076
- /** Whether closing would lose something the reader wrote. */
1077
- dirty: () => !closed && unsaved(),
1078
- /** Save to Drafts now (what leaving the screen does with a changed message). */
1079
- saveDraft,
1080
- /** Close; `true` skips the question. */
1081
- close: (force) => slideover.close(force),
1082
- /** Called once, when the window has closed however it closed. */
1083
- onClosed: (fn) => { if (closed) fn(); else closedListeners.push(fn); }
1084
- };
1024
+
1025
+ // Every way out asks when something would be lost - Discard, the X, Escape
1026
+ // and the backdrop all call close(). Once closed it goes straight through:
1027
+ // a later close() (the cleanup below, or the screen being left) must not ask again.
1028
+ const rawClose = slideover.close.bind(slideover);
1029
+ let closed = false;
1030
+ let asking = false;
1031
+ const closedListeners = [];
1032
+ slideover.close = async (force) => {
1033
+ if (!closed && force !== true && unsaved()) {
1034
+ if (asking) return undefined;
1035
+ asking = true;
1036
+ // Two different losses, and saying the wrong one is worse than
1037
+ // saying nothing: one has never been saved, the other has changes
1038
+ // since it was.
1039
+ const ok = await E.confirm(discardQuestion());
1040
+ asking = false;
1041
+ if (!ok) return undefined;
1042
+ }
1043
+ // Discarded (asked, or nothing worth asking about): an automatic-only
1044
+ // draft goes with it. Not on a forced close - Send and leaving the
1045
+ // screen have dealt with the draft themselves.
1046
+ if (!closed && force !== true) dropAutoDraft();
1047
+ if (closed) return undefined;
1048
+ closed = true;
1049
+ return rawClose();
1050
+ };
1051
+
1052
+ // The editor is a live component with its own listeners and autosave.
1053
+ whenClosed(slideover, () => {
1054
+ closed = true;
1055
+ if (autosaveTimer) clearInterval(autosaveTimer);
1056
+ // Before the editor: it closes an open menu (left on <body> by a
1057
+ // Ctrl+Enter send) and drops its dropdowns and window listener.
1058
+ fontControls?.destroy();
1059
+ editor?.destroy?.();
1060
+ stopResizing();
1061
+ for (const suggester of suggesters) suggester.destroy?.();
1062
+ bindings?.dispose?.();
1063
+ effects.forEach(stop => { try { stop(); } catch { /* gone */ } });
1064
+ attachMenu?.destroy?.();
1065
+ attachList.removeEventListener('click', onAttachClick);
1066
+ attachList.removeEventListener('keydown', onAttachKey);
1067
+ slideover.element?.removeEventListener('keydown', onSendKey, true);
1068
+ try { stopHelp?.(); } catch { /* gone */ }
1069
+ closedListeners.splice(0).forEach(fn => { try { fn(); } catch { /* ignore */ } });
1070
+ // Domma hides a closed slideover rather than removing it: every message
1071
+ // written would otherwise leave its window behind in the page.
1072
+ setTimeout(() => { try { slideover.element?.remove(); } catch { /* gone */ } }, 400);
1073
+ });
1074
+
1075
+ return {
1076
+ /** Whether closing would lose something the reader wrote. */
1077
+ dirty: () => !closed && unsaved(),
1078
+ /** Save to Drafts now (what leaving the screen does with a changed message). */
1079
+ saveDraft,
1080
+ /** Close; `true` skips the question. */
1081
+ close: (force) => slideover.close(force),
1082
+ /** Called once, when the window has closed however it closed. */
1083
+ onClosed: (fn) => { if (closed) fn(); else closedListeners.push(fn); }
1084
+ };
1085
+ }
1086
+ return openComposeImpl;
1087
+ }
1088
+
1089
+ export function openCompose(options) {
1090
+ return createComposeWindow(options.host ?? createMailHost())(options);
1085
1091
  }