@postalsys/ee-client 1.10.0 → 1.11.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 +33 -7
  2. package/index.d.ts +79 -2
  3. package/index.js +870 -183
  4. package/package.json +8 -4
package/index.js CHANGED
@@ -78,7 +78,90 @@ const ICON_PATHS = {
78
78
  move: '<path d="M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1"/><path d="M2 13h10"/><path d="m9 16 3-3-3-3"/>',
79
79
  download: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>',
80
80
  send: '<path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/>',
81
- compose: '<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/>'
81
+ compose: '<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"/>',
82
+ reply: '<polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/>',
83
+ replyAll: '<polyline points="7 17 2 12 7 7"/><polyline points="12 17 7 12 12 7"/><path d="M22 18v-2a4 4 0 0 0-4-4H7"/>',
84
+ forward: '<polyline points="15 17 20 12 15 7"/><path d="M4 18v-2a4 4 0 0 1 4-4h12"/>',
85
+ 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"/>',
86
+ close: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
87
+ 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"/>',
88
+ moon: '<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>'
89
+ };
90
+
91
+ // Default cap on the files attached in the compose form, in bytes. They travel base64 encoded
92
+ // inside one JSON request, which grows them by a third, and most providers refuse a message
93
+ // much larger than this anyway. Hosts that know their limit pass maxAttachmentSize.
94
+ const DEFAULT_MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
95
+
96
+ // What a compose form address has to look like before it is sent. Deliberately loose: the
97
+ // server validates properly, this only catches a name typed without its address.
98
+ const ADDRESS_PATTERN = /^[^\s@<>",;]+@[^\s@<>",;]+$/;
99
+
100
+ // Splits an address field on commas and semicolons that are not inside a quoted name or an
101
+ // angle-bracketed address, so "Doe, John" <john@example.com> stays one entry.
102
+ function splitAddressField(value) {
103
+ const parts = [];
104
+ let current = '';
105
+ let quoted = false;
106
+ let bracketed = false;
107
+ for (let i = 0; i < value.length; i++) {
108
+ const chr = value[i];
109
+ if (chr === '\\' && quoted && i + 1 < value.length) {
110
+ current += chr + value[++i];
111
+ continue;
112
+ }
113
+ if (chr === '"' && !bracketed) {
114
+ quoted = !quoted;
115
+ } else if (chr === '<' && !quoted) {
116
+ bracketed = true;
117
+ } else if (chr === '>' && !quoted) {
118
+ bracketed = false;
119
+ } else if ((chr === ',' || chr === ';') && !quoted && !bracketed) {
120
+ parts.push(current);
121
+ current = '';
122
+ continue;
123
+ }
124
+ current += chr;
125
+ }
126
+ parts.push(current);
127
+ return parts.map(part => part.trim()).filter(Boolean);
128
+ }
129
+
130
+ function parseAddressEntry(entry) {
131
+ const match = entry.match(/^(.*)<([^>]*)>$/);
132
+ if (!match) {
133
+ return { address: entry };
134
+ }
135
+ let name = match[1].trim();
136
+ if (name.length > 1 && name.startsWith('"') && name.endsWith('"')) {
137
+ name = name.slice(1, -1).replace(/\\(.)/g, '$1');
138
+ }
139
+ const address = match[2].trim();
140
+ return name ? { name, address } : { address };
141
+ }
142
+
143
+ // Adds "Re: " or "Fwd: " unless the subject already starts with that prefix, so a long
144
+ // thread does not read "Re: Re: Re:"
145
+ function prefixSubject(subject, prefix) {
146
+ const value = (subject || '').trim();
147
+ const pattern = prefix === 'Re' ? /^re\s*:/i : /^fwd?\s*:/i;
148
+ return pattern.test(value) ? value : `${prefix}: ${value}`.trim();
149
+ }
150
+
151
+ // Address entries that carry an address, from a list, a single entry or a bare address string.
152
+ // The server can return name-only entries and a single object where a list is expected.
153
+ function addressEntries(value) {
154
+ return (Array.isArray(value) ? value : value ? [value] : [])
155
+ .map(entry => (typeof entry === 'string' ? { address: entry } : entry))
156
+ .filter(entry => entry && typeof entry.address === 'string' && entry.address);
157
+ }
158
+
159
+ // Compose form titles, by mode
160
+ const COMPOSE_TITLES = {
161
+ new: 'New Message',
162
+ reply: 'Reply',
163
+ 'reply-all': 'Reply All',
164
+ forward: 'Forward'
82
165
  };
83
166
 
84
167
  // Below this container width the UI shows one pane at a time and the compose button
@@ -112,6 +195,14 @@ export class EmailEngineClient {
112
195
 
113
196
  this.currentFolder = null;
114
197
  this.currentMessage = null;
198
+ // A message to open on startup instead of the inbox listing (a deep link). Its folder
199
+ // is listed next to it, so the reader lands where the message lives.
200
+ this.initialMessage = typeof options.message === 'string' && options.message ? options.message : null;
201
+ // Told whenever the open folder or message changes, so a host page can keep its address
202
+ // bar in step (see _notifyNavigate)
203
+ this.onNavigate = typeof options.onNavigate === 'function' ? options.onNavigate : null;
204
+ const maxAttachmentSize = Number(options.maxAttachmentSize);
205
+ this.maxAttachmentSize = maxAttachmentSize > 0 ? maxAttachmentSize : DEFAULT_MAX_ATTACHMENT_SIZE;
115
206
  this.folders = [];
116
207
  this.messages = [];
117
208
  this.nextPageCursor = null;
@@ -266,8 +357,9 @@ export class EmailEngineClient {
266
357
  }
267
358
  }
268
359
 
360
+ // Loads and renders one page of a folder's message list. The open message stays open: it is
361
+ // the folder click (openFolder()) that closes it, while paging and refreshes keep it.
269
362
  async loadMessages(path, cursor = null) {
270
- this._setView('list');
271
363
  this._setPaneHtml('.ee-message-list', `${this._messageListHeader(path)}<div class="ee-loading">Loading messages...</div>`);
272
364
 
273
365
  try {
@@ -282,15 +374,13 @@ export class EmailEngineClient {
282
374
  this.nextPageCursor = data.nextPageCursor || null;
283
375
  this.prevPageCursor = data.prevPageCursor || null;
284
376
 
285
- // Clear active email selection when folder changes
286
- this.currentMessage = null;
287
-
288
377
  if (this.container) {
289
378
  this.renderMessageList();
290
379
  this.renderFolderList(); // Re-render to update active state
291
- this.renderMessage(); // Clear message viewer
292
380
  }
293
381
 
382
+ this._notifyNavigate();
383
+
294
384
  return {
295
385
  messages: this.messages,
296
386
  nextPageCursor: this.nextPageCursor,
@@ -309,6 +399,14 @@ export class EmailEngineClient {
309
399
  }
310
400
  }
311
401
 
402
+ // Switches to another folder: closes the open message and lists the folder
403
+ openFolder(path) {
404
+ this.currentMessage = null;
405
+ this.renderMessage();
406
+ this._setView('list');
407
+ return this.loadMessages(path);
408
+ }
409
+
312
410
  async loadMessage(messageId) {
313
411
  this._setView('message');
314
412
  this._setPaneHtml('.ee-message-viewer', `${this._messageToolbar()}<div class="ee-loading">Loading message...</div>`);
@@ -322,6 +420,7 @@ export class EmailEngineClient {
322
420
  this.currentMessage = data;
323
421
 
324
422
  this.currentMessage.unseen = false;
423
+ this._notifyNavigate();
325
424
 
326
425
  const msg = this.messages.find(m => m.id === messageId);
327
426
  if (msg) {
@@ -386,21 +485,28 @@ export class EmailEngineClient {
386
485
  }
387
486
  }
388
487
 
389
- async deleteMessage(messageId) {
390
- try {
391
- await this.apiRequest('DELETE', this._messagePath(messageId));
488
+ // Takes a message that left the folder (deleted or moved) off the list, and out of the
489
+ // viewer when it was the open one
490
+ _dropMessage(messageId) {
491
+ this.messages = this.messages.filter(m => m.id !== messageId);
492
+ if (this.container) {
493
+ this.renderMessageList();
494
+ }
392
495
 
393
- this.messages = this.messages.filter(m => m.id !== messageId);
496
+ if (this.currentMessage && this.currentMessage.id === messageId) {
497
+ this.currentMessage = null;
394
498
  if (this.container) {
395
- this.renderMessageList();
499
+ this.renderMessage();
396
500
  }
501
+ this._notifyNavigate();
502
+ }
503
+ }
397
504
 
398
- if (this.currentMessage && this.currentMessage.id === messageId) {
399
- this.currentMessage = null;
400
- if (this.container) {
401
- this.renderMessage();
402
- }
403
- }
505
+ async deleteMessage(messageId) {
506
+ try {
507
+ await this.apiRequest('DELETE', this._messagePath(messageId));
508
+
509
+ this._dropMessage(messageId);
404
510
 
405
511
  return true;
406
512
  } catch (error) {
@@ -415,17 +521,7 @@ export class EmailEngineClient {
415
521
  path: targetPath
416
522
  });
417
523
 
418
- this.messages = this.messages.filter(m => m.id !== messageId);
419
- if (this.container) {
420
- this.renderMessageList();
421
- }
422
-
423
- if (this.currentMessage && this.currentMessage.id === messageId) {
424
- this.currentMessage = null;
425
- if (this.container) {
426
- this.renderMessage();
427
- }
428
- }
524
+ this._dropMessage(messageId);
429
525
 
430
526
  return true;
431
527
  } catch (error) {
@@ -434,10 +530,6 @@ export class EmailEngineClient {
434
530
  }
435
531
  }
436
532
 
437
- _normalizeRecipients(to) {
438
- return Array.isArray(to) ? to.map(addr => (typeof addr === 'string' ? { address: addr } : addr)) : [typeof to === 'string' ? { address: to } : to];
439
- }
440
-
441
533
  // Account details (name, email address) fetched once and cached for the lifetime
442
534
  // of the instance; used as the From identity of saved drafts.
443
535
  async _getAccountInfo() {
@@ -447,13 +539,35 @@ export class EmailEngineClient {
447
539
  return this._accountInfo;
448
540
  }
449
541
 
450
- async sendMessage(to, subject, text) {
542
+ // The address and content fields shared by a submission and a draft upload. Empty recipient
543
+ // lists are left out rather than sent as [].
544
+ _messagePayload(to, subject, text, { cc, bcc, attachments, reference } = {}) {
545
+ const data = { subject, text };
546
+ for (const [key, value] of [
547
+ ['to', to],
548
+ ['cc', cc],
549
+ ['bcc', bcc]
550
+ ]) {
551
+ const list = addressEntries(value);
552
+ if (list.length) {
553
+ data[key] = list;
554
+ }
555
+ }
556
+ if (Array.isArray(attachments) && attachments.length) {
557
+ data.attachments = attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content }));
558
+ }
559
+ if (reference) {
560
+ data.reference = reference;
561
+ }
562
+ return data;
563
+ }
564
+
565
+ // options: { cc, bcc, attachments: [{ filename, contentType, content (base64) }], reference }.
566
+ // reference is EmailEngine's submit reference block ({ message, action, inline,
567
+ // forwardAttachments }); with it the server adds the threading headers and the quote.
568
+ async sendMessage(to, subject, text, options = {}) {
451
569
  try {
452
- const messageData = {
453
- to: this._normalizeRecipients(to),
454
- subject,
455
- text
456
- };
570
+ const messageData = this._messagePayload(to, subject, text, options);
457
571
 
458
572
  const response = await this.apiRequest('POST', `${this._accountPath()}/submit`, messageData);
459
573
  return response;
@@ -463,7 +577,7 @@ export class EmailEngineClient {
463
577
  }
464
578
  }
465
579
 
466
- async saveDraft(to, subject, text) {
580
+ async saveDraft(to, subject, text, options = {}) {
467
581
  try {
468
582
  if (!this.folders.length) {
469
583
  await this.loadFolders();
@@ -476,15 +590,9 @@ export class EmailEngineClient {
476
590
  const messageData = {
477
591
  path: draftsFolder.path,
478
592
  flags: ['\\Draft'],
479
- subject,
480
- text
593
+ ...this._messagePayload(to, subject, text, options)
481
594
  };
482
595
 
483
- const recipients = to ? this._normalizeRecipients(to) : [];
484
- if (recipients.length) {
485
- messageData.to = recipients;
486
- }
487
-
488
596
  // The upload endpoint does not add a From header on its own, but the draft
489
597
  // needs one to be deliverable later - use the account's own identity.
490
598
  try {
@@ -504,6 +612,82 @@ export class EmailEngineClient {
504
612
  }
505
613
  }
506
614
 
615
+ // Parses a typed address field ("Name <a@example.com>, b@example.com") into address entries
616
+ parseAddressList(value) {
617
+ return splitAddressField(String(value || '')).map(parseAddressEntry);
618
+ }
619
+
620
+ // The reverse of parseAddressList, for filling a compose field
621
+ formatAddressList(list) {
622
+ return addressEntries(list)
623
+ .map(entry => {
624
+ if (!entry.name) {
625
+ return entry.address;
626
+ }
627
+ const name = /[",;<>@\\]/.test(entry.name) ? `"${entry.name.replace(/(["\\])/g, '\\$1')}"` : entry.name;
628
+ return `${name} <${entry.address}>`;
629
+ })
630
+ .join(', ');
631
+ }
632
+
633
+ // Recipients, subject and submit reference for a reply, reply-all or forward of msg, as the
634
+ // compose form shows them. ownAddress (the account's) is left out of the recipients.
635
+ //
636
+ // Reply-all is resolved here rather than by the server: EmailEngine's reply-all merges the
637
+ // original recipients into whatever is sent, so one the user removed from the form would be
638
+ // put back. It goes out as a reply with every recipient spelled out instead, which the server
639
+ // leaves alone, and what the form shows is what is sent.
640
+ prepareResponse(msg, action, ownAddress = null) {
641
+ if (action === 'forward') {
642
+ return { to: [], cc: [], subject: prefixSubject(msg.subject, 'Fwd'), reference: { message: msg.id, action: 'forward', inline: true } };
643
+ }
644
+
645
+ const own = typeof ownAddress === 'string' ? ownAddress.toLowerCase() : '';
646
+ const seen = new Set(own ? [own] : []);
647
+ const take = list =>
648
+ addressEntries(list)
649
+ .filter(entry => {
650
+ const key = entry.address.toLowerCase();
651
+ if (seen.has(key)) {
652
+ return false;
653
+ }
654
+ seen.add(key);
655
+ return true;
656
+ })
657
+ .map(entry => (entry.name ? { name: entry.name, address: entry.address } : { address: entry.address }));
658
+
659
+ // Answer the address the message nominates, otherwise its sender - or, for a message the
660
+ // account sent itself (Sent folder), the people it went to. The account's own address is
661
+ // never an answer, so a Reply-To naming the account falls through to the next candidate.
662
+ const fromSelf = !!own && addressEntries(msg.from).some(entry => entry.address.toLowerCase() === own);
663
+ let to = [];
664
+ for (const candidate of [msg.replyTo, fromSelf ? msg.to : msg.from]) {
665
+ to = take(candidate);
666
+ if (to.length) {
667
+ break;
668
+ }
669
+ }
670
+ if (!to.length) {
671
+ // A message from the account to itself: answer it anyway
672
+ to = addressEntries(msg.from).map(entry => ({ ...entry }));
673
+ }
674
+ const cc = action === 'reply-all' ? take(addressEntries(msg.to).concat(addressEntries(msg.cc))) : [];
675
+
676
+ return { to, cc, subject: prefixSubject(msg.subject, 'Re'), reference: { message: msg.id, action: 'reply', inline: true } };
677
+ }
678
+
679
+ // Tells the host which folder and message are open. A host error must not break the client.
680
+ _notifyNavigate() {
681
+ if (!this.onNavigate || this._destroyed) {
682
+ return;
683
+ }
684
+ try {
685
+ this.onNavigate({ path: this.currentFolder, messageId: this.currentMessage ? this.currentMessage.id : null });
686
+ } catch (error) {
687
+ console.error('onNavigate handler failed:', error);
688
+ }
689
+ }
690
+
507
691
  async submitDraft(messageId, options = null) {
508
692
  try {
509
693
  const response = await this.apiRequest('POST', this._messagePath(messageId, '/submit'), options);
@@ -550,7 +734,7 @@ export class EmailEngineClient {
550
734
  // are needed - and to[N] for any index is handled, not just to[0].
551
735
  .map(field =>
552
736
  field.message
553
- .replace(/to\[\d+\]\.address|"address"/g, 'email address')
737
+ .replace(/(?:to|cc|bcc)\[\d+\]\.address|"address"/g, 'email address')
554
738
  .replace(/"subject"/g, 'subject')
555
739
  .replace(/"text"/g, 'message')
556
740
  );
@@ -1071,14 +1255,42 @@ export class EmailEngineClient {
1071
1255
  }
1072
1256
 
1073
1257
  .ee-attachment-indicator {
1074
- display: inline-block;
1258
+ display: inline-flex;
1259
+ align-items: center;
1260
+ white-space: nowrap;
1261
+ flex-shrink: 0;
1075
1262
  font-size: 11px;
1076
1263
  color: #666;
1077
1264
  margin-left: 8px;
1078
1265
  }
1079
1266
 
1080
- .ee-attachment-indicator::before {
1081
- content: "📎 ";
1267
+ .ee-attachment-indicator .ee-icon {
1268
+ margin-right: 2px;
1269
+ }
1270
+
1271
+ /* Replied / forwarded markers, from the message flags (see _responseMarkers) */
1272
+ .ee-response-marker {
1273
+ display: inline-flex;
1274
+ align-items: center;
1275
+ gap: 4px;
1276
+ color: #666;
1277
+ margin-right: 6px;
1278
+ flex-shrink: 0;
1279
+ }
1280
+
1281
+ .ee-message-title-markers {
1282
+ display: flex;
1283
+ gap: 4px;
1284
+ margin: -8px 0 12px;
1285
+ font-size: 12px;
1286
+ }
1287
+
1288
+ .ee-message-title-markers:empty {
1289
+ display: none;
1290
+ }
1291
+
1292
+ .ee-dark-mode .ee-response-marker {
1293
+ color: #999;
1082
1294
  }
1083
1295
 
1084
1296
  .ee-message-viewer {
@@ -1345,8 +1557,9 @@ export class EmailEngineClient {
1345
1557
  }
1346
1558
 
1347
1559
  .ee-attachment-icon {
1560
+ display: flex;
1348
1561
  margin-right: 8px;
1349
- font-size: 18px;
1562
+ color: #666;
1350
1563
  }
1351
1564
 
1352
1565
  .ee-attachment-info {
@@ -1593,7 +1806,7 @@ export class EmailEngineClient {
1593
1806
  border-radius: 8px;
1594
1807
  width: 90%;
1595
1808
  max-width: 600px;
1596
- max-height: 80vh;
1809
+ max-height: 90vh;
1597
1810
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
1598
1811
  display: flex;
1599
1812
  flex-direction: column;
@@ -1617,7 +1830,6 @@ export class EmailEngineClient {
1617
1830
  .ee-compose-close {
1618
1831
  background: none;
1619
1832
  border: none;
1620
- font-size: 24px;
1621
1833
  color: #666;
1622
1834
  cursor: pointer;
1623
1835
  padding: 0;
@@ -1674,7 +1886,7 @@ export class EmailEngineClient {
1674
1886
  font-size: 14px;
1675
1887
  font-family: inherit;
1676
1888
  resize: vertical;
1677
- min-height: 200px;
1889
+ min-height: 160px;
1678
1890
  }
1679
1891
 
1680
1892
  .ee-compose-textarea:focus {
@@ -1750,6 +1962,144 @@ export class EmailEngineClient {
1750
1962
  opacity: 0.6;
1751
1963
  }
1752
1964
 
1965
+ /* Parts of the compose form that come and go (Cc/Bcc, the forward checkbox, the
1966
+ quote) use the hidden attribute, which a display rule would otherwise override */
1967
+ .ee-compose-modal [hidden] {
1968
+ display: none !important;
1969
+ }
1970
+
1971
+ .ee-compose-label-row {
1972
+ display: flex;
1973
+ justify-content: space-between;
1974
+ align-items: baseline;
1975
+ }
1976
+
1977
+ .ee-compose-link {
1978
+ background: none;
1979
+ border: none;
1980
+ padding: 0;
1981
+ font: inherit;
1982
+ font-size: 13px;
1983
+ color: #007bff;
1984
+ cursor: pointer;
1985
+ }
1986
+
1987
+ .ee-compose-link:hover {
1988
+ text-decoration: underline;
1989
+ }
1990
+
1991
+ .ee-compose-files {
1992
+ display: flex;
1993
+ flex-direction: column;
1994
+ gap: 8px;
1995
+ }
1996
+
1997
+ .ee-compose-files-row {
1998
+ display: flex;
1999
+ flex-wrap: wrap;
2000
+ align-items: center;
2001
+ gap: 8px 16px;
2002
+ }
2003
+
2004
+ .ee-compose-attach {
2005
+ display: inline-flex;
2006
+ align-items: center;
2007
+ gap: 6px;
2008
+ background: transparent;
2009
+ border: 1px solid #ddd;
2010
+ border-radius: 4px;
2011
+ padding: 6px 12px;
2012
+ font: inherit;
2013
+ font-size: 13px;
2014
+ color: inherit;
2015
+ cursor: pointer;
2016
+ }
2017
+
2018
+ .ee-compose-attach:hover {
2019
+ background: #f0f0f0;
2020
+ }
2021
+
2022
+ .ee-compose-forward-attachments {
2023
+ display: inline-flex;
2024
+ align-items: center;
2025
+ gap: 6px;
2026
+ font-size: 13px;
2027
+ cursor: pointer;
2028
+ }
2029
+
2030
+ .ee-compose-chips {
2031
+ display: flex;
2032
+ flex-wrap: wrap;
2033
+ gap: 6px;
2034
+ }
2035
+
2036
+ .ee-compose-chips:empty {
2037
+ display: none;
2038
+ }
2039
+
2040
+ .ee-compose-chip {
2041
+ display: inline-flex;
2042
+ align-items: center;
2043
+ gap: 6px;
2044
+ max-width: 100%;
2045
+ padding: 4px 4px 4px 10px;
2046
+ border: 1px solid #ddd;
2047
+ border-radius: 16px;
2048
+ background: #f8f9fa;
2049
+ font-size: 13px;
2050
+ }
2051
+
2052
+ .ee-compose-chip-name {
2053
+ overflow: hidden;
2054
+ text-overflow: ellipsis;
2055
+ white-space: nowrap;
2056
+ min-width: 0;
2057
+ }
2058
+
2059
+ .ee-compose-chip-size {
2060
+ color: #666;
2061
+ flex-shrink: 0;
2062
+ }
2063
+
2064
+ .ee-compose-chip-remove {
2065
+ display: inline-flex;
2066
+ align-items: center;
2067
+ justify-content: center;
2068
+ width: 22px;
2069
+ height: 22px;
2070
+ padding: 0;
2071
+ border: none;
2072
+ border-radius: 50%;
2073
+ background: transparent;
2074
+ color: #666;
2075
+ cursor: pointer;
2076
+ flex-shrink: 0;
2077
+ }
2078
+
2079
+ .ee-compose-chip-remove:hover {
2080
+ background: #e0e0e0;
2081
+ }
2082
+
2083
+ .ee-compose-quote {
2084
+ display: flex;
2085
+ flex-direction: column;
2086
+ gap: 6px;
2087
+ }
2088
+
2089
+ .ee-compose-quote-label {
2090
+ font-size: 13px;
2091
+ color: #666;
2092
+ }
2093
+
2094
+ .ee-compose-quote-frame {
2095
+ max-height: 220px;
2096
+ overflow: auto;
2097
+ padding: 8px 12px;
2098
+ border-left: 3px solid #ddd;
2099
+ background: #fafafa;
2100
+ border-radius: 0 4px 4px 0;
2101
+ }
2102
+
1753
2103
  /* Dark mode toggle button, in the Folders pane header */
1754
2104
  .ee-dark-mode-toggle {
1755
2105
  background: #f8f9fa;
@@ -1773,8 +2123,7 @@ export class EmailEngineClient {
1773
2123
  }
1774
2124
 
1775
2125
  .ee-dark-mode-icon {
1776
- font-size: 14px;
1777
- line-height: 1;
2126
+ display: flex;
1778
2127
  }
1779
2128
 
1780
2129
  /* Dark mode styles */
@@ -2048,6 +2397,35 @@ export class EmailEngineClient {
2048
2397
  background: #66b2ff;
2049
2398
  color: #1a1a1a;
2050
2399
  }
2400
+
2401
+ .ee-dark-mode .ee-compose-link {
2402
+ color: #66b2ff;
2403
+ }
2404
+
2405
+ .ee-dark-mode .ee-compose-attach {
2406
+ border-color: #444;
2407
+ }
2408
+
2409
+ .ee-dark-mode .ee-compose-attach:hover,
2410
+ .ee-dark-mode .ee-compose-chip-remove:hover {
2411
+ background: #333;
2412
+ }
2413
+
2414
+ .ee-dark-mode .ee-compose-chip {
2415
+ background: #2a2a2a;
2416
+ border-color: #444;
2417
+ }
2418
+
2419
+ .ee-dark-mode .ee-compose-chip-size,
2420
+ .ee-dark-mode .ee-compose-chip-remove,
2421
+ .ee-dark-mode .ee-compose-quote-label {
2422
+ color: #999;
2423
+ }
2424
+
2425
+ .ee-dark-mode .ee-compose-quote-frame {
2426
+ background: #1a1a1a;
2427
+ border-color: #444;
2428
+ }
2051
2429
  `);
2052
2430
  document.head.appendChild(style);
2053
2431
  this._styleElement = style;
@@ -2176,7 +2554,7 @@ export class EmailEngineClient {
2176
2554
  folderTree.querySelectorAll('.ee-folder-item').forEach(item => {
2177
2555
  item.addEventListener('click', () => {
2178
2556
  const path = item.getAttribute('data-path');
2179
- this._fireAndForget(this.loadMessages(path));
2557
+ this._fireAndForget(this.openFolder(path));
2180
2558
  });
2181
2559
  });
2182
2560
  }
@@ -2235,8 +2613,9 @@ export class EmailEngineClient {
2235
2613
  <span class="ee-message-date">${this.formatDate(msg.date)}</span>
2236
2614
  </div>
2237
2615
  <div class="ee-message-subject">
2616
+ ${this._responseMarkers(msg)}
2238
2617
  <span class="ee-message-subject-text">${this.escapeHtml(msg.subject || '(no subject)')}</span>
2239
- ${msg.attachments && msg.attachments.length > 0 ? `<span class="ee-attachment-indicator">${msg.attachments.length}</span>` : ''}
2618
+ ${msg.attachments && msg.attachments.length > 0 ? `<span class="ee-attachment-indicator" title="Attachments">${icon('paperclip', 12)}${msg.attachments.length}</span>` : ''}
2240
2619
  </div>
2241
2620
  <div class="ee-message-preview">${this.escapeHtml(msg.intro || '')}</div>
2242
2621
  </div>
@@ -2306,8 +2685,13 @@ export class EmailEngineClient {
2306
2685
  // query); aria-label and title carry the full name either way. The move control
2307
2686
  // is a native select laid invisibly over a button so it looks like the rest of
2308
2687
  // the toolbar while keeping the platform's own folder picker.
2688
+ const respond = isDraft
2689
+ ? ''
2690
+ : `${this._toolbarButton('reply', 'reply', 'Reply', 'Reply to the sender')}
2691
+ ${addressEntries(msg.to).length + addressEntries(msg.cc).length > 1 ? this._toolbarButton('reply-all', 'replyAll', 'Reply all', 'Reply to everyone') : ''}
2692
+ ${this._toolbarButton('forward', 'forward', 'Forward', 'Forward this message')}`;
2309
2693
  const actions = `
2310
- ${isDraft ? this._toolbarButton('send-draft', 'send', 'Send draft', 'Send this draft now', 'ee-button-primary ee-keep-label') : ''}
2694
+ ${isDraft ? this._toolbarButton('send-draft', 'send', 'Send draft', 'Send this draft now', 'ee-button-primary ee-keep-label') : respond}
2311
2695
  ${this._toolbarButton('toggle-read', isUnseen ? 'mailOpen' : 'mail', isUnseen ? 'Mark read' : 'Mark unread', isUnseen ? 'Mark as read' : 'Mark as unread')}
2312
2696
  <span class="ee-button ee-move-button" title="Move to folder">
2313
2697
  ${icon('move')}<span class="ee-button-label">Move</span>${icon('chevronDown', 12)}
@@ -2330,6 +2714,7 @@ export class EmailEngineClient {
2330
2714
  ${this._messageToolbar(actions)}
2331
2715
  <div class="ee-message-content">
2332
2716
  <h2 class="ee-message-title">${this.escapeHtml(msg.subject || '(no subject)')}</h2>
2717
+ <div class="ee-message-title-markers">${this._responseMarkers(msg, true)}</div>
2333
2718
  <div class="ee-message-meta">
2334
2719
  <div class="ee-message-meta-row">
2335
2720
  <span class="ee-message-meta-label">From</span>
@@ -2365,7 +2750,7 @@ export class EmailEngineClient {
2365
2750
  .map(
2366
2751
  att => `
2367
2752
  <div class="ee-attachment-item" data-attachment-id="${this.escapeHtml(att.id)}">
2368
- <div class="ee-attachment-icon">📎</div>
2753
+ <div class="ee-attachment-icon">${icon('paperclip', 18)}</div>
2369
2754
  <div class="ee-attachment-info">
2370
2755
  <div class="ee-attachment-name">${this.escapeHtml(att.filename || 'Unnamed attachment')}</div>
2371
2756
  ${att.size ? `<div class="ee-attachment-size">${this.formatFileSize(att.size)}</div>` : ''}
@@ -2410,7 +2795,7 @@ export class EmailEngineClient {
2410
2795
  // Refresh the folder view - the provider removes the draft once it is sent,
2411
2796
  // immediately for Gmail and MS Graph, after SMTP delivery for IMAP accounts.
2412
2797
  if (!this._destroyed && this.currentFolder) {
2413
- await this.loadMessages(this.currentFolder);
2798
+ await this.openFolder(this.currentFolder);
2414
2799
  }
2415
2800
  } catch (error) {
2416
2801
  console.error('Failed to send draft:', error);
@@ -2422,6 +2807,12 @@ export class EmailEngineClient {
2422
2807
  });
2423
2808
  }
2424
2809
 
2810
+ viewer.querySelectorAll('[data-action="reply"], [data-action="reply-all"], [data-action="forward"]').forEach(button => {
2811
+ button.addEventListener('click', () => {
2812
+ this._respond(msg.id, button.dataset.action).catch(error => this._alertActionFailed(error, 'Failed to open the compose form'));
2813
+ });
2814
+ });
2815
+
2425
2816
  viewer.querySelector('[data-action="toggle-read"]').addEventListener('click', () => {
2426
2817
  const currentlyUnseen = msg.unseen;
2427
2818
  this.markAsRead(msg.id, currentlyUnseen).catch(error => this._alertActionFailed(error, 'Failed to update the message flags'));
@@ -2482,6 +2873,27 @@ export class EmailEngineClient {
2482
2873
  // Message content scrolling is now handled in loadMessage method
2483
2874
  }
2484
2875
 
2876
+ // Replied / forwarded markers from the flags the server sets on the original once a reply or
2877
+ // forward has been delivered (IMAP accounts; Gmail API and MS Graph report neither flag).
2878
+ // labelled shows the words next to the icons, otherwise they are the accessible name only.
2879
+ //
2880
+ // EmailEngine adds \Answered to a forwarded message as well as $Forwarded, so one marker is
2881
+ // shown: Forwarded when that flag is set, Replied otherwise.
2882
+ _responseMarkers(msg, labelled = false) {
2883
+ const flags = Array.isArray(msg.flags) ? msg.flags : [];
2884
+ const marker = flags.includes('$Forwarded')
2885
+ ? { icon: 'forward', label: 'Forwarded' }
2886
+ : flags.includes('\\Answered')
2887
+ ? { icon: 'reply', label: 'Replied' }
2888
+ : null;
2889
+ if (!marker) {
2890
+ return '';
2891
+ }
2892
+ return labelled
2893
+ ? `<span class="ee-response-marker">${icon(marker.icon, 12)}<span>${marker.label}</span></span>`
2894
+ : `<span class="ee-response-marker" role="img" aria-label="${marker.label}" title="${marker.label}">${icon(marker.icon, 12)}</span>`;
2895
+ }
2896
+
2485
2897
  // An icon-only button. Static arguments only, never message data.
2486
2898
  _iconButton(action, iconName, label, extraClass = '', disabled = false) {
2487
2899
  return `<button type="button" class="ee-button ee-icon-button ${extraClass}" data-action="${action}" aria-label="${label}" title="${label}"${disabled ? ' disabled' : ''}>${icon(iconName)}</button>`;
@@ -2548,7 +2960,7 @@ export class EmailEngineClient {
2548
2960
  ${
2549
2961
  this.showDarkModeToggle
2550
2962
  ? `<button type="button" class="ee-dark-mode-toggle" title="Toggle dark mode" aria-label="Toggle dark mode">
2551
- <span class="ee-dark-mode-icon">${this.darkMode ? '☀️' : '🌙'}</span>
2963
+ <span class="ee-dark-mode-icon">${icon(this.darkMode ? 'sun' : 'moon', 14)}</span>
2552
2964
  </button>`
2553
2965
  : ''
2554
2966
  }
@@ -2560,23 +2972,49 @@ export class EmailEngineClient {
2560
2972
  </div>
2561
2973
  <button type="button" class="ee-compose-button${this.darkMode ? ' ee-dark-mode' : ''}" title="Compose email" aria-label="Compose">${icon('compose', 22)}<span class="ee-compose-button-label">Compose</span></button>
2562
2974
  <div class="ee-compose-modal${this.darkMode ? ' ee-dark-mode' : ''}">
2563
- <div class="ee-compose-dialog">
2975
+ <div class="ee-compose-dialog" role="dialog" aria-modal="true" aria-label="Compose">
2564
2976
  <div class="ee-compose-header">
2565
- <h3 class="ee-compose-title">Compose Email</h3>
2566
- <button class="ee-compose-close">×</button>
2977
+ <h3 class="ee-compose-title">${COMPOSE_TITLES.new}</h3>
2978
+ <button type="button" class="ee-compose-close" aria-label="Close" title="Close">${icon('close', 18)}</button>
2567
2979
  </div>
2568
2980
  <form class="ee-compose-form">
2569
2981
  <div class="ee-compose-field">
2570
- <label class="ee-compose-label">To:</label>
2571
- <input type="email" class="ee-compose-input" name="to" placeholder="recipient@example.com" required>
2982
+ <div class="ee-compose-label-row">
2983
+ <label class="ee-compose-label" for="${this._composeId('to')}">To:</label>
2984
+ <button type="button" class="ee-compose-link" data-action="show-cc">Cc / Bcc</button>
2985
+ </div>
2986
+ <input type="text" class="ee-compose-input" id="${this._composeId('to')}" name="to" placeholder="recipient@example.com" autocomplete="off" spellcheck="false">
2987
+ </div>
2988
+ <div class="ee-compose-field" data-field="cc" hidden>
2989
+ <label class="ee-compose-label" for="${this._composeId('cc')}">Cc:</label>
2990
+ <input type="text" class="ee-compose-input" id="${this._composeId('cc')}" name="cc" autocomplete="off" spellcheck="false">
2991
+ </div>
2992
+ <div class="ee-compose-field" data-field="bcc" hidden>
2993
+ <label class="ee-compose-label" for="${this._composeId('bcc')}">Bcc:</label>
2994
+ <input type="text" class="ee-compose-input" id="${this._composeId('bcc')}" name="bcc" autocomplete="off" spellcheck="false">
2572
2995
  </div>
2573
2996
  <div class="ee-compose-field">
2574
- <label class="ee-compose-label">Subject:</label>
2575
- <input type="text" class="ee-compose-input" name="subject" placeholder="Enter subject">
2997
+ <label class="ee-compose-label" for="${this._composeId('subject')}">Subject:</label>
2998
+ <input type="text" class="ee-compose-input" id="${this._composeId('subject')}" name="subject" placeholder="Enter subject">
2576
2999
  </div>
2577
3000
  <div class="ee-compose-field">
2578
- <label class="ee-compose-label">Message:</label>
2579
- <textarea class="ee-compose-textarea" name="message" placeholder="Type your message here..." required></textarea>
3001
+ <label class="ee-compose-label" for="${this._composeId('message')}">Message:</label>
3002
+ <textarea class="ee-compose-textarea" id="${this._composeId('message')}" name="message" placeholder="Type your message here..."></textarea>
3003
+ </div>
3004
+ <div class="ee-compose-files">
3005
+ <div class="ee-compose-chips"></div>
3006
+ <div class="ee-compose-files-row">
3007
+ <button type="button" class="ee-compose-attach" data-action="attach">${icon('paperclip', 14)}<span>Attach files</span></button>
3008
+ <input type="file" class="ee-compose-file-input" multiple hidden>
3009
+ <label class="ee-compose-forward-attachments" hidden>
3010
+ <input type="checkbox" name="forwardAttachments" checked>
3011
+ <span class="ee-compose-forward-attachments-label"></span>
3012
+ </label>
3013
+ </div>
3014
+ </div>
3015
+ <div class="ee-compose-quote" hidden>
3016
+ <div class="ee-compose-quote-label"></div>
3017
+ <div class="ee-compose-quote-frame"></div>
2580
3018
  </div>
2581
3019
  </form>
2582
3020
  <div class="ee-compose-actions">
@@ -2604,142 +3042,366 @@ export class EmailEngineClient {
2604
3042
  this.positionComposeButton();
2605
3043
  }
2606
3044
 
3045
+ // Unique element ids for the compose form labels, so two clients on one page do not share them
3046
+ _composeId(field) {
3047
+ if (!this._composeIdPrefix) {
3048
+ EmailEngineClient._composeCounter = (EmailEngineClient._composeCounter || 0) + 1;
3049
+ this._composeIdPrefix = `ee-compose-${EmailEngineClient._composeCounter}`;
3050
+ }
3051
+ return `${this._composeIdPrefix}-${field}`;
3052
+ }
3053
+
3054
+ // Opens a blank compose form, optionally prefilled: { to, cc, bcc, subject, text }. The
3055
+ // address fields take a string or address entries.
3056
+ compose(prefill = {}) {
3057
+ this._openCompose({ mode: 'new', ...prefill });
3058
+ }
3059
+
3060
+ // Opens the compose form as a reply to a message (the open one when messageId is omitted)
3061
+ reply(messageId = null, { all = false } = {}) {
3062
+ return this._respond(messageId, all ? 'reply-all' : 'reply');
3063
+ }
3064
+
3065
+ // Opens the compose form to forward a message (the open one when messageId is omitted)
3066
+ forward(messageId = null) {
3067
+ return this._respond(messageId, 'forward');
3068
+ }
3069
+
3070
+ async _respond(messageId, action) {
3071
+ const id = messageId || (this.currentMessage && this.currentMessage.id);
3072
+ if (!id) {
3073
+ throw new Error('No message to respond to');
3074
+ }
3075
+
3076
+ const [msg, ownAddress] = await Promise.all([
3077
+ this.currentMessage && this.currentMessage.id === id ? this.currentMessage : this.apiRequest('GET', this._messagePath(id, '?webSafeHtml=true')),
3078
+ // Without it the account's own address may stay among the reply-all recipients
3079
+ this._getAccountInfo().then(
3080
+ info => info && info.email,
3081
+ () => null
3082
+ )
3083
+ ]);
3084
+
3085
+ this._openCompose({ mode: action, original: msg, ...this.prepareResponse(msg, action, ownAddress) });
3086
+ }
3087
+
3088
+ _openCompose({ mode = 'new', to, cc, bcc, subject, text, reference = null, original = null } = {}) {
3089
+ const els = this._compose && this._compose.els;
3090
+ if (!els) {
3091
+ throw new Error('The compose form needs the client UI (a container)');
3092
+ }
3093
+ this._resetCompose();
3094
+ this._compose.reference = reference;
3095
+
3096
+ const asField = value => (typeof value === 'string' ? value : this.formatAddressList(value));
3097
+ const { form } = els;
3098
+ form.elements.to.value = asField(to);
3099
+ form.elements.cc.value = asField(cc);
3100
+ form.elements.bcc.value = asField(bcc);
3101
+ form.elements.subject.value = subject || '';
3102
+ form.elements.message.value = text || '';
3103
+ this._showCopyFields({ cc: !!form.elements.cc.value, bcc: !!form.elements.bcc.value });
3104
+
3105
+ els.title.textContent = COMPOSE_TITLES[mode] || COMPOSE_TITLES.new;
3106
+
3107
+ // The server carries the original's attachments over on request (all or none)
3108
+ const originalAttachments = original && mode === 'forward' ? (original.attachments || []).filter(att => !att.inline && !att.embedded) : [];
3109
+ els.forwardAttachments.hidden = !originalAttachments.length;
3110
+ els.forwardAttachments.querySelector('.ee-compose-forward-attachments-label').textContent =
3111
+ `Include the original attachments (${originalAttachments.length})`;
3112
+
3113
+ if (original && reference && reference.inline) {
3114
+ this._renderComposeQuote(original, mode);
3115
+ }
3116
+
3117
+ els.modal.classList.add('show');
3118
+ const focusTarget = form.elements.to.value ? form.elements.message : form.elements.to;
3119
+ setTimeout(() => {
3120
+ focusTarget.focus();
3121
+ if (focusTarget === form.elements.message) {
3122
+ focusTarget.setSelectionRange(0, 0);
3123
+ }
3124
+ }, 100);
3125
+ }
3126
+
3127
+ // A read-only copy of the message being answered, under the textarea. The quote that is sent
3128
+ // is built by the server from the stored original; this shows what it will contain.
3129
+ _renderComposeQuote(original, mode) {
3130
+ const { quote } = this._compose.els;
3131
+ const from = addressEntries(original.from)[0];
3132
+ const sender = from ? from.name || from.address : 'the sender';
3133
+ quote.querySelector('.ee-compose-quote-label').textContent =
3134
+ mode === 'forward' ? 'The forwarded message is added below your text:' : `${sender}'s message is quoted below your reply:`;
3135
+ // A shadow root cannot be attached twice, so each quote gets a fresh host
3136
+ const host = document.createElement('div');
3137
+ quote.querySelector('.ee-compose-quote-frame').replaceChildren(host);
3138
+ this._labelCollapsedThreads(this._renderMessageBody(host, original));
3139
+ quote.hidden = false;
3140
+ }
3141
+
3142
+ // Shows the Cc and Bcc fields named true and hides the rest; the link offers whichever is hidden
3143
+ _showCopyFields(show) {
3144
+ const { form } = this._compose.els;
3145
+ const hidden = [];
3146
+ for (const key of ['cc', 'bcc']) {
3147
+ form.querySelector(`[data-field="${key}"]`).hidden = !show[key];
3148
+ if (!show[key]) {
3149
+ hidden.push(key === 'cc' ? 'Cc' : 'Bcc');
3150
+ }
3151
+ }
3152
+ const link = form.querySelector('[data-action="show-cc"]');
3153
+ link.hidden = !hidden.length;
3154
+ link.textContent = hidden.join(' / ');
3155
+ }
3156
+
3157
+ // Empties the form and starts a new compose state; the element references are kept
3158
+ _resetCompose() {
3159
+ const { els } = this._compose;
3160
+ els.form.reset();
3161
+ els.chips.replaceChildren();
3162
+ els.fileInput.value = '';
3163
+ els.forwardAttachments.hidden = true;
3164
+ els.quote.hidden = true;
3165
+ els.quote.querySelector('.ee-compose-quote-frame').replaceChildren();
3166
+ this._compose = { els, reference: null, files: [] };
3167
+ this._showCopyFields({ cc: false, bcc: false });
3168
+ }
3169
+
3170
+ _closeCompose() {
3171
+ if (this._compose && this._compose.els) {
3172
+ this._compose.els.modal.classList.remove('show');
3173
+ this._resetCompose();
3174
+ }
3175
+ }
3176
+
3177
+ // An alert shown from inside the compose form: the modal steps aside so the host's dialog is
3178
+ // not stacked under it, and comes back with the form as it was
3179
+ async _composeAlert(message, title, focusField = null) {
3180
+ const { modal, form } = this._compose.els;
3181
+ modal.classList.remove('show');
3182
+ await this.alertMethod(message, title, null, 'OK');
3183
+ if (this._destroyed) {
3184
+ return;
3185
+ }
3186
+ modal.classList.add('show');
3187
+ const field = focusField ? form.elements[focusField] : null;
3188
+ if (field) {
3189
+ setTimeout(() => field.focus(), 100);
3190
+ }
3191
+ }
3192
+
3193
+ _renderComposeChips() {
3194
+ this._compose.els.chips.innerHTML = this._compose.files
3195
+ .map(
3196
+ (file, index) => `
3197
+ <span class="ee-compose-chip">
3198
+ ${icon('paperclip', 12)}
3199
+ <span class="ee-compose-chip-name">${this.escapeHtml(file.name)}</span>
3200
+ <span class="ee-compose-chip-size">${this.formatFileSize(file.size)}</span>
3201
+ <button type="button" class="ee-compose-chip-remove" data-index="${index}" aria-label="Remove ${this.escapeHtml(file.name)}" title="Remove">${icon('close', 12)}</button>
3202
+ </span>`
3203
+ )
3204
+ .join('');
3205
+ }
3206
+
3207
+ _readFileAsBase64(file) {
3208
+ return new Promise((resolve, reject) => {
3209
+ const reader = new FileReader();
3210
+ reader.onload = () => {
3211
+ const result = String(reader.result || '');
3212
+ resolve(result.slice(result.indexOf(',') + 1));
3213
+ };
3214
+ reader.onerror = () => reject(reader.error || new Error(`Could not read ${file.name}`));
3215
+ reader.readAsDataURL(file);
3216
+ });
3217
+ }
3218
+
3219
+ // Takes picked files into the form within the size limit. They are kept as File objects and
3220
+ // read only when the message is sent, so a removed file is never read at all.
3221
+ async _addComposeFiles(files) {
3222
+ let total = this._compose.files.reduce((sum, file) => sum + file.size, 0);
3223
+ const skipped = [];
3224
+ for (const file of files) {
3225
+ if (total + file.size > this.maxAttachmentSize) {
3226
+ skipped.push(file.name);
3227
+ continue;
3228
+ }
3229
+ total += file.size;
3230
+ this._compose.files.push(file);
3231
+ }
3232
+ this._renderComposeChips();
3233
+ if (skipped.length) {
3234
+ await this._composeAlert(
3235
+ `Attachments are limited to ${this.formatFileSize(this.maxAttachmentSize)} in total. Not attached: ${skipped.join(', ')}`,
3236
+ 'Attachment Too Large'
3237
+ );
3238
+ }
3239
+ }
3240
+
3241
+ _readComposeAttachments(files) {
3242
+ return Promise.all(
3243
+ files.map(async file => ({
3244
+ filename: file.name,
3245
+ contentType: file.type || 'application/octet-stream',
3246
+ content: await this._readFileAsBase64(file)
3247
+ }))
3248
+ );
3249
+ }
3250
+
3251
+ // The form as a submission: parsed recipients, the text, the reference and the picked files,
3252
+ // plus the first reason it cannot go out as asked (null when it can). requireMessage applies
3253
+ // the send rules: a recipient, and some text unless the message is a forward.
3254
+ _readComposeForm(requireMessage) {
3255
+ const { form } = this._compose.els;
3256
+ const fields = {};
3257
+ const invalid = [];
3258
+ for (const key of ['to', 'cc', 'bcc']) {
3259
+ fields[key] = this.parseAddressList(form.elements[key].value);
3260
+ invalid.push(...fields[key].filter(entry => !ADDRESS_PATTERN.test(entry.address)).map(entry => entry.address || entry.name));
3261
+ }
3262
+
3263
+ let reference = this._compose.reference;
3264
+ const isForward = !!reference && reference.action === 'forward';
3265
+ if (isForward) {
3266
+ reference = { ...reference, forwardAttachments: form.elements.forwardAttachments.checked };
3267
+ }
3268
+
3269
+ const draft = {
3270
+ to: fields.to,
3271
+ subject: form.elements.subject.value.trim(),
3272
+ text: form.elements.message.value,
3273
+ files: this._compose.files,
3274
+ options: { cc: fields.cc, bcc: fields.bcc, reference }
3275
+ };
3276
+
3277
+ const empty = !fields.to.length && !fields.cc.length && !fields.bcc.length && !draft.subject && !draft.text.trim() && !draft.files.length && !reference;
3278
+ if (requireMessage && !fields.to.length) {
3279
+ draft.problem = { message: 'Add at least one recipient.', field: 'to' };
3280
+ } else if (!requireMessage && empty) {
3281
+ draft.problem = { message: 'Nothing to save - fill in at least one field first.', field: 'to' };
3282
+ } else if (invalid.length) {
3283
+ draft.problem = { message: `Not a valid email address: ${invalid.join(', ')}`, field: 'to' };
3284
+ } else if (requireMessage && !draft.text.trim() && !isForward) {
3285
+ // A forward can go without a note of its own; anything else needs some text
3286
+ draft.problem = { message: 'Write a message before sending.', field: 'message' };
3287
+ }
3288
+ return draft;
3289
+ }
3290
+
3291
+ // Runs a compose request with its button showing progress. The form is checked first, the
3292
+ // picked files are read, and on success the form closes and the result is returned; on any
3293
+ // failure the reason is shown over the form, kept as it was, and the result is null.
3294
+ async _runComposeAction(button, busyText, errorTitle, requireMessage, submit) {
3295
+ const draft = this._readComposeForm(requireMessage);
3296
+ if (draft.problem) {
3297
+ await this._composeAlert(draft.problem.message, 'Validation Error', draft.problem.field);
3298
+ return null;
3299
+ }
3300
+
3301
+ const originalText = button.textContent;
3302
+ button.disabled = true;
3303
+ button.textContent = busyText;
3304
+ try {
3305
+ const attachments = await this._readComposeAttachments(draft.files);
3306
+ const result = await submit(draft.to, draft.subject, draft.text, { ...draft.options, attachments });
3307
+ this._closeCompose();
3308
+ return result || {};
3309
+ } catch (error) {
3310
+ console.error(`${errorTitle}:`, error);
3311
+ await this._composeAlert(this._formatSendError(error), errorTitle, 'to');
3312
+ return null;
3313
+ } finally {
3314
+ button.disabled = false;
3315
+ button.textContent = originalText;
3316
+ }
3317
+ }
3318
+
2607
3319
  setupComposeModal() {
2608
3320
  if (typeof document === 'undefined' || !this.container) {
2609
3321
  return;
2610
3322
  }
2611
3323
 
2612
- const composeButton = this.container.querySelector('.ee-compose-button');
2613
3324
  const modal = this.container.querySelector('.ee-compose-modal');
2614
- const closeButton = this.container.querySelector('.ee-compose-close');
2615
- const cancelButton = this.container.querySelector('.ee-compose-cancel');
2616
- const saveDraftButton = this.container.querySelector('.ee-compose-save-draft');
2617
- const sendButton = this.container.querySelector('.ee-compose-send');
2618
- const form = this.container.querySelector('.ee-compose-form');
2619
-
2620
- // Open modal
2621
- composeButton.addEventListener('click', () => {
2622
- modal.classList.add('show');
2623
- // Focus the To field
2624
- const toField = form.querySelector('input[name="to"]');
2625
- setTimeout(() => toField.focus(), 100);
2626
- });
2627
-
2628
- // Close modal handlers
2629
- const closeModal = () => {
2630
- modal.classList.remove('show');
2631
- form.reset();
3325
+ const els = {
3326
+ modal,
3327
+ form: modal.querySelector('.ee-compose-form'),
3328
+ title: modal.querySelector('.ee-compose-title'),
3329
+ chips: modal.querySelector('.ee-compose-chips'),
3330
+ fileInput: modal.querySelector('.ee-compose-file-input'),
3331
+ forwardAttachments: modal.querySelector('.ee-compose-forward-attachments'),
3332
+ quote: modal.querySelector('.ee-compose-quote')
2632
3333
  };
3334
+ const { form, fileInput, chips } = els;
3335
+ this._compose = { els, reference: null, files: [] };
3336
+
3337
+ this.container.querySelector('.ee-compose-button').addEventListener('click', () => this.compose());
2633
3338
 
2634
- closeButton.addEventListener('click', closeModal);
2635
- cancelButton.addEventListener('click', closeModal);
3339
+ const closeCompose = () => this._closeCompose();
3340
+ modal.querySelector('.ee-compose-close').addEventListener('click', closeCompose);
3341
+ modal.querySelector('.ee-compose-cancel').addEventListener('click', closeCompose);
2636
3342
 
2637
3343
  // Close on backdrop click
2638
3344
  modal.addEventListener('click', e => {
2639
3345
  if (e.target === modal) {
2640
- closeModal();
3346
+ closeCompose();
2641
3347
  }
2642
3348
  });
2643
3349
 
2644
3350
  // Close on Escape key
2645
3351
  this._composeKeydownHandler = e => {
2646
3352
  if (e.key === 'Escape' && modal.classList.contains('show')) {
2647
- closeModal();
3353
+ closeCompose();
2648
3354
  }
2649
3355
  };
2650
3356
  document.addEventListener('keydown', this._composeKeydownHandler);
2651
3357
 
3358
+ form.querySelector('[data-action="show-cc"]').addEventListener('click', () => {
3359
+ const ccShown = !form.querySelector('[data-field="cc"]').hidden;
3360
+ this._showCopyFields({ cc: true, bcc: true });
3361
+ (ccShown ? form.elements.bcc : form.elements.cc).focus();
3362
+ });
3363
+
3364
+ form.querySelector('[data-action="attach"]').addEventListener('click', () => fileInput.click());
3365
+ fileInput.addEventListener('change', () => {
3366
+ const files = Array.from(fileInput.files || []);
3367
+ fileInput.value = '';
3368
+ this._fireAndForget(this._addComposeFiles(files));
3369
+ });
3370
+ chips.addEventListener('click', e => {
3371
+ const remove = e.target.closest('.ee-compose-chip-remove');
3372
+ if (remove) {
3373
+ this._compose.files.splice(Number(remove.dataset.index), 1);
3374
+ this._renderComposeChips();
3375
+ }
3376
+ });
3377
+
2652
3378
  // Save the composed message as a draft instead of sending it
3379
+ const saveDraftButton = modal.querySelector('.ee-compose-save-draft');
2653
3380
  saveDraftButton.addEventListener('click', async () => {
2654
- const formData = new FormData(form);
2655
- const to = formData.get('to').trim();
2656
- const subject = formData.get('subject').trim();
2657
- const message = formData.get('message').trim();
2658
-
2659
- if (!to && !subject && !message) {
2660
- modal.classList.remove('show');
2661
- await this.alertMethod('Nothing to save - fill in at least one field first.', 'Validation Error', null, 'OK');
2662
- modal.classList.add('show');
2663
- setTimeout(() => form.querySelector('input[name="to"]').focus(), 100);
3381
+ const response = await this._runComposeAction(saveDraftButton, 'Saving...', 'Save Error', false, (...args) => this.saveDraft(...args));
3382
+ if (!response) {
2664
3383
  return;
2665
3384
  }
2666
-
2667
- const originalText = saveDraftButton.textContent;
2668
- saveDraftButton.disabled = true;
2669
- saveDraftButton.textContent = 'Saving...';
2670
-
2671
- try {
2672
- const response = await this.saveDraft(to || null, subject, message);
2673
- closeModal();
2674
- await this.alertMethod('Draft saved to the Drafts folder.', 'Success', null, 'OK');
2675
- // Refresh the list when the user is looking at the Drafts folder
2676
- if (!this._destroyed && response && response.path && this.currentFolder === response.path) {
2677
- await this.loadMessages(this.currentFolder);
2678
- }
2679
- } catch (error) {
2680
- console.error('Failed to save draft:', error);
2681
- // Close modal before showing error alert, then reopen with preserved values
2682
- modal.classList.remove('show');
2683
- const errorMessage = this._formatSendError(error);
2684
- await this.alertMethod(errorMessage, 'Save Error', null, 'OK');
2685
- modal.classList.add('show');
2686
- setTimeout(() => form.querySelector('input[name="to"]').focus(), 100);
2687
- } finally {
2688
- saveDraftButton.disabled = false;
2689
- saveDraftButton.textContent = originalText;
3385
+ await this.alertMethod('Draft saved to the Drafts folder.', 'Success', null, 'OK');
3386
+ // Refresh the list when the user is looking at the Drafts folder
3387
+ if (!this._destroyed && response.path && this.currentFolder === response.path) {
3388
+ this._fireAndForget(this.loadMessages(this.currentFolder));
2690
3389
  }
2691
3390
  });
2692
3391
 
2693
3392
  // Send email
3393
+ const sendButton = modal.querySelector('.ee-compose-send');
2694
3394
  sendButton.addEventListener('click', async () => {
2695
- const formData = new FormData(form);
2696
- const to = formData.get('to').trim();
2697
- const subject = formData.get('subject').trim();
2698
- const message = formData.get('message').trim();
2699
-
2700
- if (!to || !message) {
2701
- // Close modal temporarily to show alert, then reopen
2702
- modal.classList.remove('show');
2703
- await this.alertMethod('Please fill in the recipient and message fields.', 'Validation Error', null, 'OK');
2704
- modal.classList.add('show');
2705
- // Re-focus the appropriate field
2706
- const fieldToFocus = !to ? form.querySelector('input[name="to"]') : form.querySelector('textarea[name="message"]');
2707
- setTimeout(() => fieldToFocus.focus(), 100);
2708
- return;
2709
- }
2710
-
2711
- // Disable send button and show loading state
2712
- const originalText = sendButton.textContent;
2713
- sendButton.disabled = true;
2714
- sendButton.textContent = 'Sending...';
2715
-
2716
- try {
2717
- await this.sendMessage(to, subject, message);
2718
- // Close modal before showing success alert
2719
- closeModal();
2720
- await this.alertMethod('Email sent successfully!', 'Success', null, 'OK');
2721
- } catch (error) {
2722
- console.error('Failed to send email:', error);
2723
- // Close modal before showing error alert
2724
- modal.classList.remove('show');
2725
- const errorMessage = this._formatSendError(error);
2726
- await this.alertMethod(errorMessage, 'Send Error', null, 'OK');
2727
-
2728
- // Reopen modal with preserved values after error alert
2729
- modal.classList.add('show');
2730
- // Re-focus the To field to allow user to continue editing
2731
- const toField = form.querySelector('input[name="to"]');
2732
- setTimeout(() => toField.focus(), 100);
2733
- } finally {
2734
- // Re-enable send button
2735
- sendButton.disabled = false;
2736
- sendButton.textContent = originalText;
3395
+ const response = await this._runComposeAction(sendButton, 'Sending...', 'Send Error', true, (...args) => this.sendMessage(...args));
3396
+ if (response) {
3397
+ // Submitting only queues the message; delivery happens afterwards and can still fail
3398
+ await this.alertMethod('Message queued for delivery.', 'Queued', null, 'OK');
2737
3399
  }
2738
3400
  });
2739
3401
 
2740
3402
  // Handle Enter key in form (Ctrl+Enter to send)
2741
3403
  form.addEventListener('keydown', e => {
2742
- if (e.key === 'Enter' && e.ctrlKey) {
3404
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
2743
3405
  e.preventDefault();
2744
3406
  sendButton.click();
2745
3407
  }
@@ -2868,6 +3530,13 @@ export class EmailEngineClient {
2868
3530
  // paint their own loading states from this point on.
2869
3531
  this._setPaneHtml('.ee-message-list', this._messageListPlaceholder());
2870
3532
 
3533
+ // A deep-linked message loads alongside the folders, not after them. Only the first load
3534
+ // follows the link: a Retry after a folder failure starts from the inbox as usual. A
3535
+ // message that fails has already put its error in the viewer.
3536
+ const messageId = this.initialMessage;
3537
+ this.initialMessage = null;
3538
+ const message = messageId ? this.loadMessage(messageId).catch(() => null) : Promise.resolve(null);
3539
+
2871
3540
  return this.loadFolders()
2872
3541
  .catch(error => {
2873
3542
  // loadFolders reports into the sidebar, but the message list is the
@@ -2876,21 +3545,39 @@ export class EmailEngineClient {
2876
3545
  this._renderPaneError('.ee-message-list', 'Folders unavailable', error, () => this._loadInitialView());
2877
3546
  throw error;
2878
3547
  })
2879
- .then(() => {
2880
- const inbox =
2881
- this.folders.find(f => f.specialUse && f.specialUse.includes('\\Inbox')) ||
2882
- this.folders.find(f => f.name.toLowerCase() === 'inbox') ||
2883
- this.folders[0];
2884
- if (inbox) {
2885
- return this.loadMessages(inbox.path);
2886
- }
2887
- })
3548
+ .then(async () => this._listFolderOf(await message))
2888
3549
  .catch(error => {
2889
3550
  // Both loadFolders and loadMessages have already rendered a panel
2890
3551
  console.error('Failed to load the initial view:', error);
2891
3552
  });
2892
3553
  }
2893
3554
 
3555
+ _inboxFolder() {
3556
+ return (
3557
+ this.folders.find(f => f.specialUse && f.specialUse.includes('\\Inbox')) ||
3558
+ this.folders.find(f => f.name.toLowerCase() === 'inbox') ||
3559
+ this.folders[0]
3560
+ );
3561
+ }
3562
+
3563
+ // Lists the folder holding a message, or the inbox when there is no message or it reports no
3564
+ // folder (Gmail API accounts) or one that is not listed
3565
+ _listFolderOf(message) {
3566
+ const folder = (message && message.path && this.folders.find(f => f.path === message.path)) || this._inboxFolder();
3567
+ if (folder && !this._destroyed) {
3568
+ return this.loadMessages(folder.path);
3569
+ }
3570
+ }
3571
+
3572
+ // Opens one message by its EmailEngine ID and lists the folder holding it. A message that
3573
+ // cannot be loaded leaves its error in the viewer and the inbox in the list, so the reader
3574
+ // still has somewhere to go.
3575
+ async openMessage(messageId) {
3576
+ const [message] = await Promise.all([this.loadMessage(messageId).catch(() => null), this.folders.length ? null : this.loadFolders()]);
3577
+ await this._listFolderOf(message);
3578
+ return message;
3579
+ }
3580
+
2894
3581
  _updateActivity() {
2895
3582
  this.lastActivity = Date.now();
2896
3583
  }
@@ -2943,9 +3630,9 @@ export class EmailEngineClient {
2943
3630
  this.container.querySelectorAll('.ee-client, .ee-compose-button, .ee-compose-modal').forEach(el => el.classList.toggle('ee-dark-mode', this.darkMode));
2944
3631
 
2945
3632
  // Update toggle button icon
2946
- const icon = this.container.querySelector('.ee-dark-mode-icon');
2947
- if (icon) {
2948
- icon.textContent = this.darkMode ? '☀️' : '🌙';
3633
+ const toggleIcon = this.container.querySelector('.ee-dark-mode-icon');
3634
+ if (toggleIcon) {
3635
+ toggleIcon.innerHTML = icon(this.darkMode ? 'sun' : 'moon', 14);
2949
3636
  }
2950
3637
  }
2951
3638