@file-viewer/renderer-email 3.1.1 → 3.1.2

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.
package/dist/email.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { createFileViewerTranslator, disposeFileViewerRendered, resolveFileViewerColorScheme, } from '@file-viewer/core';
2
+ import { createEmailHtmlDocument, createEmailImageResource } from './emailHtml.js';
3
+ import { getMsgLabels } from './msgMessages.js';
2
4
  const emailStyle = `
3
5
  .email-viewer{position:relative;height:100%;min-height:0;display:flex;flex-direction:column;background:#f3f6f8;color:#172033;box-sizing:border-box}
4
6
  .email-viewer *{box-sizing:border-box}
5
- .email-header{padding:18px 22px;border-bottom:1px solid rgba(23,32,51,.08);background:#fff}
7
+ .email-header{max-height:35%;overflow:auto;flex:0 0 auto;padding:18px 22px;border-bottom:1px solid rgba(23,32,51,.08);background:#fff}
6
8
  .email-header>span{color:#1f7a58;font-size:12px;font-weight:900}
7
9
  .email-header h2{margin:4px 0 12px;font-size:22px;line-height:1.25}
8
10
  .email-meta{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 18px}
@@ -10,7 +12,7 @@ const emailStyle = `
10
12
  .email-meta strong{margin-right:8px;color:#172033}
11
13
  .email-body{flex:1;min-height:0;display:grid;grid-template-columns:minmax(240px,300px) minmax(0,1fr)}
12
14
  .email-sidebar{min-height:0;display:flex;flex-direction:column;gap:14px;padding:14px;border-right:1px solid rgba(23,32,51,.08);background:rgba(255,255,255,.7)}
13
- .body-tabs{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px;padding:4px;border-radius:12px;background:rgba(23,32,51,.06)}
15
+ .body-tabs{display:grid;grid-template-columns:repeat(auto-fit,minmax(52px,1fr));gap:6px;padding:4px;border-radius:12px;background:rgba(23,32,51,.06)}
14
16
  .body-tabs button,.attachment-item,.attachment-preview-head button{font:inherit;cursor:pointer}
15
17
  .body-tabs button{height:34px;border:0;border-radius:9px;background:transparent;color:#64748b;font-size:12px;font-weight:800}
16
18
  .body-tabs button.active{background:#fff;color:#172033}
@@ -24,7 +26,13 @@ const emailStyle = `
24
26
  .attachment-item span{grid-row:span 2;height:38px;display:inline-flex;align-items:center;justify-content:center;border-radius:10px;background:rgba(31,122,88,.12);color:#1f7a58;font-size:11px;font-weight:900}
25
27
  .attachment-item strong,.attachment-item em{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
26
28
  .attachment-item em{color:#64748b;font-size:12px;font-style:normal}
27
- .message-panel{min-width:0;min-height:0;display:grid;grid-template-rows:minmax(240px,46%) minmax(0,1fr)}
29
+ .message-panel{min-width:0;min-height:0;display:grid;grid-template-rows:minmax(0,1fr)}
30
+ .message-panel.has-attachment-preview{grid-template-rows:minmax(160px,46%) minmax(0,1fr)}
31
+ .email-rtf{height:100%;overflow:auto}
32
+ .email-notices{max-height:25%;overflow:auto;margin:0;padding:10px 22px;background:#fff7e8;color:#714700;font-size:13px;line-height:1.5}
33
+ .email-notices p{margin:4px 0}
34
+ .attachment-preview-actions{display:flex;gap:8px;align-items:center}
35
+ [data-viewer-theme='dark'] .email-notices{background:#332711;color:#f8daa0}
28
36
  .email-message-content{min-height:0}
29
37
  .email-html,.email-text{width:100%;height:100%;border:0;background:#fff}
30
38
  .email-text{margin:0;overflow:auto;padding:20px;white-space:pre-wrap;word-break:break-word;line-height:1.65}
@@ -47,7 +55,8 @@ const emailStyle = `
47
55
  [data-viewer-theme='dark'] .email-html{background:#111827;color-scheme:dark}
48
56
  [data-viewer-theme='dark'] .email-state{background:rgba(13,17,23,.9);color:#cbd5e1}
49
57
  @media (prefers-color-scheme:dark){[data-viewer-theme='system'] .email-viewer{background:#172033;color:#e5eef8}[data-viewer-theme='system'] .email-header,[data-viewer-theme='system'] .email-sidebar,[data-viewer-theme='system'] .attachment-item,[data-viewer-theme='system'] .email-text,[data-viewer-theme='system'] .attachment-preview-head{border-color:rgba(139,148,158,.2);background:#111827;color:#e5eef8}[data-viewer-theme='system'] .email-meta p,[data-viewer-theme='system'] .attachment-item em,[data-viewer-theme='system'] .attachment-title span,[data-viewer-theme='system'] .attachment-empty{color:#94a3b8}[data-viewer-theme='system'] .email-meta strong,[data-viewer-theme='system'] .attachment-title,[data-viewer-theme='system'] .attachment-item strong{color:#f8fafc}[data-viewer-theme='system'] .body-tabs{background:rgba(139,148,158,.12)}[data-viewer-theme='system'] .body-tabs button{color:#94a3b8}[data-viewer-theme='system'] .body-tabs button.active{background:#1f2937;color:#f8fafc}[data-viewer-theme='system'] .email-html{background:#111827;color-scheme:dark}[data-viewer-theme='system'] .email-state{background:rgba(13,17,23,.9);color:#cbd5e1}}
50
- @media (max-width:860px){.email-meta,.email-body{grid-template-columns:1fr}.email-body{grid-template-rows:auto minmax(0,1fr)}.email-sidebar{border-right:0;border-bottom:1px solid rgba(23,32,51,.08)}}
58
+ @media (prefers-reduced-motion:reduce){.email-state span{animation:none}}
59
+ @media (max-width:860px){.email-sidebar{max-height:220px;overflow:auto}.email-meta,.email-body{grid-template-columns:1fr}.email-body{grid-template-rows:auto minmax(0,1fr)}.email-sidebar{border-right:0;border-bottom:1px solid rgba(23,32,51,.08)}}
51
60
  `;
52
61
  const formatBytes = (value) => {
53
62
  if (!Number.isFinite(value) || value < 0) {
@@ -118,8 +127,7 @@ const createPostalAttachments = (email, objectUrls, cidUrls) => {
118
127
  return;
119
128
  }
120
129
  const buffer = await attachment.load();
121
- const url = URL.createObjectURL(new Blob([buffer], { type: attachment.mimeType }));
122
- objectUrls.push(url);
130
+ const url = createEmailImageResource(buffer, attachment.mimeType, objectUrls);
123
131
  cidUrls.set(normalizeContentId(attachment.contentId), url);
124
132
  })).then(() => attachments);
125
133
  };
@@ -177,42 +185,9 @@ const parseMbox = async (buffer, filename, objectUrls, cidUrls, t) => {
177
185
  attachments,
178
186
  };
179
187
  };
180
- const parseMsg = async (buffer, filename) => {
181
- var _a;
182
- const msgReaderModule = await import('@kenjiuno/msgreader');
183
- const MsgReader = (((_a = msgReaderModule.default) === null || _a === void 0 ? void 0 : _a.default) || msgReaderModule.default);
184
- const reader = new MsgReader(buffer);
185
- const fileData = reader.getFileData();
186
- const attachments = (fileData.attachments || []).map((attachment, index) => {
187
- const name = attachment.fileName || attachment.fileNameShort || attachment.name || `attachment-${index + 1}${attachment.extension || ''}`;
188
- return {
189
- id: `${index}-${name}`,
190
- name,
191
- mimeType: 'application/octet-stream',
192
- size: attachment.contentLength || attachment.size || 0,
193
- contentId: attachment.pidContentId,
194
- async load() {
195
- const file = reader.getAttachment(attachment);
196
- return toArrayBuffer(file.content);
197
- },
198
- };
199
- });
200
- return {
201
- kind: 'msg',
202
- subject: fileData.subject || filename,
203
- from: normalizeAddress({ name: fileData.senderName, address: fileData.senderEmail }),
204
- to: normalizeAddress(fileData.recipients || []).filter(item => item.name || item.address),
205
- cc: [],
206
- date: fileData.messageDeliveryTime || fileData.clientSubmitTime || fileData.creationTime,
207
- text: fileData.body,
208
- html: fileData.html || '',
209
- headers: fileData.headers,
210
- attachments,
211
- };
212
- };
213
- const parseEmail = (buffer, type, filename, objectUrls, cidUrls, t) => {
188
+ const parseEmail = (buffer, type, filename, objectUrls, cidUrls, t, signal) => {
214
189
  if (type === 'msg') {
215
- return parseMsg(buffer, filename);
190
+ return import('./msg.js').then(({ parseMsg }) => parseMsg(buffer, filename, objectUrls, cidUrls, signal));
216
191
  }
217
192
  if (type === 'mbox') {
218
193
  return parseMbox(buffer, filename, objectUrls, cidUrls, t);
@@ -236,37 +211,39 @@ const createElement = (tagName, className, text) => {
236
211
  };
237
212
  const getAttachmentExtension = (name) => {
238
213
  const index = name.lastIndexOf('.');
239
- return index >= 0 ? name.slice(index + 1).toLowerCase() : 'txt';
240
- };
241
- const createHtmlSrcdoc = (html, cidUrls, darkMode = false) => {
242
- let next = html;
243
- cidUrls.forEach((url, cid) => {
244
- const escaped = cid.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
245
- next = next.replace(new RegExp(`cid:${escaped}`, 'gi'), url);
246
- });
247
- const pageStyle = darkMode
248
- ? ':root{color-scheme:dark}body{background:#111827;color:#e5e7eb}'
249
- : ':root{color-scheme:light}body{background:#fff;color:#172033}';
250
- return `<!doctype html><html><head><meta charset="utf-8"><base target="_blank"><style>${pageStyle}body{margin:0;padding:18px;font-family:Aptos,"Segoe UI",sans-serif;line-height:1.6;word-break:break-word;}img{max-width:100%;height:auto;}</style></head><body>${next}</body></html>`;
214
+ return index >= 0 ? name.slice(index + 1).toLowerCase() : 'bin';
251
215
  };
252
216
  const appendMeta = (meta, label, value) => {
253
217
  const row = document.createElement('p');
254
218
  const strong = document.createElement('strong');
255
219
  strong.textContent = label;
220
+ row.title = value || '-';
256
221
  row.append(strong, document.createTextNode(value || '-'));
257
222
  meta.append(row);
258
223
  };
259
224
  export default async function renderEmail(buffer, target, type = 'eml', context) {
260
- var _a, _b, _c, _d;
225
+ var _a, _b, _c, _d, _e, _f;
226
+ type = type.toLowerCase().replace(/^\./, '');
261
227
  const normalizedType = type === 'msg' ? 'msg' : type === 'mbox' ? 'mbox' : 'eml';
262
228
  const filename = (context === null || context === void 0 ? void 0 : context.filename) || `message.${normalizedType}`;
263
229
  const objectUrls = [];
264
230
  const cidUrls = new Map();
265
231
  const t = createFileViewerTranslator(context === null || context === void 0 ? void 0 : context.options);
266
- const systemDark = (_c = (_b = (_a = target.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.matchMedia) === null || _b === void 0 ? void 0 : _b.call(_a, '(prefers-color-scheme: dark)').matches) !== null && _c !== void 0 ? _c : false;
267
- const darkMode = resolveFileViewerColorScheme((_d = context === null || context === void 0 ? void 0 : context.options) === null || _d === void 0 ? void 0 : _d.theme, systemDark) === 'dark';
232
+ const msgLabels = getMsgLabels(context === null || context === void 0 ? void 0 : context.options);
233
+ const controller = new AbortController();
234
+ const abortFromParent = () => { var _a; return controller.abort((_a = context === null || context === void 0 ? void 0 : context.signal) === null || _a === void 0 ? void 0 : _a.reason); };
235
+ if ((_a = context === null || context === void 0 ? void 0 : context.signal) === null || _a === void 0 ? void 0 : _a.aborted)
236
+ abortFromParent();
237
+ else
238
+ (_b = context === null || context === void 0 ? void 0 : context.signal) === null || _b === void 0 ? void 0 : _b.addEventListener('abort', abortFromParent, { once: true });
239
+ const signal = controller.signal;
240
+ const systemDark = (_e = (_d = (_c = target.ownerDocument.defaultView) === null || _c === void 0 ? void 0 : _c.matchMedia) === null || _d === void 0 ? void 0 : _d.call(_c, '(prefers-color-scheme: dark)').matches) !== null && _e !== void 0 ? _e : false;
241
+ const darkMode = resolveFileViewerColorScheme((_f = context === null || context === void 0 ? void 0 : context.options) === null || _f === void 0 ? void 0 : _f.theme, systemDark) === 'dark';
268
242
  const cleanups = [];
269
243
  let nestedRendered;
244
+ let bodyRendered;
245
+ let bodyVersion = 0;
246
+ let bodyController;
270
247
  let attachmentPreviewVersion = 0;
271
248
  let attachmentAbortController;
272
249
  let disposed = false;
@@ -303,11 +280,43 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
303
280
  root.append(errorElement);
304
281
  };
305
282
  const clearAttachmentPreview = async () => {
306
- await disposeFileViewerRendered(nestedRendered);
283
+ const previous = nestedRendered;
307
284
  nestedRendered = undefined;
285
+ await disposeFileViewerRendered(previous);
286
+ };
287
+ const clearBodyPreview = async () => {
288
+ const previous = bodyRendered;
289
+ bodyRendered = undefined;
290
+ await disposeFileViewerRendered(previous);
291
+ };
292
+ const cleanup = async () => {
293
+ var _a;
294
+ if (disposed)
295
+ return;
296
+ disposed = true;
297
+ controller.abort();
298
+ bodyVersion += 1;
299
+ attachmentPreviewVersion += 1;
300
+ bodyController === null || bodyController === void 0 ? void 0 : bodyController.abort();
301
+ attachmentAbortController === null || attachmentAbortController === void 0 ? void 0 : attachmentAbortController.abort();
302
+ (_a = context === null || context === void 0 ? void 0 : context.signal) === null || _a === void 0 ? void 0 : _a.removeEventListener('abort', abortFromParent);
303
+ cleanups.splice(0).forEach(cleanup => cleanup());
304
+ try {
305
+ await Promise.allSettled([clearAttachmentPreview(), clearBodyPreview()]);
306
+ }
307
+ finally {
308
+ objectUrls.splice(0).forEach(url => URL.revokeObjectURL(url));
309
+ cidUrls.clear();
310
+ if (root.parentNode === target)
311
+ target.replaceChildren();
312
+ }
308
313
  };
309
314
  const downloadAttachment = async (attachment) => {
315
+ signal.throwIfAborted();
310
316
  const attachmentBuffer = await attachment.load();
317
+ if (disposed)
318
+ return;
319
+ signal.throwIfAborted();
311
320
  const url = URL.createObjectURL(new Blob([attachmentBuffer], { type: attachment.mimeType || 'application/octet-stream' }));
312
321
  objectUrls.push(url);
313
322
  const link = document.createElement('a');
@@ -317,8 +326,9 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
317
326
  link.click();
318
327
  link.remove();
319
328
  };
320
- const renderParsedEmail = (parsed) => {
321
- let activeBody = parsed.html ? 'html' : parsed.text ? 'text' : 'headers';
329
+ const renderParsedEmail = async (parsed) => {
330
+ var _a, _b;
331
+ let activeBody = parsed.html ? 'html' : parsed.rtf && (context === null || context === void 0 ? void 0 : context.renderNestedBuffer) ? 'rtf' : parsed.text ? 'text' : 'headers';
322
332
  let activeAttachment = null;
323
333
  const tabButtons = [];
324
334
  const attachmentButtons = [];
@@ -328,10 +338,14 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
328
338
  header.append(createElement('h2', undefined, parsed.subject || filename));
329
339
  const meta = createElement('div', 'email-meta');
330
340
  appendMeta(meta, t('email.meta.from'), addressText(parsed.from));
341
+ if ((_a = parsed.sender) === null || _a === void 0 ? void 0 : _a.length)
342
+ appendMeta(meta, msgLabels.sender, addressText(parsed.sender));
331
343
  appendMeta(meta, t('email.meta.to'), addressText(parsed.to));
332
344
  if (parsed.cc.length) {
333
345
  appendMeta(meta, t('email.meta.cc'), addressText(parsed.cc));
334
346
  }
347
+ if ((_b = parsed.bcc) === null || _b === void 0 ? void 0 : _b.length)
348
+ appendMeta(meta, msgLabels.bcc, addressText(parsed.bcc));
335
349
  appendMeta(meta, t('email.meta.date'), parsed.date || '-');
336
350
  header.append(meta);
337
351
  const body = createElement('div', 'email-body');
@@ -346,28 +360,104 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
346
360
  const attachmentDownload = createElement('button', undefined, t('email.attachments.download'));
347
361
  attachmentDownload.type = 'button';
348
362
  const attachmentTarget = createElement('div', 'attachment-target');
349
- attachmentPreviewHead.append(attachmentPreviewTitle, attachmentDownload);
363
+ const attachmentClose = createElement('button', undefined, '×');
364
+ attachmentClose.type = 'button';
365
+ attachmentClose.setAttribute('aria-label', msgLabels.close);
366
+ attachmentClose.title = msgLabels.close;
367
+ const attachmentActions = createElement('div', 'attachment-preview-actions');
368
+ attachmentActions.append(attachmentDownload, attachmentClose);
369
+ attachmentPreviewHead.append(attachmentPreviewTitle, attachmentActions);
350
370
  attachmentPreview.append(attachmentPreviewHead, attachmentTarget);
351
- const renderMessageContent = () => {
352
- messageContent.replaceChildren();
353
- if (activeBody === 'html' && parsed.html) {
354
- const iframe = createElement('iframe', 'email-html');
355
- iframe.setAttribute('sandbox', '');
356
- iframe.srcdoc = createHtmlSrcdoc(parsed.html, cidUrls, darkMode);
357
- messageContent.append(iframe);
358
- return;
359
- }
371
+ const notices = createElement('div', 'email-notices');
372
+ notices.setAttribute('role', 'status');
373
+ const noticeKeys = new Set(parsed.warnings || []);
374
+ const renderNotices = () => {
375
+ notices.replaceChildren();
376
+ noticeKeys.forEach(key => notices.append(createElement('p', undefined, msgLabels[key])));
377
+ notices.hidden = !noticeKeys.size;
378
+ };
379
+ if (parsed.rtf && !parsed.html && !(context === null || context === void 0 ? void 0 : context.renderNestedBuffer))
380
+ noticeKeys.add('email.msg.rtfUnavailable');
381
+ renderNotices();
382
+ const renderPlainBody = (mode) => {
360
383
  const pre = createElement('pre', 'email-text');
361
- pre.textContent = activeBody === 'text' ? parsed.text || '' : parsed.headers || '';
362
- messageContent.append(pre);
384
+ pre.textContent = mode === 'text' ? parsed.text || '' : parsed.headers || '';
385
+ messageContent.replaceChildren(pre);
386
+ };
387
+ const renderMessageContent = async () => {
388
+ var _a;
389
+ const version = ++bodyVersion;
390
+ bodyController === null || bodyController === void 0 ? void 0 : bodyController.abort();
391
+ const current = new AbortController();
392
+ bodyController = current;
393
+ const abort = () => current.abort(signal.reason);
394
+ if (signal.aborted)
395
+ abort();
396
+ else
397
+ signal.addEventListener('abort', abort, { once: true });
398
+ const stale = () => disposed || version !== bodyVersion || current.signal.aborted;
399
+ try {
400
+ await clearBodyPreview();
401
+ if (stale())
402
+ return;
403
+ messageContent.replaceChildren();
404
+ if (activeBody === 'html' && parsed.html) {
405
+ const iframe = createElement('iframe', 'email-html');
406
+ iframe.title = parsed.subject || filename;
407
+ iframe.setAttribute('sandbox', '');
408
+ iframe.referrerPolicy = 'no-referrer';
409
+ iframe.srcdoc = createEmailHtmlDocument(parsed.html, cidUrls, darkMode, target.ownerDocument);
410
+ messageContent.append(iframe);
411
+ }
412
+ else if (activeBody === 'rtf' && parsed.rtf && (context === null || context === void 0 ? void 0 : context.renderNestedBuffer)) {
413
+ const child = createElement('div', 'email-rtf');
414
+ messageContent.append(child);
415
+ // Reuse the host's opt-in RTF capability (RTF.js), like attachments.
416
+ // A mail body must not inherit the host's external-resource opt-in.
417
+ const rendered = await context.renderNestedBuffer(parsed.rtf, 'rtf', child, {
418
+ ...context,
419
+ filename: `${filename}.rtf`,
420
+ signal: current.signal,
421
+ options: {
422
+ ...context.options,
423
+ docx: { ...(_a = context.options) === null || _a === void 0 ? void 0 : _a.docx, externalResourcePolicy: 'block', externalLinkPolicy: 'block' },
424
+ },
425
+ });
426
+ if (stale()) {
427
+ await disposeFileViewerRendered(rendered);
428
+ return;
429
+ }
430
+ bodyRendered = rendered;
431
+ }
432
+ else {
433
+ renderPlainBody(activeBody === 'headers' ? 'headers' : 'text');
434
+ }
435
+ }
436
+ catch (error) {
437
+ if (stale())
438
+ return;
439
+ if (activeBody === 'rtf') {
440
+ noticeKeys.add('email.msg.rtfUnavailable');
441
+ renderNotices();
442
+ renderPlainBody(parsed.text ? 'text' : 'headers');
443
+ }
444
+ else {
445
+ throw error;
446
+ }
447
+ }
448
+ finally {
449
+ signal.removeEventListener('abort', abort);
450
+ }
363
451
  };
364
452
  const syncTabState = () => {
365
453
  tabButtons.forEach(({ mode, button }) => {
366
454
  button.classList.toggle('active', mode === activeBody);
455
+ button.setAttribute('aria-pressed', String(mode === activeBody));
367
456
  });
368
457
  };
369
458
  const bodyModes = [
370
459
  { key: 'html', label: 'HTML', disabled: !parsed.html },
460
+ ...(parsed.rtf ? [{ key: 'rtf', label: 'RTF', disabled: !(context === null || context === void 0 ? void 0 : context.renderNestedBuffer) }] : []),
371
461
  { key: 'text', label: t('email.tabs.text'), disabled: !parsed.text },
372
462
  { key: 'headers', label: t('email.tabs.headers'), disabled: !parsed.headers },
373
463
  ];
@@ -381,7 +471,10 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
381
471
  }
382
472
  activeBody = mode.key;
383
473
  syncTabState();
384
- renderMessageContent();
474
+ void renderMessageContent().catch(error => {
475
+ if (!disposed && !signal.aborted)
476
+ showError(error instanceof Error ? error.message : String(error));
477
+ });
385
478
  });
386
479
  tabButtons.push({ mode: mode.key, button });
387
480
  tabs.append(button);
@@ -400,27 +493,36 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
400
493
  });
401
494
  };
402
495
  const previewAttachment = async (attachment) => {
403
- var _a, _b, _c;
496
+ var _a;
404
497
  const previewVersion = ++attachmentPreviewVersion;
405
498
  attachmentAbortController === null || attachmentAbortController === void 0 ? void 0 : attachmentAbortController.abort();
406
499
  const previewAbortController = new AbortController();
407
500
  attachmentAbortController = previewAbortController;
408
- const abortFromParent = () => { var _a; return previewAbortController.abort((_a = context === null || context === void 0 ? void 0 : context.signal) === null || _a === void 0 ? void 0 : _a.reason); };
409
- if ((_a = context === null || context === void 0 ? void 0 : context.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
410
- abortFromParent();
411
- }
412
- else {
413
- (_b = context === null || context === void 0 ? void 0 : context.signal) === null || _b === void 0 ? void 0 : _b.addEventListener('abort', abortFromParent, { once: true });
414
- }
501
+ const abort = () => previewAbortController.abort(signal.reason);
502
+ if (signal.aborted)
503
+ abort();
504
+ else
505
+ signal.addEventListener('abort', abort, { once: true });
506
+ const stale = () => disposed || previewVersion !== attachmentPreviewVersion || previewAbortController.signal.aborted;
415
507
  activeAttachment = attachment;
416
508
  syncAttachmentState();
417
509
  attachmentPreview.hidden = false;
510
+ messagePanel.classList.add('has-attachment-preview');
511
+ errorElement === null || errorElement === void 0 ? void 0 : errorElement.remove();
512
+ errorElement = null;
418
513
  attachmentPreviewTitle.textContent = attachment.name;
419
514
  showLoading(t('email.attachments.opening', { name: attachment.name }));
420
515
  try {
421
516
  await clearAttachmentPreview();
517
+ if (stale())
518
+ return;
422
519
  attachmentTarget.replaceChildren();
423
520
  const attachmentBuffer = await attachment.load();
521
+ if (stale())
522
+ return;
523
+ const sizeLabel = (_a = attachmentButtons.find(item => item.id === attachment.id)) === null || _a === void 0 ? void 0 : _a.button.querySelector('em');
524
+ if (sizeLabel)
525
+ sizeLabel.textContent = formatBytes(attachmentBuffer.byteLength);
424
526
  const child = createElement('div', 'email-attachment-render');
425
527
  attachmentTarget.append(child);
426
528
  const extension = getAttachmentExtension(attachment.name);
@@ -431,7 +533,7 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
431
533
  options: context.options,
432
534
  signal: previewAbortController.signal,
433
535
  });
434
- if (disposed || previewVersion !== attachmentPreviewVersion || previewAbortController.signal.aborted) {
536
+ if (stale()) {
435
537
  await disposeFileViewerRendered(nextRendered);
436
538
  return;
437
539
  }
@@ -442,14 +544,14 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
442
544
  }
443
545
  }
444
546
  catch (nextError) {
445
- if (disposed || previewVersion !== attachmentPreviewVersion || previewAbortController.signal.aborted) {
547
+ if (stale()) {
446
548
  return;
447
549
  }
448
550
  console.error(nextError);
449
551
  showError(nextError instanceof Error ? nextError.message : String(nextError));
450
552
  }
451
553
  finally {
452
- (_c = context === null || context === void 0 ? void 0 : context.signal) === null || _c === void 0 ? void 0 : _c.removeEventListener('abort', abortFromParent);
554
+ signal.removeEventListener('abort', abort);
453
555
  if (attachmentAbortController === previewAbortController) {
454
556
  attachmentAbortController = undefined;
455
557
  }
@@ -471,41 +573,52 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
471
573
  attachmentButtons.push({ id: attachment.id, button });
472
574
  attachmentPanel.append(button);
473
575
  });
576
+ listen(attachmentClose, 'click', () => {
577
+ var _a;
578
+ attachmentPreviewVersion += 1;
579
+ attachmentAbortController === null || attachmentAbortController === void 0 ? void 0 : attachmentAbortController.abort();
580
+ attachmentAbortController = undefined;
581
+ const previous = activeAttachment;
582
+ activeAttachment = null;
583
+ syncAttachmentState();
584
+ attachmentPreview.hidden = true;
585
+ messagePanel.classList.remove('has-attachment-preview');
586
+ hideLoading();
587
+ void clearAttachmentPreview().catch(() => { });
588
+ attachmentTarget.replaceChildren();
589
+ (_a = attachmentButtons.find(item => item.id === (previous === null || previous === void 0 ? void 0 : previous.id))) === null || _a === void 0 ? void 0 : _a.button.focus();
590
+ });
474
591
  listen(attachmentDownload, 'click', () => {
475
592
  if (activeAttachment) {
476
- void downloadAttachment(activeAttachment);
593
+ void downloadAttachment(activeAttachment).catch(error => {
594
+ if (!disposed && !signal.aborted)
595
+ showError(error instanceof Error ? error.message : String(error));
596
+ });
477
597
  }
478
598
  });
479
- renderMessageContent();
480
599
  sidebar.append(tabs, attachmentPanel);
481
600
  messagePanel.append(messageContent, attachmentPreview);
482
601
  body.append(sidebar, messagePanel);
483
- root.append(header, body);
602
+ root.append(header, notices, body);
603
+ await renderMessageContent();
484
604
  };
485
605
  showLoading(t('email.loading.parsing'));
486
606
  try {
487
- const parsed = await parseEmail(buffer, normalizedType, filename, objectUrls, cidUrls, t);
488
- renderParsedEmail(parsed);
607
+ signal.throwIfAborted();
608
+ const parsed = await parseEmail(buffer, normalizedType, filename, objectUrls, cidUrls, t, signal);
609
+ signal.throwIfAborted();
610
+ await renderParsedEmail(parsed);
611
+ signal.throwIfAborted();
489
612
  }
490
613
  catch (nextError) {
491
- console.error(nextError);
492
- root.replaceChildren();
493
- showError(nextError instanceof Error ? nextError.message : String(nextError));
614
+ await cleanup();
615
+ throw nextError;
494
616
  }
495
617
  finally {
496
618
  hideLoading();
497
619
  }
498
620
  return {
499
621
  $el: root,
500
- async unmount() {
501
- disposed = true;
502
- attachmentPreviewVersion += 1;
503
- attachmentAbortController === null || attachmentAbortController === void 0 ? void 0 : attachmentAbortController.abort();
504
- attachmentAbortController = undefined;
505
- await clearAttachmentPreview();
506
- cleanups.splice(0).forEach(cleanup => cleanup());
507
- objectUrls.forEach(url => URL.revokeObjectURL(url));
508
- target.replaceChildren();
509
- },
622
+ unmount: cleanup,
510
623
  };
511
624
  }
@@ -0,0 +1,7 @@
1
+ export declare const normalizeEmailResourceId: (value: string) => string;
2
+ /** Sandboxed srcdoc cannot read blob:null URLs from a different opaque
3
+ * origin (file:// WebViews, data: hosts). Keep ordinary hosts zero-copy and use
4
+ * a bounded data URL only for those hosts or browsers without object URLs.
5
+ */
6
+ export declare function createEmailImageResource(buffer: ArrayBuffer, mimeType: string, objectUrls: string[]): string;
7
+ export declare function createEmailHtmlDocument(html: string, resources: Map<string, string>, darkMode?: boolean, documentRef?: Document): string;