@postalsys/ee-client 1.11.2 → 2.0.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 (4) hide show
  1. package/README.md +66 -41
  2. package/index.d.ts +89 -16
  3. package/index.js +1684 -637
  4. package/package.json +8 -2
package/index.js CHANGED
@@ -35,6 +35,19 @@ const MESSAGE_BODY_STYLES = `
35
35
  overflow-x: auto;
36
36
  }
37
37
 
38
+ /* A plain-text message: EmailEngine renders it as HTML with a fixed 12px font, inline, so the
39
+ override needs the weight of !important; the message itself had no styling to lose */
40
+ .ee-message-body-content[data-plain] :is(div, p, span, pre) {
41
+ font-family: inherit !important;
42
+ font-size: inherit !important;
43
+ }
44
+
45
+ .ee-message-body-content > pre {
46
+ white-space: pre-wrap;
47
+ font-family: inherit;
48
+ margin: 0;
49
+ }
50
+
38
51
  /* Quoted thread history, folded away by EmailEngine - see _labelCollapsedThreads() */
39
52
  .ee-collapsed-thread {
40
53
  margin-top: 12px;
@@ -91,9 +104,304 @@ const ICON_PATHS = {
91
104
  paperclip: '<path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/>',
92
105
  close: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
93
106
  sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>',
94
- moon: '<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>'
107
+ moon: '<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>',
108
+ inbox: '<polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/>',
109
+ file: '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>',
110
+ junk: '<path d="M7.86 2h8.28L22 7.86v8.28L16.14 22H7.86L2 16.14V7.86L7.86 2z"/><path d="M12 8v4"/><path d="M12 16h.01"/>',
111
+ archive: '<rect width="20" height="5" x="2" y="3" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/>',
112
+ folder: '<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>',
113
+ star: '<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>',
114
+ minimize: '<path d="M5 12h14"/>',
115
+ expand: '<path d="M15 3h6v6"/><path d="M9 21H3v-6"/><path d="M21 3l-7 7"/><path d="M3 21l7-7"/>',
116
+ bold: '<path d="M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"/>',
117
+ italic: '<line x1="19" x2="10" y1="4" y2="4"/><line x1="14" x2="5" y1="20" y2="20"/><line x1="15" x2="9" y1="4" y2="20"/>',
118
+ list: '<path d="M3 12h.01"/><path d="M3 18h.01"/><path d="M3 6h.01"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M8 6h13"/>',
119
+ listOrdered:
120
+ '<path d="M10 12h11"/><path d="M10 18h11"/><path d="M10 6h11"/><path d="M4 10h2"/><path d="M4 6h1v4"/><path d="M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"/>',
121
+ link: '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>',
122
+ more: '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>'
123
+ };
124
+
125
+ // Escapes text for HTML element content and quoted attribute values
126
+ const HTML_ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
127
+ function escapeHtml(value) {
128
+ if (value === null || value === undefined) {
129
+ return '';
130
+ }
131
+ return String(value).replace(/[&<>"']/g, ch => HTML_ESCAPES[ch]);
132
+ }
133
+
134
+ // Folder icons by special-use flag; any other folder gets the plain folder icon
135
+ const FOLDER_ICONS = {
136
+ '\\Inbox': 'inbox',
137
+ '\\Drafts': 'file',
138
+ '\\Sent': 'send',
139
+ '\\Trash': 'trash',
140
+ '\\Junk': 'junk',
141
+ '\\Archive': 'archive',
142
+ '\\All': 'archive',
143
+ '\\Flagged': 'star'
95
144
  };
96
145
 
146
+ // The name a folder is shown by. Servers name the inbox "INBOX" (RFC 3501 makes the name special
147
+ // and case-insensitive), which reads as shouting next to "Drafts" and "Sent".
148
+ function folderDisplayName(folder) {
149
+ if (!folder) {
150
+ return '';
151
+ }
152
+ if (folder.specialUse === '\\Inbox' && /^inbox$/i.test(folder.name)) {
153
+ return 'Inbox';
154
+ }
155
+ return folder.name;
156
+ }
157
+
158
+ // What a reader counts as attachments: not the images that the HTML body shows in place
159
+ // (EmailEngine marks those embedded)
160
+ function listedAttachments(list) {
161
+ return (Array.isArray(list) ? list : []).filter(att => att && !att.embedded);
162
+ }
163
+
164
+ // An attachment's size in bytes. EmailEngine reports encodedSize, the length of the base64 the
165
+ // file travels in, which is four thirds of the file; size is used when a backend gives it.
166
+ function attachmentSize(att) {
167
+ if (att.size > 0) {
168
+ return att.size;
169
+ }
170
+ return att.encodedSize > 0 ? Math.floor((att.encodedSize * 3) / 4) : 0;
171
+ }
172
+
173
+ // A short type label for an attachment card: the extension, or the MIME subtype without one
174
+ function attachmentType(att) {
175
+ const match = /\.([a-z0-9]{1,5})$/i.exec(att.filename || '');
176
+ if (match) {
177
+ return match[1].toUpperCase();
178
+ }
179
+ const subtype = String(att.contentType || '').split('/')[1] || '';
180
+ return /^[a-z0-9]{1,5}$/i.test(subtype) ? subtype.toUpperCase() : 'FILE';
181
+ }
182
+
183
+ // An attachment of a stored message as a compose attachment that references it by id
184
+ function referenceAttachment(att) {
185
+ return { reference: att.id, filename: att.filename, contentType: att.contentType, size: attachmentSize(att) };
186
+ }
187
+
188
+ // One attachment of a submission or a draft upload: new content, or a reference to an
189
+ // attachment of a stored message. A reference carries the name and type along, which the
190
+ // server would otherwise replace with "attachment-1.*" and application/octet-stream.
191
+ function attachmentPayload(att) {
192
+ if (att.reference) {
193
+ const entry = { reference: att.reference };
194
+ if (att.filename) {
195
+ entry.filename = att.filename;
196
+ }
197
+ if (att.contentType) {
198
+ entry.contentType = att.contentType;
199
+ }
200
+ return entry;
201
+ }
202
+ return { filename: att.filename, contentType: att.contentType, content: att.content };
203
+ }
204
+
205
+ // sendMessage, saveDraft and updateDraft take one message object since 2.0. A 1.x call
206
+ // (to, subject, text, options) would otherwise send a message without its subject and text.
207
+ function assertMessageObject(message, method) {
208
+ if (!message || typeof message !== 'object' || Array.isArray(message)) {
209
+ throw new TypeError(
210
+ `${method}() takes a message object, e.g. ${method}({ to, subject, text }). The (to, subject, text, options) form was removed in ee-client 2.0.`
211
+ );
212
+ }
213
+ }
214
+
215
+ // The HTML the compose editor keeps: what its toolbar makes, plus the quote structure of a
216
+ // reopened draft. Anything else is unwrapped to its text (DROPPED_TAGS go with their content).
217
+ const ALLOWED_TAGS = new Set(['P', 'DIV', 'BR', 'B', 'STRONG', 'I', 'EM', 'U', 'UL', 'OL', 'LI', 'A', 'BLOCKQUOTE']);
218
+ const DROPPED_TAGS = new Set([
219
+ 'SCRIPT',
220
+ 'STYLE',
221
+ 'TEMPLATE',
222
+ 'IFRAME',
223
+ 'OBJECT',
224
+ 'EMBED',
225
+ 'HEAD',
226
+ 'TITLE',
227
+ 'META',
228
+ 'LINK',
229
+ 'NOSCRIPT',
230
+ 'TEXTAREA',
231
+ 'SELECT',
232
+ 'SVG',
233
+ 'MATH'
234
+ ]);
235
+ const SAFE_LINK = /^(?:https?:|mailto:)/i;
236
+
237
+ /**
238
+ * Filters HTML down to the editor's allowlist: the tags above, no attributes except an
239
+ * http(s) or mailto href on links. The input is parsed in an inert document (no scripts run, no
240
+ * images load) and the output built element by element, so nothing of the input's markup is
241
+ * copied over as text.
242
+ *
243
+ * @param {string} html - untrusted HTML (pasted content, a stored draft)
244
+ * @returns {string} safe HTML for the editor
245
+ */
246
+ function sanitizeEditorHtml(html) {
247
+ const source = new DOMParser().parseFromString(`<!doctype html><body>${String(html || '')}`, 'text/html');
248
+ const target = document.implementation.createHTMLDocument('');
249
+ const copy = (from, to) => {
250
+ for (const node of from.childNodes) {
251
+ if (node.nodeType === 3) {
252
+ to.appendChild(target.createTextNode(node.nodeValue));
253
+ continue;
254
+ }
255
+ if (node.nodeType !== 1 || DROPPED_TAGS.has(node.tagName.toUpperCase())) {
256
+ continue;
257
+ }
258
+ const tag = node.tagName.toUpperCase();
259
+ if (!ALLOWED_TAGS.has(tag)) {
260
+ copy(node, to);
261
+ continue;
262
+ }
263
+ const el = target.createElement(tag.toLowerCase());
264
+ if (tag === 'A') {
265
+ const href = (node.getAttribute('href') || '').trim();
266
+ if (SAFE_LINK.test(href)) {
267
+ el.setAttribute('href', href);
268
+ }
269
+ }
270
+ copy(node, el);
271
+ to.appendChild(el);
272
+ }
273
+ };
274
+ copy(source.body, target.body);
275
+ return target.body.innerHTML;
276
+ }
277
+
278
+ const BLOCK_TAGS = new Set(['P', 'DIV', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'TABLE', 'TR', 'PRE']);
279
+
280
+ // The text of a node's children: blocks on lines of their own, a blank line after a paragraph
281
+ function blockText(node) {
282
+ let out = '';
283
+ const lineBreak = () => {
284
+ if (out && !out.endsWith('\n')) {
285
+ out += '\n';
286
+ }
287
+ };
288
+ for (const child of node.childNodes) {
289
+ if (child.nodeType === 3) {
290
+ out += child.nodeValue.replace(/\s+/g, ' ');
291
+ continue;
292
+ }
293
+ if (child.nodeType !== 1) {
294
+ continue;
295
+ }
296
+ const tag = child.tagName.toUpperCase();
297
+ if (tag === 'BR') {
298
+ out += '\n';
299
+ } else if (tag === 'BLOCKQUOTE') {
300
+ lineBreak();
301
+ out += `${trimLines(blockText(child))
302
+ .split('\n')
303
+ .map(line => `> ${line}`.trimEnd())
304
+ .join('\n')}\n`;
305
+ } else if (tag === 'UL' || tag === 'OL') {
306
+ lineBreak();
307
+ out += listText(child, tag === 'OL');
308
+ } else if (BLOCK_TAGS.has(tag)) {
309
+ lineBreak();
310
+ out += blockText(child);
311
+ lineBreak();
312
+ if (tag === 'P') {
313
+ out += '\n';
314
+ }
315
+ } else if (tag === 'A') {
316
+ const label = blockText(child);
317
+ const href = (child.getAttribute('href') || '').replace(/^mailto:/i, '');
318
+ out += href && href !== label.trim() ? `${label} (${href})` : label;
319
+ } else {
320
+ out += blockText(child);
321
+ }
322
+ }
323
+ return out;
324
+ }
325
+
326
+ // A list as "- item" or "1. item" lines; a nested list is indented under its item
327
+ function listText(list, ordered) {
328
+ let out = '';
329
+ let index = 0;
330
+ for (const item of list.children) {
331
+ const marker = item.tagName.toUpperCase() === 'LI' ? (ordered ? `${++index}. ` : '- ') : '';
332
+ const lines = trimLines(blockText(item)).split('\n');
333
+ out += `${marker}${lines[0]}\n${lines
334
+ .slice(1)
335
+ .map(line => ` ${line}\n`)
336
+ .join('')}`;
337
+ }
338
+ return out;
339
+ }
340
+
341
+ function trimLines(text) {
342
+ return text
343
+ .split('\n')
344
+ .map(line => line.trim())
345
+ .join('\n')
346
+ .replace(/\n{3,}/g, '\n\n')
347
+ .trim();
348
+ }
349
+
350
+ /**
351
+ * The plain-text alternative of the editor's HTML: blocks on lines of their own, list items
352
+ * marked "- " or "1. ", quotes prefixed "> " and links followed by their address.
353
+ *
354
+ * @param {Node} root
355
+ * @returns {string}
356
+ */
357
+ function editorText(root) {
358
+ return trimLines(blockText(root));
359
+ }
360
+
361
+ // Puts the caret at the start of an editable element
362
+ function placeCaretAtStart(el) {
363
+ const selection = window.getSelection();
364
+ if (!selection) {
365
+ return;
366
+ }
367
+ const range = document.createRange();
368
+ range.setStart(el, 0);
369
+ range.collapse(true);
370
+ selection.removeAllRanges();
371
+ selection.addRange(range);
372
+ }
373
+
374
+ // The threading headers of a stored draft, carried over when it is saved again or sent from the
375
+ // compose form, so the reply it holds stays in its thread
376
+ function threadingHeaders(msg) {
377
+ const headers = (msg && msg.headers) || {};
378
+ const first = value =>
379
+ String((Array.isArray(value) ? value[0] : value) || '')
380
+ .replace(/\s+/g, ' ')
381
+ .trim();
382
+ const result = {};
383
+ const inReplyTo = first(headers['in-reply-to']) || first(msg && msg.inReplyTo);
384
+ const references = first(headers.references);
385
+ if (inReplyTo) {
386
+ result['In-Reply-To'] = inReplyTo;
387
+ }
388
+ if (references) {
389
+ result.References = references;
390
+ }
391
+ return result;
392
+ }
393
+
394
+ // Plain text as editor HTML: escaped, one paragraph per blank-line separated block
395
+ function textToEditorHtml(text) {
396
+ if (!text) {
397
+ return '';
398
+ }
399
+ return String(text)
400
+ .split(/\n{2,}/)
401
+ .map(block => `<p>${escapeHtml(block).replace(/\n/g, '<br>')}</p>`)
402
+ .join('');
403
+ }
404
+
97
405
  // Default cap on the files attached in the compose form, in bytes. They travel base64 encoded
98
406
  // inside one JSON request, which grows them by a third, and most providers refuse a message
99
407
  // much larger than this anyway. Hosts that know their limit pass maxAttachmentSize.
@@ -167,10 +475,11 @@ function addressEntries(value) {
167
475
 
168
476
  // Compose form titles, by mode
169
477
  const COMPOSE_TITLES = {
170
- new: 'New Message',
478
+ new: 'New message',
171
479
  reply: 'Reply',
172
- 'reply-all': 'Reply All',
173
- forward: 'Forward'
480
+ 'reply-all': 'Reply all',
481
+ forward: 'Forward',
482
+ draft: 'Draft'
174
483
  };
175
484
 
176
485
  // Below this container width the UI shows one pane at a time and the compose button
@@ -209,13 +518,20 @@ export class EmailEngineClient {
209
518
  this.initialMessage = typeof options.message === 'string' && options.message ? options.message : null;
210
519
  // Told whenever the open folder or message changes, so a host page can keep its address
211
520
  // bar in step (see _notifyNavigate)
212
- this.onNavigate = typeof options.onNavigate === 'function' ? options.onNavigate : null;
521
+ // Host callbacks (see _emit): navigation, so the host can keep its address bar in step, and
522
+ // the outcomes it may want to track - a message queued for delivery, a draft stored, and a
523
+ // request that failed, with what the client was doing at the time
524
+ for (const name of ['onNavigate', 'onMessageSent', 'onDraftSaved', 'onError']) {
525
+ this[name] = typeof options[name] === 'function' ? options[name] : null;
526
+ }
213
527
  const maxAttachmentSize = Number(options.maxAttachmentSize);
214
528
  this.maxAttachmentSize = maxAttachmentSize > 0 ? maxAttachmentSize : DEFAULT_MAX_ATTACHMENT_SIZE;
215
529
  this.folders = [];
216
530
  this.messages = [];
217
531
  this.nextPageCursor = null;
218
532
  this.prevPageCursor = null;
533
+ // Position of the listed page: { page (0-based), total } when the server reports them
534
+ this.listPosition = null;
219
535
 
220
536
  // Set once destroy() runs; guards async completions (loadFolders,
221
537
  // loadMessages, loadMessage) from re-rendering or scrolling into a
@@ -248,9 +564,9 @@ export class EmailEngineClient {
248
564
  const requestedPageSize = savedPageSize ? parseInt(savedPageSize, 10) : parseInt(options.pageSize, 10);
249
565
  this.pageSize = requestedPageSize > 0 ? requestedPageSize : 20;
250
566
 
251
- if (this.container) {
252
- this.init();
253
- }
567
+ // Resolves once the first view has loaded: true when it did, false when its requests failed
568
+ // (the panes then show why). An API-only client has nothing to load.
569
+ this.ready = this.container ? this.init() : Promise.resolve(true);
254
570
 
255
571
  // Start keep-alive timer for sess_ tokens
256
572
  this._startKeepAliveTimer();
@@ -346,21 +662,30 @@ export class EmailEngineClient {
346
662
  return `${this._accountPath()}/attachment/${encodeURIComponent(attachmentId)}`;
347
663
  }
348
664
 
349
- async loadFolders() {
665
+ // Stores the folder list without rendering or reporting anything
666
+ async _fetchFolders(counters = false) {
667
+ const data = await this.apiRequest('GET', `${this._accountPath()}/mailboxes${counters ? '?counters=true' : ''}`);
668
+ this.folders = data.mailboxes || [];
669
+ this._folderTreeCache = null;
670
+ return this.folders;
671
+ }
672
+
673
+ // counters adds each folder's message and unread counts, at the cost of a STATUS command per
674
+ // folder on IMAP. The UI shows them, so it asks by default; an API-only client asks when told to.
675
+ async loadFolders({ counters = !!this.container } = {}) {
350
676
  // Reset the pane to its loading state so a retry after a failure does not
351
677
  // keep showing the previous error while the new request is in flight.
352
678
  this._setPaneHtml('.ee-folder-tree', '<div class="ee-loading">Loading folders...</div>');
353
679
 
354
680
  try {
355
- const data = await this.apiRequest('GET', `${this._accountPath()}/mailboxes`);
356
- this.folders = data.mailboxes || [];
357
- this._folderTreeCache = null;
681
+ await this._fetchFolders(counters);
358
682
  if (this.container) {
359
683
  this.renderFolderList();
360
684
  }
361
685
  return this.folders;
362
686
  } catch (error) {
363
687
  console.error('Failed to load folders:', error);
688
+ this._reportError(error, 'loadFolders', 'Failed to load the folders');
364
689
  this._renderPaneError('.ee-folder-tree', 'Folders unavailable', error, () => this._loadInitialView());
365
690
  throw error;
366
691
  }
@@ -382,6 +707,7 @@ export class EmailEngineClient {
382
707
  this.currentFolder = path;
383
708
  this.nextPageCursor = data.nextPageCursor || null;
384
709
  this.prevPageCursor = data.prevPageCursor || null;
710
+ this.listPosition = Number.isInteger(data.page) && Number.isInteger(data.total) ? { page: data.page, total: data.total } : null;
385
711
 
386
712
  if (this.container) {
387
713
  this.renderMessageList();
@@ -397,6 +723,7 @@ export class EmailEngineClient {
397
723
  };
398
724
  } catch (error) {
399
725
  console.error('Failed to load messages:', error);
726
+ this._reportError(error, 'loadMessages', 'Failed to load the messages');
400
727
  this._renderPaneError(
401
728
  '.ee-message-list',
402
729
  'Messages unavailable',
@@ -433,6 +760,9 @@ export class EmailEngineClient {
433
760
 
434
761
  const msg = this.messages.find(m => m.id === messageId);
435
762
  if (msg) {
763
+ if (msg.unseen) {
764
+ this._adjustUnseen(this.currentFolder, -1);
765
+ }
436
766
  msg.unseen = false;
437
767
  if (this.container) {
438
768
  this.renderMessageList();
@@ -454,6 +784,7 @@ export class EmailEngineClient {
454
784
  return this.currentMessage;
455
785
  } catch (error) {
456
786
  console.error('Failed to load message:', error);
787
+ this._reportError(error, 'loadMessage', 'Failed to load the message');
457
788
  // A message that does not exist (deleted, moved, or a link with a mangled ID) is
458
789
  // not worth retrying, and the API's validation text means nothing to a reader
459
790
  if (error && (error.statusCode === 404 || error.statusCode === 400)) {
@@ -485,6 +816,9 @@ export class EmailEngineClient {
485
816
 
486
817
  const msg = this.messages.find(m => m.id === messageId);
487
818
  if (msg) {
819
+ if (msg.unseen === seen) {
820
+ this._adjustUnseen(this.currentFolder, seen ? -1 : 1);
821
+ }
488
822
  msg.unseen = !seen;
489
823
  if (this.container) {
490
824
  this.renderMessageList();
@@ -501,13 +835,21 @@ export class EmailEngineClient {
501
835
  return true;
502
836
  } catch (error) {
503
837
  console.error('Failed to update message flags:', error);
838
+ this._reportError(error, 'markAsRead', 'Failed to update the message flags');
504
839
  throw error;
505
840
  }
506
841
  }
507
842
 
508
843
  // Takes a message that left the folder (deleted or moved) off the list, and out of the
509
844
  // viewer when it was the open one
510
- _dropMessage(messageId) {
845
+ _dropMessage(messageId, targetPath = null) {
846
+ const dropped = this.messages.find(m => m.id === messageId);
847
+ if (dropped && dropped.unseen) {
848
+ this._adjustUnseen(this.currentFolder, -1);
849
+ if (targetPath) {
850
+ this._adjustUnseen(targetPath, 1);
851
+ }
852
+ }
511
853
  this.messages = this.messages.filter(m => m.id !== messageId);
512
854
  if (this.container) {
513
855
  this.renderMessageList();
@@ -533,6 +875,7 @@ export class EmailEngineClient {
533
875
  return response || { deleted: true };
534
876
  } catch (error) {
535
877
  console.error('Failed to delete message:', error);
878
+ this._reportError(error, 'delete', 'Failed to delete the message');
536
879
  throw error;
537
880
  }
538
881
  }
@@ -543,11 +886,12 @@ export class EmailEngineClient {
543
886
  path: targetPath
544
887
  });
545
888
 
546
- this._dropMessage(messageId);
889
+ this._dropMessage(messageId, targetPath);
547
890
 
548
891
  return true;
549
892
  } catch (error) {
550
893
  console.error('Failed to move message:', error);
894
+ this._reportError(error, 'move', 'Failed to move the message');
551
895
  throw error;
552
896
  }
553
897
  }
@@ -561,10 +905,20 @@ export class EmailEngineClient {
561
905
  return this._accountInfo;
562
906
  }
563
907
 
564
- // The address and content fields shared by a submission and a draft upload. Empty recipient
565
- // lists are left out rather than sent as [].
566
- _messagePayload(to, subject, text, { cc, bcc, attachments, reference } = {}) {
567
- const data = { subject, text };
908
+ // The address and content fields shared by a submission and a draft upload, from a message
909
+ // object (see sendMessage). Empty recipient lists and empty parts are left out.
910
+ _messagePayload(message) {
911
+ const { to, cc, bcc, subject, text, html, attachments, reference, headers } = message;
912
+ const data = {};
913
+ if (typeof subject === 'string') {
914
+ data.subject = subject;
915
+ }
916
+ if (typeof text === 'string') {
917
+ data.text = text;
918
+ }
919
+ if (typeof html === 'string' && html) {
920
+ data.html = html;
921
+ }
568
922
  for (const [key, value] of [
569
923
  ['to', to],
570
924
  ['cc', cc],
@@ -576,33 +930,59 @@ export class EmailEngineClient {
576
930
  }
577
931
  }
578
932
  if (Array.isArray(attachments) && attachments.length) {
579
- data.attachments = attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content }));
933
+ data.attachments = attachments.map(attachmentPayload);
580
934
  }
581
935
  if (reference) {
582
936
  data.reference = reference;
583
937
  }
938
+ if (headers && typeof headers === 'object' && Object.keys(headers).length) {
939
+ data.headers = headers;
940
+ }
584
941
  return data;
585
942
  }
586
943
 
587
- // options: { cc, bcc, attachments: [{ filename, contentType, content (base64) }], reference }.
588
- // reference is EmailEngine's submit reference block ({ message, action, inline,
589
- // forwardAttachments }); with it the server adds the threading headers and the quote.
590
- async sendMessage(to, subject, text, options = {}) {
944
+ /**
945
+ * Submits a message for delivery.
946
+ *
947
+ * @param {Object} message
948
+ * @param {string|Object|Object[]} message.to - "Name <address>", { name, address } or a list
949
+ * @param {string|Object|Object[]} [message.cc]
950
+ * @param {string|Object|Object[]} [message.bcc]
951
+ * @param {string} [message.subject]
952
+ * @param {string} [message.text] - the plain text part
953
+ * @param {string} [message.html] - the HTML part
954
+ * @param {Object[]} [message.attachments] - { filename, contentType, content (base64) }, or
955
+ * { reference, filename, contentType } for an attachment of a stored message by its id
956
+ * @param {Object} [message.reference] - EmailEngine's reference block ({ message, action,
957
+ * inline, forwardAttachments }); the server adds the threading headers and the quote
958
+ * @param {Object} [message.headers] - extra headers, e.g. In-Reply-To of a reopened draft
959
+ * @returns {Promise<Object>} the queue response ({ messageId, queueId, ... })
960
+ */
961
+ async sendMessage(message) {
962
+ assertMessageObject(message, 'sendMessage');
591
963
  try {
592
- const messageData = this._messagePayload(to, subject, text, options);
593
-
594
- const response = await this.apiRequest('POST', `${this._accountPath()}/submit`, messageData);
964
+ const response = await this.apiRequest('POST', `${this._accountPath()}/submit`, this._messagePayload(message));
965
+ this._emit('onMessageSent', response);
595
966
  return response;
596
967
  } catch (error) {
597
968
  console.error('Failed to send message:', error);
969
+ this._reportError(error, 'send', 'Failed to send the message');
598
970
  throw error;
599
971
  }
600
972
  }
601
973
 
602
- async saveDraft(to, subject, text, options = {}) {
974
+ /**
975
+ * Stores a message in the Drafts folder. Takes the same message object as sendMessage.
976
+ *
977
+ * @param {Object} message
978
+ * @returns {Promise<Object>} the upload response ({ id, path, uid, ... })
979
+ */
980
+ async saveDraft(message) {
981
+ assertMessageObject(message, 'saveDraft');
603
982
  try {
604
983
  if (!this.folders.length) {
605
- await this.loadFolders();
984
+ // only the Drafts path is needed; a failure is this save's own
985
+ await this._fetchFolders();
606
986
  }
607
987
  const draftsFolder = this.folders.find(f => f.specialUse === '\\Drafts');
608
988
  if (!draftsFolder) {
@@ -612,7 +992,7 @@ export class EmailEngineClient {
612
992
  const messageData = {
613
993
  path: draftsFolder.path,
614
994
  flags: ['\\Draft'],
615
- ...this._messagePayload(to, subject, text, options)
995
+ ...this._messagePayload(message)
616
996
  };
617
997
 
618
998
  // The upload endpoint does not add a From header on its own, but the draft
@@ -627,13 +1007,41 @@ export class EmailEngineClient {
627
1007
  }
628
1008
 
629
1009
  const response = await this.apiRequest('POST', `${this._accountPath()}/message`, messageData);
1010
+ this._emit('onDraftSaved', response);
630
1011
  return response;
631
1012
  } catch (error) {
632
1013
  console.error('Failed to save draft:', error);
1014
+ this._reportError(error, 'saveDraft', 'Failed to save the draft');
633
1015
  throw error;
634
1016
  }
635
1017
  }
636
1018
 
1019
+ /**
1020
+ * Replaces a stored draft with a new version. IMAP has no way to change a stored message, so
1021
+ * the new version is saved first and the old one removed after; attachments the new version
1022
+ * references from the old draft are copied before it goes.
1023
+ *
1024
+ * @param {string} messageId - the draft to replace
1025
+ * @param {Object} message - the new version, as for sendMessage
1026
+ * @returns {Promise<Object>} the upload response of the new version
1027
+ */
1028
+ async updateDraft(messageId, message) {
1029
+ assertMessageObject(message, 'updateDraft');
1030
+ const saved = await this.saveDraft(message);
1031
+ await this._discardDraft(messageId);
1032
+ return saved;
1033
+ }
1034
+
1035
+ // Removes a draft for good (not to Trash: it is a superseded or sent copy). A failure is
1036
+ // logged only; the newer version is already safe.
1037
+ async _discardDraft(messageId) {
1038
+ try {
1039
+ await this.apiRequest('DELETE', this._messagePath(messageId, '?force=true'));
1040
+ } catch (error) {
1041
+ console.error('Failed to remove the previous draft:', error);
1042
+ }
1043
+ }
1044
+
637
1045
  // Parses a typed address field ("Name <a@example.com>, b@example.com") into address entries
638
1046
  parseAddressList(value) {
639
1047
  return splitAddressField(String(value || '')).map(parseAddressEntry);
@@ -661,7 +1069,16 @@ export class EmailEngineClient {
661
1069
  // leaves alone, and what the form shows is what is sent.
662
1070
  prepareResponse(msg, action, ownAddress = null) {
663
1071
  if (action === 'forward') {
664
- return { to: [], cc: [], subject: prefixSubject(msg.subject, 'Fwd'), reference: { message: msg.id, action: 'forward', inline: true } };
1072
+ // The original's files travel as references, one per file, so each can be left out;
1073
+ // forwardAttachments would carry all of them or none
1074
+ const attachments = listedAttachments(msg.attachments).map(referenceAttachment);
1075
+ return {
1076
+ to: [],
1077
+ cc: [],
1078
+ subject: prefixSubject(msg.subject, 'Fwd'),
1079
+ reference: { message: msg.id, action: 'forward', inline: true, forwardAttachments: false },
1080
+ attachments
1081
+ };
665
1082
  }
666
1083
 
667
1084
  const own = typeof ownAddress === 'string' ? ownAddress.toLowerCase() : '';
@@ -698,24 +1115,39 @@ export class EmailEngineClient {
698
1115
  return { to, cc, subject: prefixSubject(msg.subject, 'Re'), reference: { message: msg.id, action: 'reply', inline: true } };
699
1116
  }
700
1117
 
701
- // Tells the host which folder and message are open. A host error must not break the client.
702
- _notifyNavigate() {
703
- if (!this.onNavigate || this._destroyed) {
1118
+ // Calls a host callback by its option name. A host error must not break the client.
1119
+ _emit(name, ...args) {
1120
+ const handler = this[name];
1121
+ if (typeof handler !== 'function' || this._destroyed) {
704
1122
  return;
705
1123
  }
706
1124
  try {
707
- this.onNavigate({ path: this.currentFolder, messageId: this.currentMessage ? this.currentMessage.id : null });
1125
+ handler(...args);
708
1126
  } catch (error) {
709
- console.error('onNavigate handler failed:', error);
1127
+ console.error(`${name} handler failed:`, error);
710
1128
  }
711
1129
  }
712
1130
 
1131
+ // Tells the host which folder and message are open
1132
+ _notifyNavigate() {
1133
+ this._emit('onNavigate', { path: this.currentFolder, messageId: this.currentMessage ? this.currentMessage.id : null });
1134
+ }
1135
+
1136
+ // Tells the host a request failed: action names what the client was doing ('loadFolders',
1137
+ // 'loadMessages', 'loadMessage', 'markAsRead', 'delete', 'move', 'send', 'saveDraft' or
1138
+ // 'download'), and description says it in words
1139
+ _reportError(error, action, description) {
1140
+ this._emit('onError', error, { action, description });
1141
+ }
1142
+
713
1143
  async submitDraft(messageId, options = null) {
714
1144
  try {
715
1145
  const response = await this.apiRequest('POST', this._messagePath(messageId, '/submit'), options);
1146
+ this._emit('onMessageSent', response);
716
1147
  return response;
717
1148
  } catch (error) {
718
1149
  console.error('Failed to submit draft:', error);
1150
+ this._reportError(error, 'send', 'Failed to send the draft');
719
1151
  throw error;
720
1152
  }
721
1153
  }
@@ -869,15 +1301,14 @@ export class EmailEngineClient {
869
1301
 
870
1302
  // Header for every state of the message list pane, titled with the folder
871
1303
  // being shown. In the single-pane layout its back button leads to the folders.
872
- _messageListHeader(path, controls = '') {
1304
+ _messageListHeader(path) {
873
1305
  const folder = path && this.folders.find(f => f.path === path);
874
1306
  return `
875
1307
  <div class="ee-pane-header">
876
1308
  <div class="ee-pane-heading">
877
1309
  ${this._iconButton('show-folders', 'back', 'Folders', 'ee-nav-button')}
878
- <span class="ee-pane-title">${this.escapeHtml(folder ? folder.name : 'Messages')}</span>
1310
+ <span class="ee-pane-title">${this.escapeHtml(folder ? folderDisplayName(folder) : 'Messages')}</span>
879
1311
  </div>
880
- ${controls}
881
1312
  </div>
882
1313
  `;
883
1314
  }
@@ -918,12 +1349,13 @@ export class EmailEngineClient {
918
1349
  const diff = now - date;
919
1350
 
920
1351
  if (diff < 86400000) {
921
- return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
1352
+ return date.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
922
1353
  } else if (diff < 604800000) {
923
- return date.toLocaleDateString([], { weekday: 'short', hour: '2-digit', minute: '2-digit' });
924
- } else {
1354
+ return date.toLocaleDateString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' });
1355
+ } else if (date.getFullYear() === now.getFullYear()) {
925
1356
  return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
926
1357
  }
1358
+ return date.toLocaleDateString([], { year: 'numeric', month: 'short', day: 'numeric' });
927
1359
  }
928
1360
 
929
1361
  // The date in the message header: weekday, date and time to the minute
@@ -1038,11 +1470,7 @@ export class EmailEngineClient {
1038
1470
  }
1039
1471
 
1040
1472
  escapeHtml(value) {
1041
- if (value === null || value === undefined) {
1042
- return '';
1043
- }
1044
- const htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
1045
- return String(value).replace(/[&<>"']/g, ch => htmlEscapes[ch]);
1473
+ return escapeHtml(value);
1046
1474
  }
1047
1475
 
1048
1476
  _authHeaders() {
@@ -1100,6 +1528,7 @@ export class EmailEngineClient {
1100
1528
  this._saveBlob(blob, filename);
1101
1529
  } catch (error) {
1102
1530
  console.error('Failed to download attachment:', error);
1531
+ this._reportError(error, 'download', 'Failed to download the attachment');
1103
1532
  this.alertMethod(this._errorMessage(error, 'Failed to download attachment. Please try again.'), 'Download Error', null, 'OK');
1104
1533
  }
1105
1534
  }
@@ -1120,6 +1549,7 @@ export class EmailEngineClient {
1120
1549
  this._saveBlob(blob, filename);
1121
1550
  } catch (error) {
1122
1551
  console.error('Failed to download original message:', error);
1552
+ this._reportError(error, 'download', 'Failed to download the original message');
1123
1553
  this.alertMethod(this._errorMessage(error, 'Failed to download original message. Please try again.'), 'Download Error', null, 'OK');
1124
1554
  }
1125
1555
  }
@@ -1147,7 +1577,7 @@ export class EmailEngineClient {
1147
1577
  element: setting --ee-accent itself here would hide the host's value. */
1148
1578
  .ee-client,
1149
1579
  .ee-compose-button,
1150
- .ee-compose-modal,
1580
+ .ee-compose,
1151
1581
  .ee-toast {
1152
1582
  --_accent: var(--ee-accent, #007bff);
1153
1583
  --_accent-hover: var(--ee-accent-hover, #0056b3);
@@ -1187,66 +1617,80 @@ export class EmailEngineClient {
1187
1617
  .ee-folder-list {
1188
1618
  list-style: none;
1189
1619
  margin: 0;
1190
- padding: 0;
1620
+ padding: 6px 8px;
1621
+ display: flex;
1622
+ flex-direction: column;
1623
+ gap: 1px;
1191
1624
  }
1192
-
1625
+
1193
1626
  .ee-folder-item {
1194
- cursor: pointer;
1195
- border-bottom: 1px solid #e0e0e0;
1196
1627
  position: relative;
1197
1628
  }
1198
-
1199
- .ee-folder-item:hover {
1200
- background: #e8e8e8;
1201
- }
1202
-
1203
- .ee-folder-item.active {
1204
- background: var(--_accent);
1205
- color: white;
1206
- }
1207
-
1208
- .ee-folder-item.active::before {
1209
- content: '';
1210
- position: absolute;
1211
- left: 0;
1212
- top: 0;
1213
- bottom: 0;
1214
- width: 3px;
1215
- background: var(--_accent-hover);
1216
- }
1217
-
1629
+
1630
+ /* The whole row is the button */
1218
1631
  .ee-folder-content {
1219
- padding: 8px 16px 8px 0px;
1220
1632
  display: flex;
1221
1633
  align-items: center;
1222
- position: relative;
1634
+ gap: 10px;
1635
+ width: 100%;
1636
+ min-height: 34px;
1637
+ padding: 6px 10px 6px 12px;
1638
+ border: none;
1639
+ border-radius: 6px;
1640
+ background: transparent;
1641
+ color: inherit;
1642
+ font: inherit;
1643
+ text-align: left;
1644
+ cursor: pointer;
1223
1645
  }
1224
-
1225
- .ee-folder-indent {
1226
- color: #999;
1227
- font-size: 12px;
1228
- margin-right: 4px;
1229
- font-family: monospace;
1646
+
1647
+ .ee-folder-content:hover {
1648
+ background: #eef1f4;
1230
1649
  }
1231
-
1232
- .ee-folder-name {
1233
- font-weight: 500;
1234
- flex: 1;
1650
+
1651
+ .ee-folder-content:focus-visible,
1652
+ .ee-message-item:focus-visible,
1653
+ .ee-attachment-item:focus-visible {
1654
+ outline: 2px solid var(--_accent);
1655
+ outline-offset: -2px;
1235
1656
  }
1236
-
1237
- .ee-folder-name.has-children {
1657
+
1658
+ .ee-folder-item.active .ee-folder-content {
1659
+ background: color-mix(in srgb, var(--_accent) 14%, white);
1660
+ color: var(--_accent-hover);
1238
1661
  font-weight: 600;
1239
1662
  }
1240
-
1241
- .ee-folder-item.active .ee-folder-indent {
1242
- color: rgba(255, 255, 255, 0.7);
1663
+
1664
+ .ee-folder-icon {
1665
+ display: inline-flex;
1666
+ flex-shrink: 0;
1667
+ color: #6b7280;
1243
1668
  }
1244
-
1669
+
1670
+ .ee-folder-item.active .ee-folder-icon {
1671
+ color: inherit;
1672
+ }
1673
+
1674
+ .ee-folder-name {
1675
+ flex: 1;
1676
+ min-width: 0;
1677
+ overflow: hidden;
1678
+ text-overflow: ellipsis;
1679
+ white-space: nowrap;
1680
+ }
1681
+
1245
1682
  .ee-folder-count {
1246
- font-size: 12px;
1247
- opacity: 0.7;
1248
- margin-left: 8px;
1249
1683
  flex-shrink: 0;
1684
+ min-width: 20px;
1685
+ padding: 0 6px;
1686
+ border-radius: 10px;
1687
+ background: var(--_accent);
1688
+ color: white;
1689
+ font-size: 11px;
1690
+ font-weight: 600;
1691
+ line-height: 18px;
1692
+ text-align: center;
1693
+ font-variant-numeric: tabular-nums;
1250
1694
  }
1251
1695
 
1252
1696
  .ee-main {
@@ -1265,49 +1709,76 @@ export class EmailEngineClient {
1265
1709
  flex-direction: column;
1266
1710
  }
1267
1711
 
1712
+ /* A list row is a button holding spans laid out as blocks */
1268
1713
  .ee-message-item {
1269
- padding: 12px 16px;
1714
+ display: block;
1715
+ width: 100%;
1716
+ padding: 10px 16px 10px 24px;
1717
+ border: none;
1270
1718
  border-bottom: 1px solid #e0e0e0;
1719
+ background: transparent;
1720
+ color: inherit;
1721
+ font: inherit;
1722
+ text-align: left;
1271
1723
  cursor: pointer;
1724
+ position: relative;
1272
1725
  }
1273
-
1726
+
1274
1727
  .ee-message-item:hover {
1275
1728
  background: #f8f8f8;
1276
1729
  }
1277
-
1730
+
1278
1731
  .ee-message-item.active {
1279
1732
  background: color-mix(in srgb, var(--_accent) 12%, white);
1280
1733
  }
1281
-
1282
- .ee-message-item.unread {
1734
+
1735
+ .ee-message-item.unread .ee-message-from,
1736
+ .ee-message-item.unread .ee-message-subject-text {
1283
1737
  font-weight: 600;
1284
1738
  }
1285
-
1739
+
1740
+ .ee-unread-dot {
1741
+ position: absolute;
1742
+ left: 9px;
1743
+ top: 17px;
1744
+ width: 8px;
1745
+ height: 8px;
1746
+ border-radius: 50%;
1747
+ background: var(--_accent);
1748
+ }
1749
+
1286
1750
  .ee-message-header {
1287
1751
  display: flex;
1288
1752
  justify-content: space-between;
1289
- margin-bottom: 4px;
1753
+ margin-bottom: 2px;
1290
1754
  }
1291
-
1755
+
1292
1756
  .ee-message-from {
1293
1757
  flex: 1;
1294
1758
  overflow: hidden;
1295
1759
  text-overflow: ellipsis;
1296
1760
  white-space: nowrap;
1297
1761
  }
1298
-
1762
+
1763
+ .ee-message-to-label {
1764
+ color: #666;
1765
+ font-weight: 400;
1766
+ }
1767
+
1299
1768
  .ee-message-date {
1300
1769
  font-size: 12px;
1301
1770
  color: #666;
1302
1771
  flex-shrink: 0;
1303
1772
  margin-left: 8px;
1773
+ font-variant-numeric: tabular-nums;
1304
1774
  }
1305
-
1775
+
1306
1776
  .ee-message-subject {
1307
1777
  display: flex;
1308
1778
  align-items: center;
1309
- margin-bottom: 2px;
1779
+ color: #444;
1310
1780
  }
1781
+
1311
1782
 
1312
1783
  .ee-message-subject-text {
1313
1784
  overflow: hidden;
@@ -1318,6 +1789,8 @@ export class EmailEngineClient {
1318
1789
  }
1319
1790
 
1320
1791
  .ee-message-preview {
1792
+ display: block;
1793
+ margin-top: 2px;
1321
1794
  font-size: 12px;
1322
1795
  color: #666;
1323
1796
  overflow: hidden;
@@ -1609,42 +2082,71 @@ export class EmailEngineClient {
1609
2082
  margin-bottom: 8px;
1610
2083
  color: #333;
1611
2084
  }
1612
-
2085
+
2086
+ .ee-attachment-grid {
2087
+ display: grid;
2088
+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
2089
+ gap: 8px;
2090
+ }
2091
+
1613
2092
  .ee-attachment-item {
1614
2093
  display: flex;
1615
2094
  align-items: center;
1616
- padding: 8px;
1617
- margin-bottom: 4px;
1618
- background: #f8f8f8;
2095
+ gap: 10px;
2096
+ min-width: 0;
2097
+ padding: 8px 10px;
2098
+ background: #f8f9fa;
1619
2099
  border: 1px solid #e0e0e0;
1620
- border-radius: 4px;
2100
+ border-radius: 6px;
2101
+ color: inherit;
2102
+ font: inherit;
2103
+ text-align: left;
1621
2104
  cursor: pointer;
1622
2105
  transition: background 0.2s;
1623
2106
  }
1624
-
2107
+
1625
2108
  .ee-attachment-item:hover {
1626
- background: #f0f0f0;
2109
+ background: #eef1f4;
1627
2110
  }
1628
-
1629
- .ee-attachment-icon {
1630
- display: flex;
1631
- margin-right: 8px;
1632
- color: #666;
2111
+
2112
+ .ee-attachment-type {
2113
+ flex-shrink: 0;
2114
+ width: 38px;
2115
+ padding: 6px 0;
2116
+ border-radius: 4px;
2117
+ background: color-mix(in srgb, var(--_accent) 12%, white);
2118
+ color: var(--_accent-hover);
2119
+ font-size: 10px;
2120
+ font-weight: 700;
2121
+ letter-spacing: 0.03em;
2122
+ text-align: center;
1633
2123
  }
1634
-
2124
+
1635
2125
  .ee-attachment-info {
2126
+ display: flex;
2127
+ flex-direction: column;
1636
2128
  flex: 1;
2129
+ min-width: 0;
1637
2130
  }
1638
-
2131
+
1639
2132
  .ee-attachment-name {
1640
2133
  font-weight: 500;
1641
2134
  color: #333;
2135
+ overflow: hidden;
2136
+ text-overflow: ellipsis;
2137
+ white-space: nowrap;
1642
2138
  }
1643
-
2139
+
1644
2140
  .ee-attachment-size {
1645
2141
  font-size: 12px;
1646
2142
  color: #666;
1647
2143
  }
2144
+
2145
+ .ee-attachment-download {
2146
+ display: inline-flex;
2147
+ flex-shrink: 0;
2148
+ color: #666;
2149
+ }
1648
2150
 
1649
2151
  .ee-empty-state {
1650
2152
  display: flex;
@@ -1739,18 +2241,30 @@ export class EmailEngineClient {
1739
2241
  overflow-y: auto;
1740
2242
  }
1741
2243
 
1742
- .ee-pagination-controls {
2244
+ /* Paging, under the list: the position, the arrows and the page size */
2245
+ .ee-list-footer {
1743
2246
  display: flex;
1744
- gap: 6px;
1745
2247
  align-items: center;
2248
+ gap: 6px;
1746
2249
  flex-shrink: 0;
2250
+ padding: 6px 12px 6px 16px;
2251
+ border-top: 1px solid #e0e0e0;
2252
+ background: #f8f9fa;
1747
2253
  }
1748
-
2254
+
2255
+ .ee-list-range {
2256
+ flex: 1;
2257
+ font-size: 12px;
2258
+ color: #666;
2259
+ font-variant-numeric: tabular-nums;
2260
+ white-space: nowrap;
2261
+ }
2262
+
1749
2263
  .ee-page-size-selector {
1750
2264
  display: flex;
1751
2265
  gap: 6px;
1752
2266
  align-items: center;
1753
- margin-left: 4px;
2267
+ margin-left: 6px;
1754
2268
  }
1755
2269
 
1756
2270
  .ee-page-size-label {
@@ -1787,6 +2301,11 @@ export class EmailEngineClient {
1787
2301
  transition: background 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease;
1788
2302
  }
1789
2303
 
2304
+ /* An open message on a phone has its own reply actions; the button would cover the text */
2305
+ .ee-client[data-view="message"] ~ .ee-compose-button {
2306
+ display: none;
2307
+ }
2308
+
1790
2309
  .ee-compose-button:hover {
1791
2310
  background: var(--_accent-hover);
1792
2311
  transform: translateY(-1px);
@@ -1864,204 +2383,336 @@ export class EmailEngineClient {
1864
2383
  }
1865
2384
  }
1866
2385
 
1867
- .ee-compose-modal {
1868
- display: none;
2386
+ /* Compose: a panel docked to the bottom right of the window, without a backdrop, so the
2387
+ message being answered stays readable and the list stays usable. It fills the screen
2388
+ on a phone. The outer element only positions the panel. */
2389
+ .ee-compose {
1869
2390
  position: fixed;
1870
- top: 0;
1871
- left: 0;
1872
- width: 100%;
1873
- height: 100%;
1874
- background: rgba(0, 0, 0, 0.5);
2391
+ right: 24px;
2392
+ bottom: 0;
1875
2393
  z-index: 2000;
2394
+ font-family: var(--ee-font, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif);
2395
+ font-size: 14px;
2396
+ line-height: 1.5;
2397
+ color: #333;
1876
2398
  }
1877
-
1878
- .ee-compose-modal.show {
1879
- display: flex;
1880
- align-items: center;
1881
- justify-content: center;
2399
+
2400
+ .ee-compose * {
2401
+ box-sizing: border-box;
1882
2402
  }
1883
-
2403
+
1884
2404
  .ee-compose-dialog {
1885
- background: white;
1886
- border-radius: 8px;
1887
- width: 90%;
1888
- max-width: 600px;
1889
- max-height: 90vh;
1890
- box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
1891
2405
  display: flex;
1892
2406
  flex-direction: column;
2407
+ width: min(600px, calc(100vw - 48px));
2408
+ height: min(680px, calc(100vh - 32px));
2409
+ background: white;
2410
+ border: 1px solid #d5dbe3;
2411
+ border-bottom: none;
2412
+ border-radius: 10px 10px 0 0;
2413
+ box-shadow: 0 8px 40px rgba(0, 0, 0, 0.25);
2414
+ overflow: hidden;
1893
2415
  }
1894
-
2416
+
2417
+ /* Minimizing is for the docked panel; on a phone the form is the whole screen */
2418
+ @media (min-width: 701px) {
2419
+ .ee-compose-dialog.minimized {
2420
+ width: 300px;
2421
+ height: auto;
2422
+ }
2423
+
2424
+ .ee-compose-dialog.minimized > :not(.ee-compose-header) {
2425
+ display: none;
2426
+ }
2427
+
2428
+ .ee-compose-dialog.minimized .ee-compose-header {
2429
+ cursor: pointer;
2430
+ }
2431
+ }
2432
+
2433
+ .ee-compose-window-button > span {
2434
+ display: inline-flex;
2435
+ }
2436
+
2437
+ .ee-compose-dialog:not(.minimized) .ee-when-minimized,
2438
+ .ee-compose-dialog.minimized .ee-when-open {
2439
+ display: none;
2440
+ }
2441
+
1895
2442
  .ee-compose-header {
1896
- padding: 16px 20px;
1897
- border-bottom: 1px solid #e0e0e0;
1898
2443
  display: flex;
1899
- justify-content: space-between;
1900
2444
  align-items: center;
2445
+ gap: 4px;
1901
2446
  flex-shrink: 0;
2447
+ padding: 8px 8px 8px 16px;
2448
+ background: #2b3440;
2449
+ color: #fff;
1902
2450
  }
1903
-
2451
+
1904
2452
  .ee-compose-title {
1905
- font-size: 18px;
1906
- font-weight: 600;
2453
+ flex: 1;
2454
+ min-width: 0;
1907
2455
  margin: 0;
2456
+ font-size: 14px;
2457
+ font-weight: 600;
2458
+ overflow: hidden;
2459
+ text-overflow: ellipsis;
2460
+ white-space: nowrap;
1908
2461
  }
1909
-
1910
- .ee-compose-close {
1911
- background: none;
1912
- border: none;
1913
- color: #666;
1914
- cursor: pointer;
1915
- padding: 0;
1916
- width: 30px;
1917
- height: 30px;
1918
- border-radius: 50%;
1919
- display: flex;
2462
+
2463
+ .ee-compose-window-button {
2464
+ display: inline-flex;
1920
2465
  align-items: center;
1921
2466
  justify-content: center;
2467
+ width: 28px;
2468
+ height: 28px;
2469
+ padding: 0;
2470
+ border: none;
2471
+ border-radius: 6px;
2472
+ background: transparent;
2473
+ color: rgba(255, 255, 255, 0.85);
2474
+ cursor: pointer;
1922
2475
  }
1923
-
1924
- .ee-compose-close:hover {
1925
- background: #f0f0f0;
2476
+
2477
+ .ee-compose-window-button:hover {
2478
+ background: rgba(255, 255, 255, 0.15);
2479
+ color: #fff;
1926
2480
  }
1927
-
2481
+
1928
2482
  .ee-compose-form {
1929
- padding: 16px 20px;
1930
2483
  display: flex;
1931
2484
  flex-direction: column;
1932
- gap: 10px;
1933
2485
  flex: 1;
2486
+ min-height: 0;
1934
2487
  overflow-y: auto;
2488
+ padding: 4px 16px 12px;
1935
2489
  }
1936
2490
 
1937
- /* One line per header field: the label beside its input, as mail clients lay out
1938
- their compose headers, so the text box and the quote get the height */
2491
+ /* One line per header field, the label beside its input and a rule under it, as mail
2492
+ clients lay out their compose headers */
1939
2493
  .ee-compose-row {
1940
2494
  display: flex;
1941
2495
  align-items: center;
1942
2496
  gap: 10px;
2497
+ border-bottom: 1px solid #e5e8ec;
1943
2498
  }
1944
2499
 
1945
2500
  .ee-compose-label {
1946
- flex: 0 0 56px;
2501
+ flex: 0 0 52px;
1947
2502
  font-size: 13px;
1948
- font-weight: 500;
1949
- color: #555;
2503
+ color: #666;
1950
2504
  }
1951
2505
 
1952
2506
  .ee-compose-input {
1953
2507
  flex: 1;
1954
2508
  min-width: 0;
1955
- padding: 8px 12px;
1956
- border: 1px solid #ddd;
1957
- border-radius: 4px;
1958
- font-size: 14px;
1959
- font-family: inherit;
2509
+ padding: 10px 0;
2510
+ border: none;
2511
+ background: transparent;
2512
+ color: inherit;
2513
+ font: inherit;
1960
2514
  }
1961
2515
 
1962
- .ee-compose-input[aria-invalid="true"],
1963
- .ee-compose-textarea[aria-invalid="true"] {
1964
- border-color: #dc3545;
2516
+ .ee-compose-input:focus {
2517
+ outline: none;
2518
+ }
2519
+
2520
+ .ee-compose-row:focus-within {
2521
+ border-bottom-color: var(--_accent);
2522
+ }
2523
+
2524
+ .ee-compose-row:has([aria-invalid="true"]) {
2525
+ border-bottom-color: #dc3545;
2526
+ }
2527
+
2528
+ .ee-compose-toolbar {
2529
+ display: flex;
2530
+ gap: 2px;
2531
+ padding: 6px 0;
2532
+ border-bottom: 1px solid #e5e8ec;
2533
+ }
2534
+
2535
+ .ee-compose-format,
2536
+ .ee-compose-icon-button {
2537
+ display: inline-flex;
2538
+ align-items: center;
2539
+ justify-content: center;
2540
+ width: 30px;
2541
+ height: 30px;
2542
+ padding: 0;
2543
+ border: none;
2544
+ border-radius: 6px;
2545
+ background: transparent;
2546
+ color: #555;
2547
+ cursor: pointer;
2548
+ }
2549
+
2550
+ .ee-compose-format:hover,
2551
+ .ee-compose-icon-button:hover {
2552
+ background: #eef1f4;
2553
+ color: #222;
2554
+ }
2555
+
2556
+ .ee-compose-format[aria-pressed="true"] {
2557
+ background: color-mix(in srgb, var(--_accent) 14%, white);
2558
+ color: var(--_accent-hover);
2559
+ }
2560
+
2561
+ .ee-compose-linkbar {
2562
+ display: flex;
2563
+ align-items: center;
2564
+ gap: 8px;
2565
+ padding: 6px 0;
2566
+ border-bottom: 1px solid #e5e8ec;
2567
+ }
2568
+
2569
+ .ee-compose-linkbar .ee-compose-input {
2570
+ padding: 6px 8px;
2571
+ border: 1px solid #d5dbe3;
2572
+ border-radius: 6px;
2573
+ }
2574
+
2575
+ .ee-compose-small-button {
2576
+ flex-shrink: 0;
2577
+ padding: 6px 10px;
2578
+ border: 1px solid #d5dbe3;
2579
+ border-radius: 6px;
2580
+ background: white;
2581
+ color: inherit;
2582
+ font: inherit;
2583
+ font-size: 13px;
2584
+ cursor: pointer;
2585
+ }
2586
+
2587
+ .ee-compose-small-button:hover {
2588
+ background: #eef1f4;
2589
+ }
2590
+
2591
+ .ee-compose-editor {
2592
+ position: relative;
2593
+ flex: 1 0 auto;
2594
+ min-height: 160px;
2595
+ padding: 12px 0;
2596
+ outline: none;
2597
+ overflow-wrap: break-word;
2598
+ cursor: text;
2599
+ }
2600
+
2601
+ .ee-compose-editor.ee-empty::before {
2602
+ content: attr(data-placeholder);
2603
+ color: #999;
2604
+ pointer-events: none;
2605
+ position: absolute;
2606
+ }
2607
+
2608
+ .ee-compose-editor p {
2609
+ margin: 0 0 0.8em;
2610
+ }
2611
+
2612
+ .ee-compose-editor blockquote {
2613
+ margin: 0 0 0.8em 0.4em;
2614
+ padding-left: 10px;
2615
+ border-left: 2px solid #ccc;
2616
+ color: #555;
2617
+ }
2618
+
2619
+ .ee-compose-editor a {
2620
+ color: var(--_accent);
2621
+ }
2622
+
2623
+ .ee-compose-editor[aria-invalid="true"] {
2624
+ box-shadow: inset 0 -2px 0 #dc3545;
1965
2625
  }
1966
2626
 
1967
2627
  /* Why the form did not go out, between the form and its buttons so it is on
1968
2628
  screen however far the form is scrolled */
1969
2629
  .ee-compose-error {
1970
- margin: 0 20px 4px;
2630
+ margin: 0 16px 8px;
1971
2631
  padding: 8px 12px;
1972
2632
  border: 1px solid #fcc;
1973
- border-radius: 4px;
2633
+ border-radius: 6px;
1974
2634
  background: #fee;
1975
2635
  color: #c00;
1976
2636
  font-size: 13px;
1977
2637
  white-space: pre-line;
1978
2638
  flex-shrink: 0;
1979
2639
  }
1980
-
1981
- .ee-compose-textarea {
1982
- padding: 12px;
1983
- border: 1px solid #ddd;
1984
- border-radius: 4px;
1985
- font-size: 14px;
1986
- font-family: inherit;
1987
- resize: vertical;
1988
- min-height: 180px;
1989
- }
1990
2640
 
1991
- .ee-compose-input:focus,
1992
- .ee-compose-textarea:focus {
1993
- outline: none;
1994
- border-color: var(--_accent);
1995
- box-shadow: 0 0 0 2px color-mix(in srgb, var(--_accent) 12%, transparent);
1996
- }
1997
-
1998
2641
  .ee-compose-actions {
1999
- padding: 16px 20px;
2000
- border-top: 1px solid #e0e0e0;
2001
2642
  display: flex;
2002
- gap: 12px;
2003
- justify-content: flex-end;
2643
+ align-items: center;
2644
+ gap: 6px;
2004
2645
  flex-shrink: 0;
2646
+ padding: 10px 16px;
2647
+ border-top: 1px solid #e5e8ec;
2005
2648
  }
2006
-
2649
+
2650
+
2007
2651
  .ee-compose-send {
2652
+ padding: 8px 22px;
2653
+ border: none;
2654
+ border-radius: 18px;
2008
2655
  background: var(--_accent);
2009
2656
  color: white;
2010
- border: none;
2011
- padding: 10px 20px;
2012
- border-radius: 4px;
2013
- font-size: 14px;
2014
- font-weight: 500;
2657
+ font: inherit;
2658
+ font-weight: 600;
2015
2659
  cursor: pointer;
2016
2660
  }
2017
-
2661
+
2018
2662
  .ee-compose-send:hover:not(:disabled) {
2019
2663
  background: var(--_accent-hover);
2020
2664
  }
2021
-
2022
- .ee-compose-send:disabled {
2023
- background: #6c757d;
2665
+
2666
+ .ee-compose-send:disabled,
2667
+ .ee-compose-save-draft:disabled {
2024
2668
  cursor: not-allowed;
2025
2669
  opacity: 0.6;
2026
2670
  }
2027
-
2028
- /* Cancel is the quiet way out, not a third weighted button */
2029
- .ee-compose-cancel {
2030
- margin-right: auto;
2031
- background: transparent;
2032
- color: #555;
2033
- border: none;
2034
- padding: 10px 12px;
2035
- border-radius: 4px;
2036
- font-size: 14px;
2037
- cursor: pointer;
2038
- }
2039
-
2040
- .ee-compose-cancel:hover {
2041
- background: #f0f0f0;
2042
- }
2043
2671
 
2044
2672
  .ee-compose-save-draft {
2045
- background: transparent;
2046
- color: var(--_accent);
2047
- border: 1px solid var(--_accent);
2048
- padding: 10px 20px;
2049
- border-radius: 4px;
2050
- font-size: 14px;
2051
- font-weight: 500;
2673
+ margin-left: auto;
2674
+ padding: 7px 14px;
2675
+ border: 1px solid #d5dbe3;
2676
+ border-radius: 18px;
2677
+ background: white;
2678
+ color: inherit;
2679
+ font: inherit;
2052
2680
  cursor: pointer;
2053
2681
  }
2054
2682
 
2055
2683
  .ee-compose-save-draft:hover:not(:disabled) {
2056
- background: var(--_accent);
2057
- color: white;
2684
+ background: #eef1f4;
2685
+ }
2686
+
2687
+ .ee-compose-format:focus-visible,
2688
+ .ee-compose-icon-button:focus-visible,
2689
+ .ee-compose-window-button:focus-visible,
2690
+ .ee-compose-send:focus-visible,
2691
+ .ee-compose-save-draft:focus-visible,
2692
+ .ee-compose-small-button:focus-visible,
2693
+ .ee-compose-quote-toggle:focus-visible,
2694
+ .ee-compose-chip-remove:focus-visible,
2695
+ .ee-compose-link:focus-visible {
2696
+ outline: 2px solid var(--_accent);
2697
+ outline-offset: 1px;
2058
2698
  }
2059
2699
 
2060
- .ee-compose-save-draft:disabled {
2061
- color: #6c757d;
2062
- border-color: #6c757d;
2063
- cursor: not-allowed;
2064
- opacity: 0.6;
2700
+ /* On a phone the form is the whole screen; minimizing it makes no sense there */
2701
+ @media (max-width: 700px) {
2702
+ .ee-compose {
2703
+ inset: 0;
2704
+ }
2705
+
2706
+ .ee-compose-dialog {
2707
+ width: 100%;
2708
+ height: 100%;
2709
+ border: none;
2710
+ border-radius: 0;
2711
+ }
2712
+
2713
+ .ee-compose [data-action="minimize"] {
2714
+ display: none;
2715
+ }
2065
2716
  }
2066
2717
 
2067
2718
  .ee-sidebar-compose {
@@ -2141,9 +2792,10 @@ export class EmailEngineClient {
2141
2792
  color: #1a1a1a;
2142
2793
  }
2143
2794
 
2144
- /* Parts of the compose form that come and go (Cc/Bcc, the forward checkbox, the
2145
- quote) use the hidden attribute, which a display rule would otherwise override */
2146
- .ee-compose-modal [hidden] {
2795
+ /* Parts of the compose form that come and go (Cc/Bcc, the link field, the quote) use
2796
+ the hidden attribute, which a display rule would otherwise override */
2797
+ .ee-compose [hidden],
2798
+ .ee-compose[hidden] {
2147
2799
  display: none !important;
2148
2800
  }
2149
2801
 
@@ -2162,49 +2814,11 @@ export class EmailEngineClient {
2162
2814
  text-decoration: underline;
2163
2815
  }
2164
2816
 
2165
- .ee-compose-files {
2166
- display: flex;
2167
- flex-direction: column;
2168
- gap: 8px;
2169
- }
2170
-
2171
- .ee-compose-files-row {
2172
- display: flex;
2173
- flex-wrap: wrap;
2174
- align-items: center;
2175
- gap: 8px 16px;
2176
- }
2177
-
2178
- .ee-compose-attach {
2179
- display: inline-flex;
2180
- align-items: center;
2181
- gap: 6px;
2182
- background: transparent;
2183
- border: 1px solid #ddd;
2184
- border-radius: 4px;
2185
- padding: 6px 12px;
2186
- font: inherit;
2187
- font-size: 13px;
2188
- color: inherit;
2189
- cursor: pointer;
2190
- }
2191
-
2192
- .ee-compose-attach:hover {
2193
- background: #f0f0f0;
2194
- }
2195
-
2196
- .ee-compose-forward-attachments {
2197
- display: inline-flex;
2198
- align-items: center;
2199
- gap: 6px;
2200
- font-size: 13px;
2201
- cursor: pointer;
2202
- }
2203
-
2204
2817
  .ee-compose-chips {
2205
2818
  display: flex;
2206
2819
  flex-wrap: wrap;
2207
2820
  gap: 6px;
2821
+ padding-bottom: 10px;
2208
2822
  }
2209
2823
 
2210
2824
  .ee-compose-chips:empty {
@@ -2254,24 +2868,58 @@ export class EmailEngineClient {
2254
2868
  background: #e0e0e0;
2255
2869
  }
2256
2870
 
2871
+ /* The message being answered or forwarded, behind a "..." toggle */
2257
2872
  .ee-compose-quote {
2258
2873
  display: flex;
2259
2874
  flex-direction: column;
2875
+ align-items: flex-start;
2876
+ gap: 8px;
2877
+ }
2878
+
2879
+ .ee-compose-quote-toggle {
2880
+ display: inline-flex;
2881
+ align-items: center;
2260
2882
  gap: 6px;
2883
+ padding: 2px 10px 2px 6px;
2884
+ border: 1px solid #d5dbe3;
2885
+ border-radius: 12px;
2886
+ background: #f3f5f7;
2887
+ color: #555;
2888
+ font: inherit;
2889
+ font-size: 12px;
2890
+ cursor: pointer;
2261
2891
  }
2262
2892
 
2263
- .ee-compose-quote-label {
2893
+ .ee-compose-quote-toggle:hover {
2894
+ background: #e8ecf0;
2895
+ }
2896
+
2897
+ .ee-compose-quote-content {
2898
+ align-self: stretch;
2899
+ padding: 4px 0 4px 12px;
2900
+ border-left: 2px solid #ccc;
2901
+ }
2902
+
2903
+ .ee-forward-title {
2904
+ font-weight: 600;
2905
+ margin-bottom: 4px;
2906
+ }
2907
+
2908
+ .ee-forward-row {
2909
+ display: flex;
2910
+ gap: 8px;
2264
2911
  font-size: 13px;
2912
+ }
2913
+
2914
+ .ee-forward-label {
2915
+ flex: 0 0 56px;
2265
2916
  color: #666;
2266
2917
  }
2267
2918
 
2268
- .ee-compose-quote-frame {
2269
- max-height: 220px;
2270
- overflow: auto;
2271
- padding: 8px 12px;
2272
- border-left: 3px solid #ddd;
2273
- background: #fafafa;
2274
- border-radius: 0 4px 4px 0;
2919
+ .ee-compose-quote-header:not(:empty) {
2920
+ margin-bottom: 12px;
2921
+ padding-bottom: 10px;
2922
+ border-bottom: 1px solid #e5e8ec;
2275
2923
  }
2276
2924
 
2277
2925
  /* Dark mode toggle button, in the Folders pane header */
@@ -2322,15 +2970,20 @@ export class EmailEngineClient {
2322
2970
  border-color: #333;
2323
2971
  }
2324
2972
 
2325
- .ee-dark-mode .ee-folder-item {
2326
- border-color: #333;
2973
+ .ee-dark-mode .ee-folder-content:hover {
2974
+ background: #2a2a2a;
2327
2975
  }
2328
2976
 
2329
- .ee-dark-mode .ee-folder-item:hover {
2330
- background: #2a2a2a;
2977
+ .ee-dark-mode .ee-folder-item.active .ee-folder-content {
2978
+ background: color-mix(in srgb, var(--_accent) 35%, #1a1a1a);
2979
+ color: #fff;
2980
+ }
2981
+
2982
+ .ee-dark-mode .ee-folder-icon {
2983
+ color: #999;
2331
2984
  }
2332
2985
 
2333
- .ee-dark-mode .ee-folder-item.active {
2986
+ .ee-dark-mode .ee-folder-count {
2334
2987
  background: var(--_accent-hover);
2335
2988
  }
2336
2989
 
@@ -2353,10 +3006,27 @@ export class EmailEngineClient {
2353
3006
 
2354
3007
  .ee-dark-mode .ee-message-date,
2355
3008
  .ee-dark-mode .ee-message-preview,
2356
- .ee-dark-mode .ee-attachment-indicator {
3009
+ .ee-dark-mode .ee-message-to-label,
3010
+ .ee-dark-mode .ee-attachment-indicator,
3011
+ .ee-dark-mode .ee-list-range,
3012
+ .ee-dark-mode .ee-attachment-download {
2357
3013
  color: #999;
2358
3014
  }
2359
3015
 
3016
+ .ee-dark-mode .ee-message-subject {
3017
+ color: #ccc;
3018
+ }
3019
+
3020
+ .ee-dark-mode .ee-list-footer {
3021
+ background: #252525;
3022
+ border-color: #333;
3023
+ }
3024
+
3025
+ .ee-dark-mode .ee-attachment-type {
3026
+ background: color-mix(in srgb, var(--_accent) 30%, #1a1a1a);
3027
+ color: #e0e0e0;
3028
+ }
3029
+
2360
3030
  .ee-dark-mode .ee-pane-header {
2361
3031
  background: linear-gradient(to bottom, #2a2a2a, #252525);
2362
3032
  border-color: #333;
@@ -2496,121 +3166,99 @@ export class EmailEngineClient {
2496
3166
  color: #999;
2497
3167
  }
2498
3168
 
2499
- .ee-dark-mode .ee-pagination {
2500
- background: #252525;
2501
- border-color: #333;
2502
- }
2503
-
2504
- /* The compose button and modal sit beside .ee-client, not inside it, so
3169
+ /* The compose button and form sit beside .ee-client, not inside it, so
2505
3170
  setDarkMode puts the ee-dark-mode class on them directly */
2506
3171
  .ee-compose-button.ee-dark-mode {
2507
3172
  background: var(--_accent-hover);
2508
3173
  color: white;
2509
3174
  }
2510
3175
 
2511
- .ee-compose-modal.ee-dark-mode {
2512
- background: rgba(0, 0, 0, 0.7);
2513
- }
2514
-
2515
- .ee-dark-mode .ee-compose-dialog {
2516
- background: #202020;
3176
+ .ee-compose.ee-dark-mode {
2517
3177
  color: #e0e0e0;
2518
3178
  }
2519
3179
 
2520
- .ee-dark-mode .ee-compose-header {
2521
- background: linear-gradient(to bottom, #2a2a2a, #252525);
2522
- border-color: #333;
2523
- }
2524
-
2525
- .ee-dark-mode .ee-compose-close {
2526
- color: #999;
2527
- }
2528
-
2529
- .ee-dark-mode .ee-compose-close:hover {
2530
- color: #fff;
2531
- }
2532
-
2533
- .ee-dark-mode .ee-compose-input,
2534
- .ee-dark-mode .ee-compose-textarea {
2535
- background: #1a1a1a;
2536
- border-color: #444;
2537
- color: #e0e0e0;
3180
+ .ee-compose.ee-dark-mode .ee-compose-dialog {
3181
+ background: #202020;
3182
+ border-color: #3a3a3a;
3183
+ box-shadow: 0 8px 40px rgba(0, 0, 0, 0.6);
2538
3184
  }
2539
3185
 
2540
- .ee-dark-mode .ee-compose-input:focus,
2541
- .ee-dark-mode .ee-compose-textarea:focus {
2542
- border-color: var(--_accent-hover);
2543
- box-shadow: 0 0 0 2px color-mix(in srgb, var(--_accent) 25%, transparent);
3186
+ .ee-compose.ee-dark-mode .ee-compose-header {
3187
+ background: #111;
2544
3188
  }
2545
3189
 
2546
- .ee-dark-mode .ee-compose-actions {
3190
+ .ee-compose.ee-dark-mode .ee-compose-row,
3191
+ .ee-compose.ee-dark-mode .ee-compose-toolbar,
3192
+ .ee-compose.ee-dark-mode .ee-compose-linkbar,
3193
+ .ee-compose.ee-dark-mode .ee-compose-actions,
3194
+ .ee-compose.ee-dark-mode .ee-compose-quote-header:not(:empty) {
2547
3195
  border-color: #333;
2548
3196
  }
2549
3197
 
2550
- .ee-dark-mode .ee-compose-cancel {
2551
- color: #ccc;
2552
- }
2553
-
2554
- .ee-dark-mode .ee-compose-cancel:hover {
2555
- background: #333;
2556
- }
2557
-
2558
- .ee-dark-mode .ee-compose-save-draft {
2559
- color: var(--_accent-light);
2560
- border-color: var(--_accent-light);
2561
- }
2562
-
2563
- .ee-dark-mode .ee-compose-save-draft:hover:not(:disabled) {
2564
- background: var(--_accent-light);
2565
- color: #1a1a1a;
3198
+ .ee-compose.ee-dark-mode .ee-compose-label,
3199
+ .ee-compose.ee-dark-mode .ee-forward-label,
3200
+ .ee-compose.ee-dark-mode .ee-compose-chip-size,
3201
+ .ee-compose.ee-dark-mode .ee-compose-chip-remove {
3202
+ color: #999;
2566
3203
  }
2567
3204
 
2568
- .ee-dark-mode .ee-sidebar-compose {
2569
- border-color: #333;
3205
+ .ee-compose.ee-dark-mode .ee-compose-format,
3206
+ .ee-compose.ee-dark-mode .ee-compose-icon-button {
3207
+ color: #bbb;
2570
3208
  }
2571
3209
 
2572
- .ee-dark-mode .ee-toolbar-divider {
2573
- background: #444;
3210
+ .ee-compose.ee-dark-mode .ee-compose-format:hover,
3211
+ .ee-compose.ee-dark-mode .ee-compose-icon-button:hover,
3212
+ .ee-compose.ee-dark-mode .ee-compose-small-button:hover,
3213
+ .ee-compose.ee-dark-mode .ee-compose-save-draft:hover:not(:disabled),
3214
+ .ee-compose.ee-dark-mode .ee-compose-chip-remove:hover,
3215
+ .ee-compose.ee-dark-mode .ee-compose-quote-toggle:hover {
3216
+ background: #333;
3217
+ color: #fff;
2574
3218
  }
2575
3219
 
2576
- .ee-dark-mode .ee-address,
2577
- .ee-dark-mode .ee-compose-label {
2578
- color: #aaa;
3220
+ .ee-compose.ee-dark-mode .ee-compose-format[aria-pressed="true"] {
3221
+ background: color-mix(in srgb, var(--_accent) 35%, #1a1a1a);
3222
+ color: #fff;
2579
3223
  }
2580
3224
 
2581
- .ee-dark-mode .ee-compose-error {
2582
- background: #3a2222;
2583
- border-color: #5c3030;
2584
- color: #f0a5a5;
3225
+ .ee-compose.ee-dark-mode .ee-compose-small-button,
3226
+ .ee-compose.ee-dark-mode .ee-compose-save-draft,
3227
+ .ee-compose.ee-dark-mode .ee-compose-chip,
3228
+ .ee-compose.ee-dark-mode .ee-compose-quote-toggle,
3229
+ .ee-compose.ee-dark-mode .ee-compose-linkbar .ee-compose-input {
3230
+ background: #2a2a2a;
3231
+ border-color: #444;
3232
+ color: #e0e0e0;
2585
3233
  }
2586
3234
 
2587
- .ee-dark-mode .ee-compose-link {
2588
- color: var(--_accent-light);
3235
+ .ee-compose.ee-dark-mode .ee-compose-editor blockquote,
3236
+ .ee-compose.ee-dark-mode .ee-compose-quote-content {
3237
+ border-color: #555;
3238
+ color: #ccc;
2589
3239
  }
2590
3240
 
2591
- .ee-dark-mode .ee-compose-attach {
2592
- border-color: #444;
3241
+ .ee-compose.ee-dark-mode .ee-compose-editor a,
3242
+ .ee-compose.ee-dark-mode .ee-compose-link {
3243
+ color: var(--_accent-light);
2593
3244
  }
2594
3245
 
2595
- .ee-dark-mode .ee-compose-attach:hover,
2596
- .ee-dark-mode .ee-compose-chip-remove:hover {
2597
- background: #333;
3246
+ .ee-compose.ee-dark-mode .ee-compose-error {
3247
+ background: #3a2222;
3248
+ border-color: #5c3030;
3249
+ color: #f0a5a5;
2598
3250
  }
2599
3251
 
2600
- .ee-dark-mode .ee-compose-chip {
2601
- background: #2a2a2a;
2602
- border-color: #444;
3252
+ .ee-dark-mode .ee-sidebar-compose {
3253
+ border-color: #333;
2603
3254
  }
2604
3255
 
2605
- .ee-dark-mode .ee-compose-chip-size,
2606
- .ee-dark-mode .ee-compose-chip-remove,
2607
- .ee-dark-mode .ee-compose-quote-label {
2608
- color: #999;
3256
+ .ee-dark-mode .ee-toolbar-divider {
3257
+ background: #444;
2609
3258
  }
2610
3259
 
2611
- .ee-dark-mode .ee-compose-quote-frame {
2612
- background: #1a1a1a;
2613
- border-color: #444;
3260
+ .ee-dark-mode .ee-address {
3261
+ color: #aaa;
2614
3262
  }
2615
3263
  `);
2616
3264
  document.head.appendChild(style);
@@ -2710,39 +3358,105 @@ export class EmailEngineClient {
2710
3358
  return;
2711
3359
  }
2712
3360
 
2713
- const sortedFolders = this.buildFolderTree();
2714
- // Precompute which paths are some folder's parent so the per-row
2715
- // has-children check is O(1) instead of scanning this.folders each time.
2716
- const parentPaths = new Set(this.folders.map(f => f.parentPath));
2717
-
2718
3361
  const html = `
2719
3362
  <ul class="ee-folder-list">
2720
- ${sortedFolders
2721
- .map(({ folder, depth }) => {
2722
- const hasChildren = parentPaths.has(folder.path);
2723
- return `
2724
- <li class="ee-folder-item ${folder.path === this.currentFolder ? 'active' : ''}"
2725
- data-path="${this.escapeHtml(folder.path)}"
2726
- data-depth="${depth}">
2727
- <div class="ee-folder-content" style="padding-left: ${8 + depth * 12}px;">
2728
- ${depth > 0 ? '<span class="ee-folder-indent">└ </span>' : ''}
2729
- <span class="ee-folder-name ${hasChildren ? 'has-children' : ''}">${this.escapeHtml(folder.name)}</span>
2730
- ${folder.status && folder.status.messages > 0 ? `<span class="ee-folder-count">${folder.status.messages}</span>` : ''}
2731
- </div>
2732
- </li>
2733
- `;
2734
- })
3363
+ ${this.buildFolderTree()
3364
+ .map(({ folder, depth }) => this._folderItemHtml(folder, depth))
2735
3365
  .join('')}
2736
3366
  </ul>
2737
3367
  `;
2738
3368
  folderTree.innerHTML = html;
3369
+ }
2739
3370
 
2740
- folderTree.querySelectorAll('.ee-folder-item').forEach(item => {
2741
- item.addEventListener('click', () => {
2742
- const path = item.getAttribute('data-path');
2743
- this._fireAndForget(this.openFolder(path));
2744
- });
2745
- });
3371
+ // One folder row: an icon by special use, the name, and the unread count. The row is a button,
3372
+ // so the folders can be reached and opened from the keyboard.
3373
+ _folderItemHtml(folder, depth) {
3374
+ const active = folder.path === this.currentFolder;
3375
+ const unseen = folder.status && folder.status.unseen > 0 ? folder.status.unseen : 0;
3376
+ const name = folderDisplayName(folder);
3377
+ const label = unseen ? `${name}, ${unseen} unread` : name;
3378
+ return `
3379
+ <li class="ee-folder-item${active ? ' active' : ''}" data-path="${this.escapeHtml(folder.path)}" data-depth="${depth}">
3380
+ <button type="button" class="ee-folder-content" style="padding-left: ${12 + depth * 16}px;" aria-label="${this.escapeHtml(label)}"${active ? ' aria-current="true"' : ''}>
3381
+ <span class="ee-folder-icon">${icon(FOLDER_ICONS[folder.specialUse] || 'folder', 16)}</span>
3382
+ <span class="ee-folder-name">${this.escapeHtml(name)}</span>
3383
+ ${unseen ? `<span class="ee-folder-count">${unseen}</span>` : ''}
3384
+ </button>
3385
+ </li>
3386
+ `;
3387
+ }
3388
+
3389
+ // Keeps a folder's unread count in step with a read state the client changed itself, so the
3390
+ // badge does not wait for the next folder listing
3391
+ _adjustUnseen(path, delta) {
3392
+ const folder = this.folders.find(f => f.path === path);
3393
+ if (!folder || !folder.status || typeof folder.status.unseen !== 'number') {
3394
+ return;
3395
+ }
3396
+ folder.status.unseen = Math.max(0, folder.status.unseen + delta);
3397
+ this.renderFolderList();
3398
+ }
3399
+
3400
+ // Folders whose messages the account sent itself: the list names the recipients instead
3401
+ _isOutgoingFolder(path) {
3402
+ const folder = this.folders.find(f => f.path === path);
3403
+ return !!folder && (folder.specialUse === '\\Sent' || folder.specialUse === '\\Drafts');
3404
+ }
3405
+
3406
+ // The correspondent column of a list row: the sender, or "To: ..." in Sent and Drafts
3407
+ _correspondentHtml(msg, outgoing) {
3408
+ if (outgoing) {
3409
+ const names = addressEntries(msg.to)
3410
+ .concat(addressEntries(msg.cc))
3411
+ .map(entry => entry.name || entry.address);
3412
+ return names.length ? `<span class="ee-message-to-label">To:</span> ${this.escapeHtml(names.join(', '))}` : '(no recipients)';
3413
+ }
3414
+ return this.escapeHtml(msg.from ? msg.from.name || msg.from.address : 'Unknown');
3415
+ }
3416
+
3417
+ _messageItemHtml(msg, outgoing) {
3418
+ const active = msg.id === (this.currentMessage && this.currentMessage.id);
3419
+ const attachments = listedAttachments(msg.attachments).length;
3420
+ const status = msg.unseen ? '<span class="ee-unread-dot" role="img" aria-label="Unread"></span>' : '';
3421
+ return `
3422
+ <button type="button" class="ee-message-item${msg.unseen ? ' unread' : ''}${active ? ' active' : ''}" data-id="${this.escapeHtml(msg.id)}"${active ? ' aria-current="true"' : ''}>
3423
+ <span class="ee-message-header">
3424
+ ${status}
3425
+ <span class="ee-message-from">${this._correspondentHtml(msg, outgoing)}</span>
3426
+ <span class="ee-message-date">${this.formatDate(msg.date)}</span>
3427
+ </span>
3428
+ <span class="ee-message-subject">
3429
+ ${this._responseMarkers(msg)}
3430
+ <span class="ee-message-subject-text">${this.escapeHtml(msg.subject || '(no subject)')}</span>
3431
+ ${attachments ? `<span class="ee-attachment-indicator" role="img" aria-label="${attachments} attachments" title="Attachments">${icon('paperclip', 12)}${attachments}</span>` : ''}
3432
+ </span>
3433
+ ${msg.intro ? `<span class="ee-message-preview">${this.escapeHtml(msg.intro)}</span>` : ''}
3434
+ </button>
3435
+ `;
3436
+ }
3437
+
3438
+ // The bottom bar of the message list: where the page sits in the folder, the page arrows
3439
+ // and the page size
3440
+ _messageListFooter() {
3441
+ const count = this.messages.length;
3442
+ let range = '';
3443
+ if (this.listPosition && count) {
3444
+ const first = this.listPosition.page * this.pageSize + 1;
3445
+ range = `${first}-${first + count - 1} of ${this.listPosition.total}`;
3446
+ }
3447
+ const hasPagination = this.nextPageCursor || this.prevPageCursor;
3448
+ return `
3449
+ <div class="ee-list-footer">
3450
+ <span class="ee-list-range">${range}</span>
3451
+ ${hasPagination ? this._iconButton('prev-page', 'back', 'Previous page', '', !this.prevPageCursor) + this._iconButton('next-page', 'next', 'Next page', '', !this.nextPageCursor) : ''}
3452
+ <label class="ee-page-size-selector" title="Messages per page">
3453
+ <span class="ee-page-size-label">Per page</span>
3454
+ <select class="ee-button ee-page-size-select" data-action="page-size">
3455
+ ${[10, 20, 30, 50, 100].map(size => `<option value="${size}"${this.pageSize === size ? ' selected' : ''}>${size}</option>`).join('')}
3456
+ </select>
3457
+ </label>
3458
+ </div>
3459
+ `;
2746
3460
  }
2747
3461
 
2748
3462
  renderMessageList() {
@@ -2756,61 +3470,18 @@ export class EmailEngineClient {
2756
3470
  }
2757
3471
 
2758
3472
  if (!this.messages.length) {
2759
- messageList.innerHTML = `${this._messageListHeader(this.currentFolder)}<div class="ee-empty-state">No messages</div>`;
3473
+ messageList.innerHTML = `${this._messageListHeader(this.currentFolder)}<div class="ee-empty-state">No messages in this folder</div>`;
2760
3474
  return;
2761
3475
  }
2762
3476
 
2763
- const hasPagination = this.nextPageCursor || this.prevPageCursor;
2764
-
2765
- // Both arrows stay in place once there is more than one page, the unavailable
2766
- // one disabled, so the controls do not shift under the pointer between pages
2767
- const controls = `
2768
- <div class="ee-pagination-controls">
2769
- ${
2770
- hasPagination
2771
- ? `
2772
- ${this._iconButton('prev-page', 'back', 'Previous page', '', !this.prevPageCursor)}
2773
- ${this._iconButton('next-page', 'next', 'Next page', '', !this.nextPageCursor)}
2774
- `
2775
- : ''
2776
- }
2777
- <label class="ee-page-size-selector" title="Messages per page">
2778
- <span class="ee-page-size-label">Show</span>
2779
- <select class="ee-button ee-page-size-select" data-action="page-size">
2780
- <option value="10" ${this.pageSize === 10 ? 'selected' : ''}>10</option>
2781
- <option value="20" ${this.pageSize === 20 ? 'selected' : ''}>20</option>
2782
- <option value="30" ${this.pageSize === 30 ? 'selected' : ''}>30</option>
2783
- <option value="50" ${this.pageSize === 50 ? 'selected' : ''}>50</option>
2784
- <option value="100" ${this.pageSize === 100 ? 'selected' : ''}>100</option>
2785
- </select>
2786
- </label>
2787
- </div>
2788
- `;
2789
-
2790
- const html = `
2791
- ${this._messageListHeader(this.currentFolder, controls)}
3477
+ const outgoing = this._isOutgoingFolder(this.currentFolder);
3478
+ messageList.innerHTML = `
3479
+ ${this._messageListHeader(this.currentFolder)}
2792
3480
  <div class="ee-message-items">
2793
- ${this.messages
2794
- .map(
2795
- msg => `
2796
- <div class="ee-message-item ${msg.unseen ? 'unread' : ''} ${msg.id === (this.currentMessage && this.currentMessage.id) ? 'active' : ''}" data-id="${this.escapeHtml(msg.id)}">
2797
- <div class="ee-message-header">
2798
- <span class="ee-message-from">${this.escapeHtml(msg.from ? msg.from.name || msg.from.address : 'Unknown')}</span>
2799
- <span class="ee-message-date">${this.formatDate(msg.date)}</span>
2800
- </div>
2801
- <div class="ee-message-subject">
2802
- ${this._responseMarkers(msg)}
2803
- <span class="ee-message-subject-text">${this.escapeHtml(msg.subject || '(no subject)')}</span>
2804
- ${msg.attachments && msg.attachments.length > 0 ? `<span class="ee-attachment-indicator" title="Attachments">${icon('paperclip', 12)}${msg.attachments.length}</span>` : ''}
2805
- </div>
2806
- <div class="ee-message-preview">${this.escapeHtml(msg.intro || '')}</div>
2807
- </div>
2808
- `
2809
- )
2810
- .join('')}
3481
+ ${this.messages.map(msg => this._messageItemHtml(msg, outgoing)).join('')}
2811
3482
  </div>
3483
+ ${this._messageListFooter()}
2812
3484
  `;
2813
- messageList.innerHTML = html;
2814
3485
 
2815
3486
  messageList.querySelectorAll('.ee-message-item').forEach(item => {
2816
3487
  item.addEventListener('click', () => {
@@ -2878,7 +3549,7 @@ export class EmailEngineClient {
2878
3549
  ${this._toolbarButton('forward', 'forward', 'Forward', 'Forward this message', 'ee-label-priority')}
2879
3550
  <span class="ee-toolbar-divider"></span>`;
2880
3551
  const actions = `
2881
- ${isDraft ? this._toolbarButton('send-draft', 'send', 'Send draft', 'Send this draft now', 'ee-button-primary ee-keep-label') : respond}
3552
+ ${isDraft ? this._toolbarButton('edit-draft', 'compose', 'Edit', 'Continue writing this draft', 'ee-button-primary ee-keep-label') + this._toolbarButton('send-draft', 'send', 'Send draft', 'Send this draft as it is', 'ee-label-priority') : respond}
2882
3553
  ${this._toolbarButton('toggle-read', isUnseen ? 'mailOpen' : 'mail', isUnseen ? 'Mark read' : 'Mark unread', isUnseen ? 'Mark as read' : 'Mark as unread')}
2883
3554
  <span class="ee-button ee-move-button" title="Move to folder">
2884
3555
  ${icon('move')}<span class="ee-button-label">Move</span>${icon('chevronDown', 12)}
@@ -2928,28 +3599,7 @@ export class EmailEngineClient {
2928
3599
  </div>
2929
3600
  ${this.renderOtpBox(msg.otp)}
2930
3601
  <div class="ee-message-body"></div>
2931
- ${
2932
- msg.attachments && msg.attachments.length > 0
2933
- ? `
2934
- <div class="ee-attachments">
2935
- <div class="ee-attachments-title">Attachments (${msg.attachments.length})</div>
2936
- ${msg.attachments
2937
- .map(
2938
- att => `
2939
- <div class="ee-attachment-item" data-attachment-id="${this.escapeHtml(att.id)}">
2940
- <div class="ee-attachment-icon">${icon('paperclip', 18)}</div>
2941
- <div class="ee-attachment-info">
2942
- <div class="ee-attachment-name">${this.escapeHtml(att.filename || 'Unnamed attachment')}</div>
2943
- ${att.size ? `<div class="ee-attachment-size">${this.formatFileSize(att.size)}</div>` : ''}
2944
- </div>
2945
- </div>
2946
- `
2947
- )
2948
- .join('')}
2949
- </div>
2950
- `
2951
- : ''
2952
- }
3602
+ ${this._attachmentsHtml(listedAttachments(msg.attachments))}
2953
3603
  </div>
2954
3604
  `;
2955
3605
  viewer.innerHTML = html;
@@ -2994,6 +3644,13 @@ export class EmailEngineClient {
2994
3644
  });
2995
3645
  }
2996
3646
 
3647
+ const editDraftButton = viewer.querySelector('[data-action="edit-draft"]');
3648
+ if (editDraftButton) {
3649
+ editDraftButton.addEventListener('click', () => {
3650
+ this.editDraft(msg.id).catch(error => this._alertActionFailed(error, 'Failed to open the draft'));
3651
+ });
3652
+ }
3653
+
2997
3654
  viewer.querySelectorAll('[data-action="reply"], [data-action="reply-all"], [data-action="forward"]').forEach(button => {
2998
3655
  button.addEventListener('click', () => {
2999
3656
  this._respond(msg.id, button.dataset.action).catch(error => this._alertActionFailed(error, 'Failed to open the compose form'));
@@ -3060,6 +3717,34 @@ export class EmailEngineClient {
3060
3717
  // Message content scrolling is now handled in loadMessage method
3061
3718
  }
3062
3719
 
3720
+ // The attachments of the open message as download cards: a type label, the name and the size
3721
+ _attachmentsHtml(attachments) {
3722
+ if (!attachments.length) {
3723
+ return '';
3724
+ }
3725
+ const cards = attachments
3726
+ .map(att => {
3727
+ const name = att.filename || 'Unnamed attachment';
3728
+ const size = attachmentSize(att);
3729
+ return `
3730
+ <button type="button" class="ee-attachment-item" data-attachment-id="${this.escapeHtml(att.id)}" aria-label="Download ${this.escapeHtml(name)}" title="Download ${this.escapeHtml(name)}">
3731
+ <span class="ee-attachment-type">${this.escapeHtml(attachmentType(att))}</span>
3732
+ <span class="ee-attachment-info">
3733
+ <span class="ee-attachment-name">${this.escapeHtml(name)}</span>
3734
+ ${size ? `<span class="ee-attachment-size">${this.formatFileSize(size)}</span>` : ''}
3735
+ </span>
3736
+ <span class="ee-attachment-download">${icon('download', 16)}</span>
3737
+ </button>`;
3738
+ })
3739
+ .join('');
3740
+ return `
3741
+ <div class="ee-attachments">
3742
+ <div class="ee-attachments-title">${attachments.length === 1 ? '1 attachment' : `${attachments.length} attachments`}</div>
3743
+ <div class="ee-attachment-grid">${cards}</div>
3744
+ </div>
3745
+ `;
3746
+ }
3747
+
3063
3748
  // Replied / forwarded markers from the flags the server sets on the original once a reply or
3064
3749
  // forward has been delivered (IMAP accounts; Gmail API and MS Graph report neither flag).
3065
3750
  // labelled shows the words next to the icons, otherwise they are the accessible name only.
@@ -3112,6 +3797,12 @@ export class EmailEngineClient {
3112
3797
  }
3113
3798
 
3114
3799
  root.replaceChildren(style, content);
3800
+ // A message that had no HTML of its own: EmailEngine's conversion sets a small fixed font,
3801
+ // and the plain-text rule lets it read at the size of the rest of the client
3802
+ const encodedSize = msg.text && msg.text.encodedSize;
3803
+ if (encodedSize && encodedSize.plain && !encodedSize.html) {
3804
+ content.dataset.plain = 'true';
3805
+ }
3115
3806
  // A message that sets its own colours or backgrounds was designed for a light page;
3116
3807
  // in dark mode its dark text would land on a dark background, or the client's light
3117
3808
  // text on its white tables, so it is shown on a light surface instead (see the
@@ -3172,11 +3863,12 @@ export class EmailEngineClient {
3172
3863
  </div>
3173
3864
  <button type="button" class="ee-compose-button${this.darkMode ? ' ee-dark-mode' : ''}" title="Compose email" aria-label="Compose">${icon('compose', 22)}</button>
3174
3865
  <div class="ee-toast${this.darkMode ? ' ee-dark-mode' : ''}" role="status" aria-live="polite"></div>
3175
- <div class="ee-compose-modal${this.darkMode ? ' ee-dark-mode' : ''}">
3176
- <div class="ee-compose-dialog" role="dialog" aria-modal="true" aria-label="Compose">
3866
+ <div class="ee-compose${this.darkMode ? ' ee-dark-mode' : ''}" hidden>
3867
+ <div class="ee-compose-dialog" role="dialog" aria-modal="false" aria-labelledby="${this._composeId('title')}">
3177
3868
  <div class="ee-compose-header">
3178
- <h3 class="ee-compose-title">${COMPOSE_TITLES.new}</h3>
3179
- <button type="button" class="ee-compose-close" aria-label="Close" title="Close">${icon('close', 18)}</button>
3869
+ <h3 class="ee-compose-title" id="${this._composeId('title')}">${COMPOSE_TITLES.new}</h3>
3870
+ <button type="button" class="ee-compose-window-button" data-action="minimize" aria-label="Minimize" title="Minimize"><span class="ee-when-open">${icon('minimize', 16)}</span><span class="ee-when-minimized">${icon('expand', 16)}</span></button>
3871
+ <button type="button" class="ee-compose-window-button ee-compose-close" data-action="close" aria-label="Close" title="Close">${icon('close', 16)}</button>
3180
3872
  </div>
3181
3873
  <form class="ee-compose-form" novalidate>
3182
3874
  <div class="ee-compose-row">
@@ -3196,33 +3888,48 @@ export class EmailEngineClient {
3196
3888
  <label class="ee-compose-label" for="${this._composeId('subject')}">Subject</label>
3197
3889
  <input type="text" class="ee-compose-input" id="${this._composeId('subject')}" name="subject">
3198
3890
  </div>
3199
- <textarea class="ee-compose-textarea" name="message" aria-label="Message" placeholder="Write your message"></textarea>
3200
- <div class="ee-compose-files">
3201
- <div class="ee-compose-chips"></div>
3202
- <div class="ee-compose-files-row">
3203
- <button type="button" class="ee-compose-attach" data-action="attach">${icon('paperclip', 14)}<span>Attach files</span></button>
3204
- <input type="file" class="ee-compose-file-input" multiple hidden>
3205
- <label class="ee-compose-forward-attachments" hidden>
3206
- <input type="checkbox" name="forwardAttachments" checked>
3207
- <span class="ee-compose-forward-attachments-label"></span>
3208
- </label>
3209
- </div>
3891
+ <div class="ee-compose-toolbar" role="toolbar" aria-label="Formatting">
3892
+ ${this._formatButton('bold', 'bold', 'Bold')}
3893
+ ${this._formatButton('italic', 'italic', 'Italic')}
3894
+ ${this._formatButton('insertUnorderedList', 'list', 'Bulleted list')}
3895
+ ${this._formatButton('insertOrderedList', 'listOrdered', 'Numbered list')}
3896
+ <button type="button" class="ee-compose-format" data-action="link" aria-label="Link" title="Link">${icon('link', 16)}</button>
3210
3897
  </div>
3898
+ <div class="ee-compose-linkbar" hidden>
3899
+ <input type="url" class="ee-compose-input" name="link" aria-label="Link address" placeholder="https://" autocomplete="off">
3900
+ <button type="button" class="ee-compose-small-button" data-action="insert-link">Add link</button>
3901
+ <button type="button" class="ee-compose-small-button" data-action="cancel-link">Cancel</button>
3902
+ </div>
3903
+ <div class="ee-compose-editor" contenteditable="true" role="textbox" aria-multiline="true" aria-label="Message" data-placeholder="Write your message"></div>
3904
+ <div class="ee-compose-chips"></div>
3211
3905
  <div class="ee-compose-quote" hidden>
3212
- <div class="ee-compose-quote-label"></div>
3213
- <div class="ee-compose-quote-frame"></div>
3906
+ <button type="button" class="ee-compose-quote-toggle" aria-expanded="false" title="Show the quoted message">${icon('more', 16)}<span class="ee-compose-quote-toggle-label"></span></button>
3907
+ <div class="ee-compose-quote-content" hidden>
3908
+ <div class="ee-compose-quote-header"></div>
3909
+ <div class="ee-compose-quote-frame"></div>
3910
+ </div>
3214
3911
  </div>
3215
3912
  </form>
3216
3913
  <div class="ee-compose-error" role="alert" hidden></div>
3217
3914
  <div class="ee-compose-actions">
3218
- <button type="button" class="ee-compose-cancel">Cancel</button>
3219
- <button type="button" class="ee-compose-save-draft">Save Draft</button>
3220
3915
  <button type="button" class="ee-compose-send">Send</button>
3916
+ <button type="button" class="ee-compose-icon-button" data-action="attach" aria-label="Attach files" title="Attach files">${icon('paperclip', 18)}</button>
3917
+ <input type="file" class="ee-compose-file-input" multiple hidden>
3918
+ <button type="button" class="ee-compose-save-draft">Save draft</button>
3919
+ <button type="button" class="ee-compose-icon-button" data-action="discard" aria-label="Discard" title="Discard">${icon('trash', 18)}</button>
3221
3920
  </div>
3222
3921
  </div>
3223
3922
  </div>
3224
3923
  `;
3225
3924
 
3925
+ // Folder rows are rebuilt on every count change, so their clicks are taken here once
3926
+ this.container.querySelector('.ee-folder-tree').addEventListener('click', e => {
3927
+ const row = e.target.closest('.ee-folder-content');
3928
+ if (row) {
3929
+ this._fireAndForget(this.openFolder(row.closest('.ee-folder-item').getAttribute('data-path')));
3930
+ }
3931
+ });
3932
+
3226
3933
  // Pane navigation in the single-pane layout, delegated because the panes
3227
3934
  // re-render their headers on every load
3228
3935
  this.container.querySelector('.ee-client').addEventListener('click', e => {
@@ -3248,10 +3955,16 @@ export class EmailEngineClient {
3248
3955
  return `${this._composeIdPrefix}-${field}`;
3249
3956
  }
3250
3957
 
3251
- // Opens a blank compose form, optionally prefilled: { to, cc, bcc, subject, text }. The
3252
- // address fields take a string or address entries.
3958
+ // A formatting toolbar button. Static arguments only, never message data.
3959
+ _formatButton(command, iconName, label) {
3960
+ return `<button type="button" class="ee-compose-format" data-command="${command}" aria-label="${label}" title="${label}" aria-pressed="false">${icon(iconName, 16)}</button>`;
3961
+ }
3962
+
3963
+ // Opens a blank compose form, optionally prefilled: { to, cc, bcc, subject, text, html }. The
3964
+ // address fields take a string or address entries; html is filtered to what the editor keeps.
3965
+ // Resolves false when the user kept an unsaved message open instead.
3253
3966
  compose(prefill = {}) {
3254
- this._openCompose({ mode: 'new', ...prefill });
3967
+ return this._openCompose({ ...prefill, mode: 'new' });
3255
3968
  }
3256
3969
 
3257
3970
  // Opens the compose form as a reply to a message (the open one when messageId is omitted)
@@ -3279,62 +3992,182 @@ export class EmailEngineClient {
3279
3992
  )
3280
3993
  ]);
3281
3994
 
3282
- this._openCompose({ mode: action, original: msg, ...this.prepareResponse(msg, action, ownAddress) });
3995
+ return this._openCompose({ mode: action, original: msg, ...this.prepareResponse(msg, action, ownAddress) });
3996
+ }
3997
+
3998
+ /**
3999
+ * Opens a stored draft in the compose form (the open message when messageId is omitted).
4000
+ * Saving replaces the stored draft, sending removes it. The draft's HTML is filtered to what
4001
+ * the editor keeps, so a quote keeps its paragraphs, emphasis and quote bars but not a layout
4002
+ * of its own; its files come along as attachments.
4003
+ *
4004
+ * @param {string} [messageId]
4005
+ * @returns {Promise<boolean>} false when the user kept another unsaved message open instead
4006
+ */
4007
+ async editDraft(messageId = null) {
4008
+ const id = messageId || (this.currentMessage && this.currentMessage.id);
4009
+ if (!id) {
4010
+ throw new Error('No draft to edit');
4011
+ }
4012
+ const msg = await this.apiRequest('GET', this._messagePath(id, '?textType=*'));
4013
+ const text = msg.text || {};
4014
+ return this._openCompose({
4015
+ mode: 'draft',
4016
+ to: msg.to,
4017
+ cc: msg.cc,
4018
+ bcc: msg.bcc,
4019
+ subject: msg.subject || '',
4020
+ html: text.html || textToEditorHtml(text.plain || ''),
4021
+ attachments: listedAttachments(msg.attachments).map(referenceAttachment),
4022
+ headers: threadingHeaders(msg),
4023
+ draftId: id
4024
+ });
3283
4025
  }
3284
4026
 
3285
- _openCompose({ mode = 'new', to, cc, bcc, subject, text, reference = null, original = null } = {}) {
4027
+ async _openCompose(state = {}) {
3286
4028
  const els = this._compose && this._compose.els;
3287
4029
  if (!els) {
3288
4030
  throw new Error('The compose form needs the client UI (a container)');
3289
4031
  }
4032
+ if (!(await this._settleOpenCompose())) {
4033
+ return false;
4034
+ }
4035
+ this._fillCompose(state);
4036
+ this._showCompose();
4037
+ return true;
4038
+ }
4039
+
4040
+ // Puts a compose state into the form: fields, editor content, attachments and the quote
4041
+ _fillCompose({ mode = 'new', to, cc, bcc, subject, text, html, reference = null, original = null, attachments = [], headers = null, draftId = null }) {
3290
4042
  this._resetCompose();
3291
- this._compose.reference = reference;
4043
+ const { els } = this._compose;
4044
+ Object.assign(this._compose, {
4045
+ mode,
4046
+ reference,
4047
+ original,
4048
+ headers,
4049
+ draftId,
4050
+ files: (attachments || []).filter(att => att && att.reference).map(att => ({ ...att, kind: 'reference' }))
4051
+ });
3292
4052
 
3293
4053
  const asField = value => (typeof value === 'string' ? value : this.formatAddressList(value));
3294
- const { form } = els;
4054
+ const { form, editor } = els;
3295
4055
  form.elements.to.value = asField(to);
3296
4056
  form.elements.cc.value = asField(cc);
3297
4057
  form.elements.bcc.value = asField(bcc);
3298
4058
  form.elements.subject.value = subject || '';
3299
- form.elements.message.value = text || '';
4059
+ editor.innerHTML = html ? sanitizeEditorHtml(html) : textToEditorHtml(text || '');
4060
+ this._updateEditorEmpty();
3300
4061
  this._showCopyFields({ cc: !!form.elements.cc.value, bcc: !!form.elements.bcc.value });
3301
4062
 
3302
4063
  els.title.textContent = COMPOSE_TITLES[mode] || COMPOSE_TITLES.new;
3303
-
3304
- // The server carries the original's attachments over on request (all or none)
3305
- const originalAttachments = original && mode === 'forward' ? (original.attachments || []).filter(att => !att.inline && !att.embedded) : [];
3306
- els.forwardAttachments.hidden = !originalAttachments.length;
3307
- els.forwardAttachments.querySelector('.ee-compose-forward-attachments-label').textContent =
3308
- `Include the original attachments (${originalAttachments.length})`;
3309
-
3310
4064
  if (original && reference && reference.inline) {
3311
4065
  this._renderComposeQuote(original, mode);
3312
4066
  }
4067
+ this._renderComposeChips();
4068
+ this._compose.snapshot = this._composeSnapshot();
4069
+ }
3313
4070
 
3314
- els.modal.classList.add('show');
3315
- const focusTarget = form.elements.to.value ? form.elements.message : form.elements.to;
3316
- setTimeout(() => {
3317
- focusTarget.focus();
3318
- if (focusTarget === form.elements.message) {
3319
- focusTarget.setSelectionRange(0, 0);
3320
- }
3321
- }, 100);
4071
+ _showCompose() {
4072
+ const { els } = this._compose;
4073
+ els.root.hidden = false;
4074
+ this._setComposeMinimized(false);
4075
+ const { form, editor } = els;
4076
+ if (form.elements.to.value) {
4077
+ editor.focus();
4078
+ placeCaretAtStart(editor);
4079
+ } else {
4080
+ form.elements.to.focus();
4081
+ }
4082
+ }
4083
+
4084
+ _isComposeOpen() {
4085
+ return !!(this._compose && this._compose.els && !this._compose.els.root.hidden);
3322
4086
  }
3323
4087
 
3324
- // A read-only copy of the message being answered, under the textarea. The quote that is sent
3325
- // is built by the server from the stored original; this shows what it will contain.
4088
+ // What the form holds, to tell whether anything changed since it was opened
4089
+ _composeSnapshot() {
4090
+ const { form, editor } = this._compose.els;
4091
+ return JSON.stringify([
4092
+ ['to', 'cc', 'bcc', 'subject'].map(key => form.elements[key].value),
4093
+ editor.innerHTML,
4094
+ this._compose.files.map(entry => (entry.kind === 'reference' ? entry.reference : entry.file.name))
4095
+ ]);
4096
+ }
4097
+
4098
+ _isComposeDirty() {
4099
+ return this._isComposeOpen() && this._compose.snapshot !== this._composeSnapshot();
4100
+ }
4101
+
4102
+ // Before the form is closed or reused: a changed message is saved as a draft or discarded, as
4103
+ // the user chooses. Resolves false when saving failed, so the message stays on screen.
4104
+ async _settleOpenCompose() {
4105
+ if (!this._isComposeDirty()) {
4106
+ return true;
4107
+ }
4108
+ this._setComposeMinimized(false);
4109
+ const save = await this.confirmMethod('Save the message you are writing as a draft?', 'Unsaved message', 'Discard', 'Save draft');
4110
+ if (!save) {
4111
+ return true;
4112
+ }
4113
+ return this._saveComposeDraft();
4114
+ }
4115
+
4116
+ // Closes the form, asking first when it holds unsaved changes
4117
+ async _requestCloseCompose() {
4118
+ if (await this._settleOpenCompose()) {
4119
+ this._closeCompose();
4120
+ }
4121
+ }
4122
+
4123
+ _setComposeMinimized(minimized) {
4124
+ const { dialog, minimizeButton } = this._compose.els;
4125
+ dialog.classList.toggle('minimized', minimized);
4126
+ const label = minimized ? 'Restore' : 'Minimize';
4127
+ minimizeButton.setAttribute('aria-label', label);
4128
+ minimizeButton.title = label;
4129
+ }
4130
+
4131
+ // The message being answered or forwarded, read-only under the editor. The quote that is sent
4132
+ // is built by the server from the stored original; this shows what it will contain. A reply's
4133
+ // quote starts folded, a forward's open, with the forwarded message's own header above it.
3326
4134
  _renderComposeQuote(original, mode) {
3327
4135
  const { quote } = this._compose.els;
3328
- const from = addressEntries(original.from)[0];
3329
- const sender = from ? from.name || from.address : 'the sender';
3330
- quote.querySelector('.ee-compose-quote-label').textContent =
3331
- mode === 'forward' ? 'The forwarded message is added below your text:' : `${sender}'s message is quoted below your reply:`;
4136
+ const forward = mode === 'forward';
4137
+ quote.querySelector('.ee-compose-quote-header').innerHTML = forward ? this._forwardHeaderHtml(original) : '';
3332
4138
  // A shadow root cannot be attached twice, so each quote gets a fresh host
3333
4139
  const host = document.createElement('div');
3334
4140
  host.className = 'ee-compose-quote-body';
3335
4141
  quote.querySelector('.ee-compose-quote-frame').replaceChildren(host);
3336
4142
  this._labelCollapsedThreads(this._renderMessageBody(host, original));
3337
4143
  quote.hidden = false;
4144
+ this._setQuoteExpanded(forward);
4145
+ }
4146
+
4147
+ _setQuoteExpanded(expanded) {
4148
+ const { quote } = this._compose.els;
4149
+ const toggle = quote.querySelector('.ee-compose-quote-toggle');
4150
+ const forward = this._compose.mode === 'forward';
4151
+ toggle.setAttribute('aria-expanded', String(expanded));
4152
+ const label = `${expanded ? 'Hide' : 'Show'} ${forward ? 'forwarded message' : 'quoted text'}`;
4153
+ toggle.title = label;
4154
+ toggle.querySelector('.ee-compose-quote-toggle-label').textContent = label;
4155
+ quote.querySelector('.ee-compose-quote-content').hidden = !expanded;
4156
+ }
4157
+
4158
+ // The header of a forwarded message, as the server adds it to the sent message
4159
+ _forwardHeaderHtml(original) {
4160
+ const rows = [
4161
+ ['From', this._addressListHtml(original.from)],
4162
+ ['Date', this.escapeHtml(this.formatFullDate(original.date))],
4163
+ ['Subject', this.escapeHtml(original.subject || '(no subject)')],
4164
+ ['To', this._addressListHtml(original.to)],
4165
+ ['Cc', this._addressListHtml(original.cc)]
4166
+ ].filter(([, value]) => value);
4167
+ return `
4168
+ <div class="ee-forward-title">Forwarded message</div>
4169
+ ${rows.map(([label, value]) => `<div class="ee-forward-row"><span class="ee-forward-label">${label}</span><span>${value}</span></div>`).join('')}
4170
+ `;
3338
4171
  }
3339
4172
 
3340
4173
  // Shows the Cc and Bcc fields named true and hides the rest; the link offers whichever is hidden
@@ -3356,19 +4189,21 @@ export class EmailEngineClient {
3356
4189
  _resetCompose() {
3357
4190
  const { els } = this._compose;
3358
4191
  els.form.reset();
4192
+ els.editor.replaceChildren();
3359
4193
  els.chips.replaceChildren();
3360
4194
  els.fileInput.value = '';
3361
- els.forwardAttachments.hidden = true;
4195
+ els.linkbar.hidden = true;
3362
4196
  els.quote.hidden = true;
4197
+ els.quote.querySelector('.ee-compose-quote-header').replaceChildren();
3363
4198
  els.quote.querySelector('.ee-compose-quote-frame').replaceChildren();
3364
4199
  this._clearComposeError();
3365
- this._compose = { els, reference: null, files: [] };
4200
+ this._compose = { els, mode: 'new', reference: null, original: null, headers: null, draftId: null, files: [], snapshot: null };
3366
4201
  this._showCopyFields({ cc: false, bcc: false });
3367
4202
  }
3368
4203
 
3369
4204
  _closeCompose() {
3370
4205
  if (this._compose && this._compose.els) {
3371
- this._compose.els.modal.classList.remove('show');
4206
+ this._compose.els.root.hidden = true;
3372
4207
  this._resetCompose();
3373
4208
  }
3374
4209
  }
@@ -3376,11 +4211,11 @@ export class EmailEngineClient {
3376
4211
  // Shows why the form cannot go out, inside the form itself, and marks the field it is about.
3377
4212
  // The message stays until the form is changed or closed.
3378
4213
  _showComposeError(message, field = null) {
3379
- const { form, error } = this._compose.els;
4214
+ const { form, error, editor } = this._compose.els;
3380
4215
  this._clearComposeError();
3381
4216
  error.textContent = message;
3382
4217
  error.hidden = false;
3383
- const input = field ? form.elements[field] : null;
4218
+ const input = field === 'message' ? editor : field ? form.elements[field] : null;
3384
4219
  if (input) {
3385
4220
  input.setAttribute('aria-invalid', 'true');
3386
4221
  input.focus();
@@ -3388,22 +4223,26 @@ export class EmailEngineClient {
3388
4223
  }
3389
4224
 
3390
4225
  _clearComposeError() {
3391
- const { form, error } = this._compose.els;
4226
+ const { dialog, error } = this._compose.els;
3392
4227
  error.hidden = true;
3393
- form.querySelectorAll('[aria-invalid]').forEach(input => input.removeAttribute('aria-invalid'));
4228
+ dialog.querySelectorAll('[aria-invalid]').forEach(input => input.removeAttribute('aria-invalid'));
3394
4229
  }
3395
4230
 
4231
+ // Attachment chips: picked files, and the original's files of a forward or the files of a
4232
+ // reopened draft, which travel as references. Each can be removed.
3396
4233
  _renderComposeChips() {
3397
4234
  this._compose.els.chips.innerHTML = this._compose.files
3398
- .map(
3399
- (file, index) => `
4235
+ .map((entry, index) => {
4236
+ const name = entry.kind === 'reference' ? entry.filename || 'Unnamed attachment' : entry.file.name;
4237
+ const size = entry.kind === 'reference' ? entry.size : entry.file.size;
4238
+ return `
3400
4239
  <span class="ee-compose-chip">
3401
4240
  ${icon('paperclip', 12)}
3402
- <span class="ee-compose-chip-name">${this.escapeHtml(file.name)}</span>
3403
- <span class="ee-compose-chip-size">${this.formatFileSize(file.size)}</span>
3404
- <button type="button" class="ee-compose-chip-remove" data-index="${index}" aria-label="Remove ${this.escapeHtml(file.name)}" title="Remove">${icon('close', 12)}</button>
3405
- </span>`
3406
- )
4241
+ <span class="ee-compose-chip-name">${this.escapeHtml(name)}</span>
4242
+ ${size ? `<span class="ee-compose-chip-size">${this.formatFileSize(size)}</span>` : ''}
4243
+ <button type="button" class="ee-compose-chip-remove" data-index="${index}" aria-label="Remove ${this.escapeHtml(name)}" title="Remove">${icon('close', 12)}</button>
4244
+ </span>`;
4245
+ })
3407
4246
  .join('');
3408
4247
  }
3409
4248
 
@@ -3420,9 +4259,10 @@ export class EmailEngineClient {
3420
4259
  }
3421
4260
 
3422
4261
  // Takes picked files into the form within the size limit. They are kept as File objects and
3423
- // read only when the message is sent, so a removed file is never read at all.
4262
+ // read only when the message is sent, so a removed file is never read at all. Files of the
4263
+ // original travel as references and do not count against the limit.
3424
4264
  _addComposeFiles(files) {
3425
- let total = this._compose.files.reduce((sum, file) => sum + file.size, 0);
4265
+ let total = this._compose.files.reduce((sum, entry) => sum + (entry.kind === 'file' ? entry.file.size : 0), 0);
3426
4266
  const skipped = [];
3427
4267
  for (const file of files) {
3428
4268
  if (total + file.size > this.maxAttachmentSize) {
@@ -3430,7 +4270,7 @@ export class EmailEngineClient {
3430
4270
  continue;
3431
4271
  }
3432
4272
  total += file.size;
3433
- this._compose.files.push(file);
4273
+ this._compose.files.push({ kind: 'file', file });
3434
4274
  }
3435
4275
  this._renderComposeChips();
3436
4276
  if (skipped.length) {
@@ -3440,19 +4280,25 @@ export class EmailEngineClient {
3440
4280
 
3441
4281
  _readComposeAttachments(files) {
3442
4282
  return Promise.all(
3443
- files.map(async file => ({
3444
- filename: file.name,
3445
- contentType: file.type || 'application/octet-stream',
3446
- content: await this._readFileAsBase64(file)
3447
- }))
4283
+ // a reference entry goes as it is; attachmentPayload keeps only the fields it sends
4284
+ files.map(async entry =>
4285
+ entry.kind === 'reference'
4286
+ ? entry
4287
+ : {
4288
+ filename: entry.file.name,
4289
+ contentType: entry.file.type || 'application/octet-stream',
4290
+ content: await this._readFileAsBase64(entry.file)
4291
+ }
4292
+ )
3448
4293
  );
3449
4294
  }
3450
4295
 
3451
- // The form as a submission: parsed recipients, the text, the reference and the picked files,
3452
- // plus the first reason it cannot go out as asked (null when it can). requireMessage applies
3453
- // the send rules: a recipient, and some text unless the message is a forward.
4296
+ // The form as a message object, plus the first reason it cannot go out as asked (null when it
4297
+ // can). requireMessage applies the send rules: a recipient, and some text unless the message
4298
+ // is a forward.
3454
4299
  _readComposeForm(requireMessage) {
3455
- const { form } = this._compose.els;
4300
+ const { form, editor } = this._compose.els;
4301
+ const { reference, headers } = this._compose;
3456
4302
  const fields = {};
3457
4303
  const invalid = [];
3458
4304
  for (const key of ['to', 'cc', 'bcc']) {
@@ -3460,41 +4306,34 @@ export class EmailEngineClient {
3460
4306
  invalid.push(...fields[key].filter(entry => !ADDRESS_PATTERN.test(entry.address)).map(entry => entry.address || entry.name));
3461
4307
  }
3462
4308
 
3463
- let reference = this._compose.reference;
3464
- const isForward = !!reference && reference.action === 'forward';
3465
- if (isForward) {
3466
- reference = { ...reference, forwardAttachments: form.elements.forwardAttachments.checked };
3467
- }
4309
+ const text = editorText(editor);
4310
+ const html = text ? sanitizeEditorHtml(editor.innerHTML) : '';
3468
4311
 
3469
- const draft = {
3470
- to: fields.to,
3471
- subject: form.elements.subject.value.trim(),
3472
- text: form.elements.message.value,
3473
- files: this._compose.files,
3474
- options: { cc: fields.cc, bcc: fields.bcc, reference }
3475
- };
4312
+ const message = { to: fields.to, cc: fields.cc, bcc: fields.bcc, subject: form.elements.subject.value.trim(), text, html, reference, headers };
4313
+ const isForward = !!reference && reference.action === 'forward';
4314
+ const empty = !fields.to.length && !fields.cc.length && !fields.bcc.length && !message.subject && !text && !this._compose.files.length && !reference;
3476
4315
 
3477
- const empty = !fields.to.length && !fields.cc.length && !fields.bcc.length && !draft.subject && !draft.text.trim() && !draft.files.length && !reference;
4316
+ let problem = null;
3478
4317
  if (requireMessage && !fields.to.length) {
3479
- draft.problem = { message: 'Add at least one recipient.', field: 'to' };
4318
+ problem = { message: 'Add at least one recipient.', field: 'to' };
3480
4319
  } else if (!requireMessage && empty) {
3481
- draft.problem = { message: 'Nothing to save - fill in at least one field first.', field: 'to' };
4320
+ problem = { message: 'Nothing to save - fill in at least one field first.', field: 'to' };
3482
4321
  } else if (invalid.length) {
3483
- draft.problem = { message: `Not a valid email address: ${invalid.join(', ')}`, field: 'to' };
3484
- } else if (requireMessage && !draft.text.trim() && !isForward) {
4322
+ problem = { message: `Not a valid email address: ${invalid.join(', ')}`, field: 'to' };
4323
+ } else if (requireMessage && !text && !isForward) {
3485
4324
  // A forward can go without a note of its own; anything else needs some text
3486
- draft.problem = { message: 'Write a message before sending.', field: 'message' };
4325
+ problem = { message: 'Write a message before sending.', field: 'message' };
3487
4326
  }
3488
- return draft;
4327
+ return { message, problem };
3489
4328
  }
3490
4329
 
3491
4330
  // Runs a compose request with its button showing progress. The form is checked first, the
3492
4331
  // picked files are read, and on success the form closes and the result is returned; on any
3493
4332
  // failure the reason is shown over the form, kept as it was, and the result is null.
3494
4333
  async _runComposeAction(button, busyText, errorTitle, requireMessage, submit) {
3495
- const draft = this._readComposeForm(requireMessage);
3496
- if (draft.problem) {
3497
- this._showComposeError(draft.problem.message, draft.problem.field);
4334
+ const { message, problem } = this._readComposeForm(requireMessage);
4335
+ if (problem) {
4336
+ this._showComposeError(problem.message, problem.field);
3498
4337
  return null;
3499
4338
  }
3500
4339
  this._clearComposeError();
@@ -3503,8 +4342,8 @@ export class EmailEngineClient {
3503
4342
  button.disabled = true;
3504
4343
  button.textContent = busyText;
3505
4344
  try {
3506
- const attachments = await this._readComposeAttachments(draft.files);
3507
- const result = await submit(draft.to, draft.subject, draft.text, { ...draft.options, attachments });
4345
+ message.attachments = await this._readComposeAttachments(this._compose.files);
4346
+ const result = await submit(message);
3508
4347
  this._closeCompose();
3509
4348
  return result || {};
3510
4349
  } catch (error) {
@@ -3517,61 +4356,298 @@ export class EmailEngineClient {
3517
4356
  }
3518
4357
  }
3519
4358
 
4359
+ // Saves the form as a draft, replacing the stored draft it was opened from. Resolves whether
4360
+ // it was saved; on failure the form stays open with the reason.
4361
+ async _saveComposeDraft() {
4362
+ const { draftId, els } = this._compose;
4363
+ const response = await this._runComposeAction(els.saveDraftButton, 'Saving...', 'Could not save the draft', false, message =>
4364
+ draftId ? this.updateDraft(draftId, message) : this.saveDraft(message)
4365
+ );
4366
+ if (!response) {
4367
+ return false;
4368
+ }
4369
+ this.notify('Draft saved.');
4370
+ this._afterDraftChange(draftId, response.path);
4371
+ return true;
4372
+ }
4373
+
4374
+ // Brings the list and viewer up to date after a draft was saved, replaced or sent
4375
+ _afterDraftChange(oldDraftId, draftsPath) {
4376
+ if (this._destroyed) {
4377
+ return;
4378
+ }
4379
+ if (oldDraftId && this.currentMessage && this.currentMessage.id === oldDraftId) {
4380
+ this.currentMessage = null;
4381
+ this.renderMessage();
4382
+ this._notifyNavigate();
4383
+ }
4384
+ if (this.currentFolder && (this.currentFolder === draftsPath || this._isOutgoingFolder(this.currentFolder))) {
4385
+ this._fireAndForget(this.loadMessages(this.currentFolder));
4386
+ }
4387
+ }
4388
+
4389
+ async _sendCompose() {
4390
+ const { draftId, els } = this._compose;
4391
+ const response = await this._runComposeAction(els.sendButton, 'Sending...', 'Could not send the message', true, message => this.sendMessage(message));
4392
+ if (!response) {
4393
+ return;
4394
+ }
4395
+ // Submitting only queues the message; delivery happens afterwards and can still fail
4396
+ this.notify('Message queued for delivery.');
4397
+ if (draftId) {
4398
+ await this._discardDraft(draftId);
4399
+ this._afterDraftChange(draftId, null);
4400
+ }
4401
+ }
4402
+
4403
+ async _discardCompose() {
4404
+ if (this._isComposeDirty()) {
4405
+ const discard = await this.confirmMethod('Discard this message?', 'Discard message', 'Cancel', 'Discard');
4406
+ if (!discard) {
4407
+ return;
4408
+ }
4409
+ }
4410
+ this._closeCompose();
4411
+ }
4412
+
4413
+ // The placeholder shows while the editor holds no text
4414
+ _updateEditorEmpty() {
4415
+ const { editor } = this._compose.els;
4416
+ editor.classList.toggle('ee-empty', !editor.textContent.trim() && !editor.querySelector('li, blockquote'));
4417
+ }
4418
+
4419
+ // Marks the toolbar buttons whose format applies at the caret
4420
+ _updateFormatButtons() {
4421
+ const { editor, formatButtons } = this._compose.els;
4422
+ if (typeof document.queryCommandState !== 'function' || !editor.contains(document.activeElement)) {
4423
+ return;
4424
+ }
4425
+ for (const button of formatButtons) {
4426
+ let state = false;
4427
+ try {
4428
+ state = document.queryCommandState(button.dataset.command);
4429
+ } catch {
4430
+ // not supported
4431
+ }
4432
+ button.setAttribute('aria-pressed', String(state));
4433
+ }
4434
+ }
4435
+
4436
+ _openLinkbar() {
4437
+ const { editor, linkbar } = this._compose.els;
4438
+ const selection = window.getSelection();
4439
+ const range = selection && selection.rangeCount ? selection.getRangeAt(0) : null;
4440
+ this._compose.linkRange = range && editor.contains(range.commonAncestorContainer) ? range.cloneRange() : null;
4441
+ const input = linkbar.querySelector('[name="link"]');
4442
+ input.value = '';
4443
+ linkbar.hidden = false;
4444
+ input.focus();
4445
+ }
4446
+
4447
+ // Hides the link field and puts the selection back where it was in the editor
4448
+ _closeLinkbar() {
4449
+ const { editor, linkbar } = this._compose.els;
4450
+ linkbar.hidden = true;
4451
+ editor.focus();
4452
+ const range = this._compose.linkRange;
4453
+ if (range) {
4454
+ const selection = window.getSelection();
4455
+ selection.removeAllRanges();
4456
+ selection.addRange(range);
4457
+ }
4458
+ }
4459
+
4460
+ // Turns the selection into a link, or inserts the address as one at the caret. Only http(s)
4461
+ // and mailto addresses are taken; a bare host gets https://.
4462
+ _insertLink() {
4463
+ const { linkbar } = this._compose.els;
4464
+ const input = linkbar.querySelector('[name="link"]');
4465
+ let url = input.value.trim();
4466
+ if (!url) {
4467
+ this._closeLinkbar();
4468
+ return;
4469
+ }
4470
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) {
4471
+ url = url.includes('@') && !url.includes('/') ? `mailto:${url}` : `https://${url}`;
4472
+ }
4473
+ if (!SAFE_LINK.test(url)) {
4474
+ this._showComposeError('Links must start with http://, https:// or mailto:');
4475
+ input.focus();
4476
+ return;
4477
+ }
4478
+ this._closeLinkbar();
4479
+ const range = this._compose.linkRange;
4480
+ if (!range || range.collapsed) {
4481
+ const label = url.replace(/^mailto:/i, '');
4482
+ document.execCommand('insertHTML', false, `<a href="${this.escapeHtml(url)}">${this.escapeHtml(label)}</a>`);
4483
+ } else {
4484
+ document.execCommand('createLink', false, url);
4485
+ }
4486
+ this._updateEditorEmpty();
4487
+ }
4488
+
4489
+ // Pasted and dropped content goes through the editor's filter; files become attachments
4490
+ _onEditorPaste(e) {
4491
+ const data = e.clipboardData;
4492
+ if (!data) {
4493
+ return;
4494
+ }
4495
+ e.preventDefault();
4496
+ const html = data.getData('text/html');
4497
+ const text = data.getData('text/plain');
4498
+ if (html) {
4499
+ document.execCommand('insertHTML', false, sanitizeEditorHtml(html));
4500
+ } else if (text) {
4501
+ document.execCommand('insertText', false, text);
4502
+ } else if (data.files && data.files.length) {
4503
+ this._addComposeFiles(Array.from(data.files));
4504
+ }
4505
+ this._updateEditorEmpty();
4506
+ }
4507
+
3520
4508
  setupComposeModal() {
3521
4509
  if (typeof document === 'undefined' || !this.container) {
3522
4510
  return;
3523
4511
  }
3524
4512
 
3525
- const modal = this.container.querySelector('.ee-compose-modal');
4513
+ const root = this.container.querySelector('.ee-compose');
4514
+ const dialog = root.querySelector('.ee-compose-dialog');
3526
4515
  const els = {
3527
- modal,
3528
- form: modal.querySelector('.ee-compose-form'),
3529
- title: modal.querySelector('.ee-compose-title'),
3530
- chips: modal.querySelector('.ee-compose-chips'),
3531
- fileInput: modal.querySelector('.ee-compose-file-input'),
3532
- forwardAttachments: modal.querySelector('.ee-compose-forward-attachments'),
3533
- quote: modal.querySelector('.ee-compose-quote'),
3534
- error: modal.querySelector('.ee-compose-error')
4516
+ root,
4517
+ dialog,
4518
+ form: dialog.querySelector('.ee-compose-form'),
4519
+ title: dialog.querySelector('.ee-compose-title'),
4520
+ editor: dialog.querySelector('.ee-compose-editor'),
4521
+ toolbar: dialog.querySelector('.ee-compose-toolbar'),
4522
+ formatButtons: Array.from(dialog.querySelectorAll('.ee-compose-format[data-command]')),
4523
+ linkbar: dialog.querySelector('.ee-compose-linkbar'),
4524
+ chips: dialog.querySelector('.ee-compose-chips'),
4525
+ fileInput: dialog.querySelector('.ee-compose-file-input'),
4526
+ quote: dialog.querySelector('.ee-compose-quote'),
4527
+ error: dialog.querySelector('.ee-compose-error'),
4528
+ sendButton: dialog.querySelector('.ee-compose-send'),
4529
+ saveDraftButton: dialog.querySelector('.ee-compose-save-draft'),
4530
+ minimizeButton: dialog.querySelector('[data-action="minimize"]')
3535
4531
  };
3536
- const { form, fileInput, chips } = els;
3537
- this._compose = { els, reference: null, files: [] };
4532
+ this._compose = { els };
4533
+ this._resetCompose();
3538
4534
 
3539
4535
  this.container
3540
4536
  .querySelectorAll('.ee-compose-button, .ee-sidebar-compose-button')
3541
- .forEach(button => button.addEventListener('click', () => this.compose()));
4537
+ .forEach(button => button.addEventListener('click', () => this._composeFailSafe(this.compose())));
4538
+
4539
+ this._bindComposeWindow(els);
4540
+ this._bindComposeEditor(els);
4541
+ this._bindComposeFields(els);
4542
+ }
3542
4543
 
3543
- const closeCompose = () => this._closeCompose();
3544
- modal.querySelector('.ee-compose-close').addEventListener('click', closeCompose);
3545
- modal.querySelector('.ee-compose-cancel').addEventListener('click', closeCompose);
4544
+ // A compose action started from a click has no caller to report to
4545
+ _composeFailSafe(promise) {
4546
+ return promise.catch(error => this._alertActionFailed(error, 'Something went wrong in the compose form'));
4547
+ }
3546
4548
 
3547
- // Close on backdrop click
3548
- modal.addEventListener('click', e => {
3549
- if (e.target === modal) {
3550
- closeCompose();
4549
+ // Close, discard, minimize, and the keys that work anywhere in the form
4550
+ _bindComposeWindow(els) {
4551
+ const { dialog, linkbar } = els;
4552
+ dialog.querySelector('[data-action="close"]').addEventListener('click', () => this._composeFailSafe(this._requestCloseCompose()));
4553
+ dialog.querySelector('[data-action="discard"]').addEventListener('click', () => this._composeFailSafe(this._discardCompose()));
4554
+ els.minimizeButton.addEventListener('click', () => this._setComposeMinimized(!dialog.classList.contains('minimized')));
4555
+ // A minimized form comes back with a click on its title bar
4556
+ dialog.querySelector('.ee-compose-header').addEventListener('click', e => {
4557
+ if (dialog.classList.contains('minimized') && !e.target.closest('button')) {
4558
+ this._setComposeMinimized(false);
3551
4559
  }
3552
4560
  });
3553
4561
 
3554
- // Close on Escape key
4562
+ // Keys work while focus is in the form: Escape closes it (or the link field), Ctrl+Enter sends
3555
4563
  this._composeKeydownHandler = e => {
3556
- if (e.key === 'Escape' && modal.classList.contains('show')) {
3557
- closeCompose();
4564
+ if (e.key === 'Escape') {
4565
+ e.preventDefault();
4566
+ if (!linkbar.hidden) {
4567
+ this._closeLinkbar();
4568
+ } else {
4569
+ this._composeFailSafe(this._requestCloseCompose());
4570
+ }
4571
+ } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
4572
+ e.preventDefault();
4573
+ els.sendButton.click();
3558
4574
  }
3559
4575
  };
3560
- document.addEventListener('keydown', this._composeKeydownHandler);
4576
+ dialog.addEventListener('keydown', this._composeKeydownHandler);
4577
+
4578
+ els.saveDraftButton.addEventListener('click', () => this._composeFailSafe(this._saveComposeDraft()));
4579
+ els.sendButton.addEventListener('click', () => this._composeFailSafe(this._sendCompose()));
4580
+ }
4581
+
4582
+ // The editor: typing state, paste and drop, the formatting toolbar and the link field
4583
+ _bindComposeEditor(els) {
4584
+ const { dialog, editor, toolbar, linkbar } = els;
4585
+ editor.addEventListener('input', () => this._updateEditorEmpty());
4586
+ editor.addEventListener('keyup', () => this._updateFormatButtons());
4587
+ editor.addEventListener('mouseup', () => this._updateFormatButtons());
4588
+ editor.addEventListener('paste', e => this._onEditorPaste(e));
4589
+ // Dropped files are attached; dropped markup would bypass the paste filter, so text only
4590
+ dialog.addEventListener('dragover', e => e.preventDefault());
4591
+ dialog.addEventListener('drop', e => {
4592
+ e.preventDefault();
4593
+ const files = e.dataTransfer && Array.from(e.dataTransfer.files || []);
4594
+ if (files && files.length) {
4595
+ this._addComposeFiles(files);
4596
+ } else if (e.dataTransfer && editor.contains(e.target)) {
4597
+ document.execCommand('insertText', false, e.dataTransfer.getData('text/plain'));
4598
+ }
4599
+ });
4600
+
4601
+ // keep the selection in the editor while a toolbar button is pressed
4602
+ toolbar.addEventListener('mousedown', e => {
4603
+ if (e.target.closest('.ee-compose-format')) {
4604
+ e.preventDefault();
4605
+ }
4606
+ });
4607
+ toolbar.addEventListener('click', e => {
4608
+ if (e.target.closest('[data-action="link"]')) {
4609
+ this._openLinkbar();
4610
+ return;
4611
+ }
4612
+ const button = e.target.closest('.ee-compose-format[data-command]');
4613
+ if (button) {
4614
+ editor.focus();
4615
+ document.execCommand(button.dataset.command, false, null);
4616
+ this._updateEditorEmpty();
4617
+ this._updateFormatButtons();
4618
+ }
4619
+ });
4620
+ linkbar.querySelector('[data-action="insert-link"]').addEventListener('click', () => this._insertLink());
4621
+ linkbar.querySelector('[data-action="cancel-link"]').addEventListener('click', () => this._closeLinkbar());
4622
+ linkbar.querySelector('[name="link"]').addEventListener('keydown', e => {
4623
+ if (e.key === 'Enter') {
4624
+ e.preventDefault();
4625
+ this._insertLink();
4626
+ }
4627
+ });
4628
+ }
3561
4629
 
4630
+ // The address fields, attachments and the quote toggle
4631
+ _bindComposeFields(els) {
4632
+ const { dialog, form, fileInput, chips, quote } = els;
4633
+ // the editor's input bubbles here too
3562
4634
  form.addEventListener('input', () => {
3563
4635
  if (!els.error.hidden) {
3564
4636
  this._clearComposeError();
3565
4637
  }
3566
4638
  });
3567
4639
 
4640
+ quote.querySelector('.ee-compose-quote-toggle').addEventListener('click', e => {
4641
+ this._setQuoteExpanded(e.currentTarget.getAttribute('aria-expanded') !== 'true');
4642
+ });
4643
+
3568
4644
  form.querySelector('[data-action="show-cc"]').addEventListener('click', () => {
3569
4645
  const ccShown = !form.querySelector('[data-field="cc"]').hidden;
3570
4646
  this._showCopyFields({ cc: true, bcc: true });
3571
4647
  (ccShown ? form.elements.bcc : form.elements.cc).focus();
3572
4648
  });
3573
4649
 
3574
- form.querySelector('[data-action="attach"]').addEventListener('click', () => fileInput.click());
4650
+ dialog.querySelector('[data-action="attach"]').addEventListener('click', () => fileInput.click());
3575
4651
  fileInput.addEventListener('change', () => {
3576
4652
  const files = Array.from(fileInput.files || []);
3577
4653
  fileInput.value = '';
@@ -3584,40 +4660,6 @@ export class EmailEngineClient {
3584
4660
  this._renderComposeChips();
3585
4661
  }
3586
4662
  });
3587
-
3588
- // Save the composed message as a draft instead of sending it
3589
- const saveDraftButton = modal.querySelector('.ee-compose-save-draft');
3590
- saveDraftButton.addEventListener('click', async () => {
3591
- const response = await this._runComposeAction(saveDraftButton, 'Saving...', 'Could not save the draft', false, (...args) =>
3592
- this.saveDraft(...args)
3593
- );
3594
- if (!response) {
3595
- return;
3596
- }
3597
- this.notify('Draft saved to the Drafts folder.');
3598
- // Refresh the list when the user is looking at the Drafts folder
3599
- if (!this._destroyed && response.path && this.currentFolder === response.path) {
3600
- this._fireAndForget(this.loadMessages(this.currentFolder));
3601
- }
3602
- });
3603
-
3604
- // Send email
3605
- const sendButton = modal.querySelector('.ee-compose-send');
3606
- sendButton.addEventListener('click', async () => {
3607
- const response = await this._runComposeAction(sendButton, 'Sending...', 'Could not send the message', true, (...args) => this.sendMessage(...args));
3608
- if (response) {
3609
- // Submitting only queues the message; delivery happens afterwards and can still fail
3610
- this.notify('Message queued for delivery.');
3611
- }
3612
- });
3613
-
3614
- // Handle Enter key in form (Ctrl+Enter to send)
3615
- form.addEventListener('keydown', e => {
3616
- if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
3617
- e.preventDefault();
3618
- sendButton.click();
3619
- }
3620
- });
3621
4663
  }
3622
4664
 
3623
4665
  positionComposeButton() {
@@ -3716,7 +4758,7 @@ export class EmailEngineClient {
3716
4758
  init() {
3717
4759
  if (typeof document === 'undefined') {
3718
4760
  console.warn('EmailEngineClient UI features are only available in browser environments');
3719
- return;
4761
+ return Promise.resolve(false);
3720
4762
  }
3721
4763
 
3722
4764
  this.createStyles();
@@ -3728,13 +4770,14 @@ export class EmailEngineClient {
3728
4770
  toggleBtn.addEventListener('click', () => this.toggleDarkMode());
3729
4771
  }
3730
4772
 
3731
- this._loadInitialView();
4773
+ return this._loadInitialView();
3732
4774
  }
3733
4775
 
3734
4776
  // Load the folder list and open the account's inbox. Used on startup and by
3735
4777
  // the Retry button that loadFolders renders when the request fails; both
3736
4778
  // failure paths already put an error panel in the UI, so the rejection is
3737
4779
  // logged and swallowed here rather than surfacing as an unhandled rejection.
4780
+ // Resolves whether the view loaded.
3738
4781
  _loadInitialView() {
3739
4782
  // Drop whatever a previous attempt left here; loadFolders and loadMessages
3740
4783
  // paint their own loading states from this point on.
@@ -3755,10 +4798,14 @@ export class EmailEngineClient {
3755
4798
  this._renderPaneError('.ee-message-list', 'Folders unavailable', error, () => this._loadInitialView());
3756
4799
  throw error;
3757
4800
  })
3758
- .then(async () => this._listFolderOf(await message))
4801
+ .then(async () => {
4802
+ await this._listFolderOf(await message);
4803
+ return true;
4804
+ })
3759
4805
  .catch(error => {
3760
4806
  // Both loadFolders and loadMessages have already rendered a panel
3761
4807
  console.error('Failed to load the initial view:', error);
4808
+ return false;
3762
4809
  });
3763
4810
  }
3764
4811
 
@@ -3838,7 +4885,7 @@ export class EmailEngineClient {
3838
4885
  // Update UI. The compose button and modal are siblings of .ee-client, so
3839
4886
  // they carry the class themselves.
3840
4887
  this.container
3841
- .querySelectorAll('.ee-client, .ee-compose-button, .ee-compose-modal, .ee-toast')
4888
+ .querySelectorAll('.ee-client, .ee-compose-button, .ee-compose, .ee-toast')
3842
4889
  .forEach(el => el.classList.toggle('ee-dark-mode', this.darkMode));
3843
4890
 
3844
4891
  // Update toggle button icon
@@ -3877,9 +4924,9 @@ export class EmailEngineClient {
3877
4924
  this._composeButtonCleanup = null;
3878
4925
  }
3879
4926
 
3880
- // Remove the document-level Escape keydown listener
3881
- if (this._composeKeydownHandler && typeof document !== 'undefined') {
3882
- document.removeEventListener('keydown', this._composeKeydownHandler);
4927
+ // The compose form's keys listen on the form itself
4928
+ if (this._composeKeydownHandler && this._compose && this._compose.els) {
4929
+ this._compose.els.dialog.removeEventListener('keydown', this._composeKeydownHandler);
3883
4930
  this._composeKeydownHandler = null;
3884
4931
  }
3885
4932