@file-viewer/renderer-email 3.1.1 → 3.2.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.
package/README.en.md CHANGED
@@ -1,40 +1,7 @@
1
1
  # @file-viewer/renderer-email
2
2
 
3
- Standalone email renderer package for Flyfish File Viewer. It handles `.eml`, `.msg`, and `.mbox` previews, body/header switching, attachment download, and nested attachment previews.
3
+ Runtime package version 3.2.0.
4
4
 
5
- ## Usage
5
+ Usage and API documentation: https://doc.file-viewer.app/guide/on-demand-renderers
6
6
 
7
- ```ts
8
- import FileViewer from '@file-viewer/vue3'
9
- import { emailRenderer } from '@file-viewer/renderer-email'
10
-
11
- const options = {
12
- builtinRenderers: 'none',
13
- renderers: emailRenderer,
14
- }
15
- ```
16
-
17
- You can also compose it with other renderers:
18
-
19
- ```ts
20
- import { emailRenderer } from '@file-viewer/renderer-email'
21
- import { pdfRenderer } from '@file-viewer/renderer-pdf'
22
- import { archiveRenderer } from '@file-viewer/renderer-archive'
23
-
24
- const options = {
25
- builtinRenderers: 'none',
26
- renderers: [pdfRenderer, archiveRenderer, emailRenderer],
27
- }
28
- ```
29
-
30
- ## Capabilities
31
-
32
- - Parses `.eml` and `.mbox` with `postal-mime`.
33
- - Parses Outlook `.msg` with `@kenjiuno/msgreader`.
34
- - Supports HTML body, plain-text body, and raw header switching. HTML email is rendered read-only inside a sandbox iframe.
35
- - Supports attachment download and nested preview through `renderNestedBuffer` when the host viewer provides it.
36
- - Does not depend on any online service or public CDN, making it suitable for intranet attachment centers, ticket email archives, and customer communication review.
37
-
38
- ## Migration Note
39
-
40
- The core package no longer bundles the email renderer and no longer installs `postal-mime` / `@kenjiuno/msgreader` directly. Install this renderer explicitly, or use `@file-viewer/preset-all`, when email preview is required.
7
+ The package's own license is Apache-2.0. Included third-party notices apply to their respective components.
package/README.md CHANGED
@@ -1,40 +1,7 @@
1
1
  # @file-viewer/renderer-email
2
2
 
3
- Flyfish File Viewer 的独立邮件 renderer 包。它负责 `.eml`、`.msg`、`.mbox` 邮件预览、正文/头信息切换、附件下载和附件嵌套预览。
3
+ Runtime package version 3.2.0.
4
4
 
5
- ## 用法
5
+ Usage and API documentation: https://doc.file-viewer.app/guide/on-demand-renderers
6
6
 
7
- ```ts
8
- import FileViewer from '@file-viewer/vue3'
9
- import { emailRenderer } from '@file-viewer/renderer-email'
10
-
11
- const options = {
12
- builtinRenderers: 'none',
13
- renderers: emailRenderer,
14
- }
15
- ```
16
-
17
- 也可以与其他 renderer 组合:
18
-
19
- ```ts
20
- import { emailRenderer } from '@file-viewer/renderer-email'
21
- import { pdfRenderer } from '@file-viewer/renderer-pdf'
22
- import { archiveRenderer } from '@file-viewer/renderer-archive'
23
-
24
- const options = {
25
- builtinRenderers: 'none',
26
- renderers: [pdfRenderer, archiveRenderer, emailRenderer],
27
- }
28
- ```
29
-
30
- ## 能力边界
31
-
32
- - `.eml` 和 `.mbox` 使用 `postal-mime` 解析邮件头、HTML 正文、纯文本正文和附件。
33
- - `.msg` 使用 `@kenjiuno/msgreader` 解析 Outlook MSG 文件。
34
- - 支持 HTML / 正文 / 头信息切换,HTML 邮件在 sandbox iframe 中只读展示。
35
- - 支持附件下载;宿主 viewer 提供 `renderNestedBuffer` 时,附件会继续复用 PDF、Office、图片、代码等现有 renderer。
36
- - 不绑定任何在线服务或公共 CDN,适合内网附件中心、工单邮件归档和客户来信查看。
37
-
38
- ## 迁移说明
39
-
40
- `@file-viewer/core` 已不再内置 email renderer,也不再直接安装 `postal-mime` / `@kenjiuno/msgreader`。需要邮件预览时,请显式安装本包,或直接使用 `@file-viewer/preset-all` 聚合能力。
7
+ The package's own license is Apache-2.0. Included third-party notices apply to their respective components.
package/dist/email.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { FileRenderContext, FileViewerRenderedInstance } from '@file-viewer/core';
2
+ import { type MsgNotice } from './msgMessages.js';
2
3
  type EmailKind = 'eml' | 'msg' | 'mbox';
3
4
  interface EmailAddress {
4
5
  name?: string;
@@ -10,14 +11,20 @@ interface EmailAttachmentView {
10
11
  mimeType?: string;
11
12
  size: number;
12
13
  contentId?: string;
14
+ contentLocation?: string;
15
+ inline?: boolean;
13
16
  load(): Promise<ArrayBuffer>;
14
17
  }
15
18
  export interface ParsedEmailView {
16
19
  kind: EmailKind;
17
20
  subject: string;
18
21
  from: EmailAddress[];
22
+ sender?: EmailAddress[];
19
23
  to: EmailAddress[];
20
24
  cc: EmailAddress[];
25
+ bcc?: EmailAddress[];
26
+ rtf?: ArrayBuffer;
27
+ warnings?: MsgNotice[];
21
28
  date?: string;
22
29
  text?: string;
23
30
  html?: string;
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,20 +127,18 @@ 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
  };
126
- // Exported for the package-local #232 regression gate (verify-github-232.mjs); it
127
- // stays out of the public exports map, so the shipped API surface is unchanged.
128
134
  export const parseEml = async (buffer, filename, objectUrls, cidUrls) => {
129
135
  var _a, _b;
130
- const PostalMime = (await import('postal-mime')).default;
136
+ const { default: PostalMime } = await import('postal-mime');
131
137
  const email = await PostalMime.parse(buffer, {
132
138
  attachmentEncoding: 'arraybuffer',
133
139
  maxNestingDepth: 24,
134
140
  maxHeadersSize: 2 * 1024 * 1024,
141
+ maxPartCount: 10000,
135
142
  });
136
143
  const attachments = await createPostalAttachments(email, objectUrls, cidUrls);
137
144
  return {
@@ -156,11 +163,12 @@ const parseMbox = async (buffer, filename, objectUrls, cidUrls, t) => {
156
163
  const secondStart = (_b = starts[1]) !== null && _b !== void 0 ? _b : source.length;
157
164
  const firstMessage = source.slice(firstStart, secondStart).replace(/^From .*$\n/, '');
158
165
  const encoded = new TextEncoder().encode(firstMessage).buffer;
159
- const PostalMime = (await import('postal-mime')).default;
166
+ const { default: PostalMime } = await import('postal-mime');
160
167
  const email = await PostalMime.parse(encoded, {
161
168
  attachmentEncoding: 'arraybuffer',
162
169
  maxNestingDepth: 24,
163
170
  maxHeadersSize: 2 * 1024 * 1024,
171
+ maxPartCount: 10000,
164
172
  });
165
173
  const attachments = await createPostalAttachments(email, objectUrls, cidUrls);
166
174
  return {
@@ -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,102 @@ 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
+ const rendered = await context.renderNestedBuffer(parsed.rtf, 'rtf', child, {
416
+ ...context,
417
+ filename: `${filename}.rtf`,
418
+ signal: current.signal,
419
+ options: {
420
+ ...context.options,
421
+ docx: { ...(_a = context.options) === null || _a === void 0 ? void 0 : _a.docx, externalResourcePolicy: 'block', externalLinkPolicy: 'block' },
422
+ },
423
+ });
424
+ if (stale()) {
425
+ await disposeFileViewerRendered(rendered);
426
+ return;
427
+ }
428
+ bodyRendered = rendered;
429
+ }
430
+ else {
431
+ renderPlainBody(activeBody === 'headers' ? 'headers' : 'text');
432
+ }
433
+ }
434
+ catch (error) {
435
+ if (stale())
436
+ return;
437
+ if (activeBody === 'rtf') {
438
+ noticeKeys.add('email.msg.rtfUnavailable');
439
+ renderNotices();
440
+ renderPlainBody(parsed.text ? 'text' : 'headers');
441
+ }
442
+ else {
443
+ throw error;
444
+ }
445
+ }
446
+ finally {
447
+ signal.removeEventListener('abort', abort);
448
+ }
363
449
  };
364
450
  const syncTabState = () => {
365
451
  tabButtons.forEach(({ mode, button }) => {
366
452
  button.classList.toggle('active', mode === activeBody);
453
+ button.setAttribute('aria-pressed', String(mode === activeBody));
367
454
  });
368
455
  };
369
456
  const bodyModes = [
370
457
  { key: 'html', label: 'HTML', disabled: !parsed.html },
458
+ ...(parsed.rtf ? [{ key: 'rtf', label: 'RTF', disabled: !(context === null || context === void 0 ? void 0 : context.renderNestedBuffer) }] : []),
371
459
  { key: 'text', label: t('email.tabs.text'), disabled: !parsed.text },
372
460
  { key: 'headers', label: t('email.tabs.headers'), disabled: !parsed.headers },
373
461
  ];
@@ -381,7 +469,10 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
381
469
  }
382
470
  activeBody = mode.key;
383
471
  syncTabState();
384
- renderMessageContent();
472
+ void renderMessageContent().catch(error => {
473
+ if (!disposed && !signal.aborted)
474
+ showError(error instanceof Error ? error.message : String(error));
475
+ });
385
476
  });
386
477
  tabButtons.push({ mode: mode.key, button });
387
478
  tabs.append(button);
@@ -400,27 +491,36 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
400
491
  });
401
492
  };
402
493
  const previewAttachment = async (attachment) => {
403
- var _a, _b, _c;
494
+ var _a;
404
495
  const previewVersion = ++attachmentPreviewVersion;
405
496
  attachmentAbortController === null || attachmentAbortController === void 0 ? void 0 : attachmentAbortController.abort();
406
497
  const previewAbortController = new AbortController();
407
498
  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
- }
499
+ const abort = () => previewAbortController.abort(signal.reason);
500
+ if (signal.aborted)
501
+ abort();
502
+ else
503
+ signal.addEventListener('abort', abort, { once: true });
504
+ const stale = () => disposed || previewVersion !== attachmentPreviewVersion || previewAbortController.signal.aborted;
415
505
  activeAttachment = attachment;
416
506
  syncAttachmentState();
417
507
  attachmentPreview.hidden = false;
508
+ messagePanel.classList.add('has-attachment-preview');
509
+ errorElement === null || errorElement === void 0 ? void 0 : errorElement.remove();
510
+ errorElement = null;
418
511
  attachmentPreviewTitle.textContent = attachment.name;
419
512
  showLoading(t('email.attachments.opening', { name: attachment.name }));
420
513
  try {
421
514
  await clearAttachmentPreview();
515
+ if (stale())
516
+ return;
422
517
  attachmentTarget.replaceChildren();
423
518
  const attachmentBuffer = await attachment.load();
519
+ if (stale())
520
+ return;
521
+ const sizeLabel = (_a = attachmentButtons.find(item => item.id === attachment.id)) === null || _a === void 0 ? void 0 : _a.button.querySelector('em');
522
+ if (sizeLabel)
523
+ sizeLabel.textContent = formatBytes(attachmentBuffer.byteLength);
424
524
  const child = createElement('div', 'email-attachment-render');
425
525
  attachmentTarget.append(child);
426
526
  const extension = getAttachmentExtension(attachment.name);
@@ -431,7 +531,7 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
431
531
  options: context.options,
432
532
  signal: previewAbortController.signal,
433
533
  });
434
- if (disposed || previewVersion !== attachmentPreviewVersion || previewAbortController.signal.aborted) {
534
+ if (stale()) {
435
535
  await disposeFileViewerRendered(nextRendered);
436
536
  return;
437
537
  }
@@ -442,14 +542,14 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
442
542
  }
443
543
  }
444
544
  catch (nextError) {
445
- if (disposed || previewVersion !== attachmentPreviewVersion || previewAbortController.signal.aborted) {
545
+ if (stale()) {
446
546
  return;
447
547
  }
448
548
  console.error(nextError);
449
549
  showError(nextError instanceof Error ? nextError.message : String(nextError));
450
550
  }
451
551
  finally {
452
- (_c = context === null || context === void 0 ? void 0 : context.signal) === null || _c === void 0 ? void 0 : _c.removeEventListener('abort', abortFromParent);
552
+ signal.removeEventListener('abort', abort);
453
553
  if (attachmentAbortController === previewAbortController) {
454
554
  attachmentAbortController = undefined;
455
555
  }
@@ -471,41 +571,52 @@ export default async function renderEmail(buffer, target, type = 'eml', context)
471
571
  attachmentButtons.push({ id: attachment.id, button });
472
572
  attachmentPanel.append(button);
473
573
  });
574
+ listen(attachmentClose, 'click', () => {
575
+ var _a;
576
+ attachmentPreviewVersion += 1;
577
+ attachmentAbortController === null || attachmentAbortController === void 0 ? void 0 : attachmentAbortController.abort();
578
+ attachmentAbortController = undefined;
579
+ const previous = activeAttachment;
580
+ activeAttachment = null;
581
+ syncAttachmentState();
582
+ attachmentPreview.hidden = true;
583
+ messagePanel.classList.remove('has-attachment-preview');
584
+ hideLoading();
585
+ void clearAttachmentPreview().catch(() => { });
586
+ attachmentTarget.replaceChildren();
587
+ (_a = attachmentButtons.find(item => item.id === (previous === null || previous === void 0 ? void 0 : previous.id))) === null || _a === void 0 ? void 0 : _a.button.focus();
588
+ });
474
589
  listen(attachmentDownload, 'click', () => {
475
590
  if (activeAttachment) {
476
- void downloadAttachment(activeAttachment);
591
+ void downloadAttachment(activeAttachment).catch(error => {
592
+ if (!disposed && !signal.aborted)
593
+ showError(error instanceof Error ? error.message : String(error));
594
+ });
477
595
  }
478
596
  });
479
- renderMessageContent();
480
597
  sidebar.append(tabs, attachmentPanel);
481
598
  messagePanel.append(messageContent, attachmentPreview);
482
599
  body.append(sidebar, messagePanel);
483
- root.append(header, body);
600
+ root.append(header, notices, body);
601
+ await renderMessageContent();
484
602
  };
485
603
  showLoading(t('email.loading.parsing'));
486
604
  try {
487
- const parsed = await parseEmail(buffer, normalizedType, filename, objectUrls, cidUrls, t);
488
- renderParsedEmail(parsed);
605
+ signal.throwIfAborted();
606
+ const parsed = await parseEmail(buffer, normalizedType, filename, objectUrls, cidUrls, t, signal);
607
+ signal.throwIfAborted();
608
+ await renderParsedEmail(parsed);
609
+ signal.throwIfAborted();
489
610
  }
490
611
  catch (nextError) {
491
- console.error(nextError);
492
- root.replaceChildren();
493
- showError(nextError instanceof Error ? nextError.message : String(nextError));
612
+ await cleanup();
613
+ throw nextError;
494
614
  }
495
615
  finally {
496
616
  hideLoading();
497
617
  }
498
618
  return {
499
619
  $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
- },
620
+ unmount: cleanup,
510
621
  };
511
622
  }
@@ -0,0 +1,3 @@
1
+ export declare const normalizeEmailResourceId: (value: string) => string;
2
+ export declare function createEmailImageResource(buffer: ArrayBuffer, mimeType: string, objectUrls: string[]): string;
3
+ export declare function createEmailHtmlDocument(html: string, resources: Map<string, string>, darkMode?: boolean, documentRef?: Document): string;