@postalsys/ee-client 1.3.3 → 1.5.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.md +16 -10
- package/index.d.ts +51 -6
- package/index.js +201 -134
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -115,21 +115,23 @@ EmailEngine can also mint short-lived, session-bound tokens whose value starts w
|
|
|
115
115
|
new EmailEngineClient(options);
|
|
116
116
|
```
|
|
117
117
|
|
|
118
|
-
| Option
|
|
119
|
-
|
|
|
120
|
-
| `account`
|
|
121
|
-
| `apiUrl`
|
|
122
|
-
| `accessToken`
|
|
123
|
-
| `container`
|
|
124
|
-
| `pageSize`
|
|
125
|
-
| `confirmMethod`
|
|
126
|
-
| `alertMethod`
|
|
118
|
+
| Option | Type | Default | Description |
|
|
119
|
+
| -------------------- | ------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
120
|
+
| `account` | `string` | (required) | EmailEngine account identifier. |
|
|
121
|
+
| `apiUrl` | `string` | `http://127.0.0.1:3000` | Base URL of your EmailEngine instance. |
|
|
122
|
+
| `accessToken` | `string` | - | Bearer token for API authentication. |
|
|
123
|
+
| `container` | `HTMLElement` | - | DOM element to render the webmail UI into. Omit for API-only use. |
|
|
124
|
+
| `pageSize` | `number` | `20` | Messages per page. A saved value in `localStorage` takes precedence. |
|
|
125
|
+
| `confirmMethod` | `function` | browser `confirm()` | Custom confirm dialog, `(message, title, cancelText, okText)`. May be sync or async; returns a boolean. |
|
|
126
|
+
| `alertMethod` | `function` | browser `alert()` | Custom alert dialog, `(message, title, cancelText, okText)` where `cancelText` is `null`. |
|
|
127
|
+
| `darkMode` | `boolean` | stored preference | Initial dark mode. Overrides the preference stored by the builtin toggle. |
|
|
128
|
+
| `showDarkModeToggle` | `boolean` | `true` | Render the builtin dark mode toggle. Set `false` when the host application drives the mode through `client.setDarkMode(enabled)` (for example in sync with its own theme switch). |
|
|
127
129
|
|
|
128
130
|
UI rendering, the compose modal, and dark mode only activate when a `container` is supplied. In a non-browser environment the UI is skipped and the instance behaves as a plain API client.
|
|
129
131
|
|
|
130
132
|
### Factory helper
|
|
131
133
|
|
|
132
|
-
`createEmailEngineClient()` is a convenience wrapper that
|
|
134
|
+
`createEmailEngineClient()` is a convenience wrapper that resolves a `containerId` to its DOM element and validates that `account` is present:
|
|
133
135
|
|
|
134
136
|
```javascript
|
|
135
137
|
import { createEmailEngineClient } from '@postalsys/ee-client';
|
|
@@ -187,6 +189,10 @@ Browser only. Fetch an attachment and trigger a download, using the filename fro
|
|
|
187
189
|
|
|
188
190
|
Browser only. Download the raw message source as an `.eml` file.
|
|
189
191
|
|
|
192
|
+
### `setDarkMode(enabled: boolean): void`
|
|
193
|
+
|
|
194
|
+
Set dark mode from the host application without touching the preference stored by the builtin toggle. Combine with `showDarkModeToggle: false` to keep the rendered UI in sync with the host page's own theme switch.
|
|
195
|
+
|
|
190
196
|
### `destroy(): void`
|
|
191
197
|
|
|
192
198
|
Clean up the instance and clear the `sess_` token keep-alive interval. Always call this when you are finished with a client (for example when unmounting the UI) to avoid a leaked timer.
|
package/index.d.ts
CHANGED
|
@@ -26,6 +26,18 @@ export interface Folder {
|
|
|
26
26
|
status?: MessageStatus;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
export interface FolderTreeEntry {
|
|
30
|
+
folder: Folder;
|
|
31
|
+
depth: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface Attachment {
|
|
35
|
+
id: string;
|
|
36
|
+
filename?: string;
|
|
37
|
+
contentType?: string;
|
|
38
|
+
size?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
29
41
|
export interface Message {
|
|
30
42
|
id: string;
|
|
31
43
|
subject?: string;
|
|
@@ -36,6 +48,7 @@ export interface Message {
|
|
|
36
48
|
unseen: boolean;
|
|
37
49
|
intro?: string;
|
|
38
50
|
text?: MessageText;
|
|
51
|
+
attachments?: Attachment[];
|
|
39
52
|
}
|
|
40
53
|
|
|
41
54
|
export interface MessageListResponse {
|
|
@@ -44,20 +57,45 @@ export interface MessageListResponse {
|
|
|
44
57
|
prevPageCursor?: string;
|
|
45
58
|
}
|
|
46
59
|
|
|
60
|
+
export type SendRecipient = string | EmailAddress;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Custom dialog handler. Invoked by the client as
|
|
64
|
+
* `(message, title, cancelText, okText)`; `cancelText` is `null` for alerts.
|
|
65
|
+
* May be synchronous or asynchronous. Confirm handlers should resolve to a boolean.
|
|
66
|
+
*/
|
|
67
|
+
export type DialogMethod = (
|
|
68
|
+
message: string,
|
|
69
|
+
title?: string,
|
|
70
|
+
cancelText?: string | null,
|
|
71
|
+
okText?: string
|
|
72
|
+
) => boolean | void | Promise<boolean | void>;
|
|
73
|
+
|
|
47
74
|
export interface EmailEngineClientOptions {
|
|
48
75
|
apiUrl?: string;
|
|
49
76
|
account: string;
|
|
50
77
|
accessToken?: string;
|
|
51
78
|
container?: HTMLElement;
|
|
52
79
|
containerId?: string;
|
|
53
|
-
|
|
80
|
+
pageSize?: number;
|
|
81
|
+
confirmMethod?: DialogMethod;
|
|
82
|
+
alertMethod?: DialogMethod;
|
|
83
|
+
/** Initial dark mode; overrides the preference stored by the builtin toggle */
|
|
84
|
+
darkMode?: boolean;
|
|
85
|
+
/** Render the builtin dark mode toggle button (default true); set false when the host drives the mode through setDarkMode() */
|
|
86
|
+
showDarkModeToggle?: boolean;
|
|
54
87
|
}
|
|
55
88
|
|
|
56
89
|
export declare class EmailEngineClient {
|
|
57
90
|
apiUrl: string;
|
|
58
91
|
account: string;
|
|
59
92
|
accessToken?: string;
|
|
60
|
-
container?: HTMLElement;
|
|
93
|
+
container?: HTMLElement | null;
|
|
94
|
+
confirmMethod: DialogMethod;
|
|
95
|
+
alertMethod: DialogMethod;
|
|
96
|
+
pageSize: number;
|
|
97
|
+
darkMode: boolean;
|
|
98
|
+
showDarkModeToggle: boolean;
|
|
61
99
|
currentFolder: string | null;
|
|
62
100
|
currentMessage: Message | null;
|
|
63
101
|
folders: Folder[];
|
|
@@ -74,17 +112,24 @@ export declare class EmailEngineClient {
|
|
|
74
112
|
markAsRead(messageId: string, seen?: boolean): Promise<boolean>;
|
|
75
113
|
deleteMessage(messageId: string): Promise<boolean>;
|
|
76
114
|
moveMessage(messageId: string, targetPath: string): Promise<boolean>;
|
|
115
|
+
sendMessage(to: SendRecipient | SendRecipient[], subject: string, text: string): Promise<any>;
|
|
116
|
+
downloadAttachment(attachmentId: string, suggestedFilename?: string): Promise<void>;
|
|
117
|
+
downloadOriginalMessage(messageId: string, subject?: string): Promise<void>;
|
|
77
118
|
formatDate(dateStr: string): string;
|
|
119
|
+
formatFileSize(bytes: number): string;
|
|
120
|
+
escapeHtml(value: unknown): string;
|
|
78
121
|
createStyles(): void;
|
|
79
|
-
|
|
80
|
-
buildFolderTree(): Folder[];
|
|
122
|
+
buildFolderTree(): FolderTreeEntry[];
|
|
81
123
|
renderFolderList(): void;
|
|
82
124
|
renderMessageList(): void;
|
|
83
125
|
renderMessage(): void;
|
|
84
126
|
createLayout(): void;
|
|
85
127
|
init(): void;
|
|
128
|
+
setDarkMode(enabled: boolean): void;
|
|
129
|
+
toggleDarkMode(): void;
|
|
130
|
+
destroy(): void;
|
|
86
131
|
}
|
|
87
132
|
|
|
88
|
-
export declare function createEmailEngineClient(options: EmailEngineClientOptions
|
|
133
|
+
export declare function createEmailEngineClient(options: EmailEngineClientOptions): EmailEngineClient;
|
|
89
134
|
|
|
90
|
-
export default EmailEngineClient;
|
|
135
|
+
export default EmailEngineClient;
|
package/index.js
CHANGED
|
@@ -3,7 +3,20 @@ export class EmailEngineClient {
|
|
|
3
3
|
this.apiUrl = options.apiUrl || 'http://127.0.0.1:3000';
|
|
4
4
|
this.account = options.account;
|
|
5
5
|
this.accessToken = options.accessToken;
|
|
6
|
-
this.container = options.container;
|
|
6
|
+
this.container = options.container || null;
|
|
7
|
+
// Resolve containerId when no element was passed directly, so
|
|
8
|
+
// `new EmailEngineClient({ containerId })` renders UI too (not only the
|
|
9
|
+
// factory). In a non-DOM env this stays null - an API-only client.
|
|
10
|
+
if (!this.container && options.containerId && typeof document !== 'undefined') {
|
|
11
|
+
this.container = document.getElementById(options.containerId);
|
|
12
|
+
// A containerId that matches nothing is almost always a typo; warn
|
|
13
|
+
// rather than silently degrading to a UI-less, API-only client.
|
|
14
|
+
if (!this.container) {
|
|
15
|
+
console.warn(
|
|
16
|
+
`EmailEngineClient: no element found for containerId "${options.containerId}"; UI rendering disabled`
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
7
20
|
this.confirmMethod =
|
|
8
21
|
options.confirmMethod ||
|
|
9
22
|
((message, _title = 'Confirm', _cancelText = 'Cancel', _okText = 'OK') => confirm(message));
|
|
@@ -17,20 +30,33 @@ export class EmailEngineClient {
|
|
|
17
30
|
this.nextPageCursor = null;
|
|
18
31
|
this.prevPageCursor = null;
|
|
19
32
|
|
|
33
|
+
// Set once destroy() runs; guards async completions (loadFolders,
|
|
34
|
+
// loadMessages, loadMessage) from re-rendering or scrolling into a
|
|
35
|
+
// torn-down - or recreated - container.
|
|
36
|
+
this._destroyed = false;
|
|
37
|
+
|
|
20
38
|
// Keep-alive timer for sess_ tokens
|
|
21
39
|
this.keepAliveTimer = null;
|
|
22
40
|
this.lastActivity = Date.now();
|
|
23
41
|
|
|
24
|
-
// Dark mode state
|
|
42
|
+
// Dark mode state. An explicit darkMode option overrides the stored
|
|
43
|
+
// preference - for hosts that manage the theme themselves (usually
|
|
44
|
+
// together with showDarkModeToggle: false to hide the builtin button
|
|
45
|
+
// and drive the mode through setDarkMode()).
|
|
25
46
|
this.darkMode = false;
|
|
26
47
|
if (typeof window !== 'undefined' && window.localStorage) {
|
|
27
48
|
this.darkMode = localStorage.getItem('ee-client-dark-mode') === 'true';
|
|
28
49
|
}
|
|
50
|
+
if (typeof options.darkMode === 'boolean') {
|
|
51
|
+
this.darkMode = options.darkMode;
|
|
52
|
+
}
|
|
53
|
+
this.showDarkModeToggle = options.showDarkModeToggle !== false;
|
|
29
54
|
|
|
30
55
|
// Get page size from localStorage or options or default
|
|
31
56
|
const savedPageSize =
|
|
32
57
|
typeof window !== 'undefined' && window.localStorage ? localStorage.getItem('ee-client-page-size') : null;
|
|
33
|
-
|
|
58
|
+
const requestedPageSize = savedPageSize ? parseInt(savedPageSize, 10) : parseInt(options.pageSize, 10);
|
|
59
|
+
this.pageSize = requestedPageSize > 0 ? requestedPageSize : 20;
|
|
34
60
|
|
|
35
61
|
if (this.container) {
|
|
36
62
|
this.init();
|
|
@@ -48,32 +74,32 @@ export class EmailEngineClient {
|
|
|
48
74
|
const options = {
|
|
49
75
|
method: method,
|
|
50
76
|
headers: {
|
|
51
|
-
'Content-Type': 'application/json'
|
|
77
|
+
'Content-Type': 'application/json',
|
|
78
|
+
...this._authHeaders()
|
|
52
79
|
}
|
|
53
80
|
};
|
|
54
81
|
|
|
55
|
-
if (this.accessToken) {
|
|
56
|
-
options.headers['Authorization'] = `Bearer ${this.accessToken}`;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
82
|
if (data) {
|
|
60
83
|
options.body = JSON.stringify(data);
|
|
61
84
|
}
|
|
62
85
|
|
|
63
86
|
let fetchFn = globalThis.fetch;
|
|
64
|
-
if (!fetchFn
|
|
87
|
+
if (!fetchFn) {
|
|
88
|
+
// Native fetch is missing (older Node.js). Fall back to node-fetch.
|
|
89
|
+
// This is a dynamic import so browsers and modern Node never load it.
|
|
65
90
|
try {
|
|
66
91
|
const nodeFetch = await import('node-fetch');
|
|
67
92
|
fetchFn = nodeFetch.default;
|
|
68
93
|
} catch (err) {
|
|
69
|
-
|
|
70
|
-
'fetch is not available. In Node.js environments, please install node-fetch: npm install node-fetch'
|
|
71
|
-
);
|
|
94
|
+
// node-fetch is not installed; the guard below reports it
|
|
72
95
|
}
|
|
73
96
|
}
|
|
74
97
|
|
|
75
98
|
if (!fetchFn) {
|
|
76
|
-
|
|
99
|
+
// Either node-fetch is missing or it exposed no callable default export
|
|
100
|
+
throw new Error(
|
|
101
|
+
'fetch is not available. In Node.js environments, please install node-fetch: npm install node-fetch'
|
|
102
|
+
);
|
|
77
103
|
}
|
|
78
104
|
|
|
79
105
|
const response = await fetchFn(url, options);
|
|
@@ -99,6 +125,7 @@ export class EmailEngineClient {
|
|
|
99
125
|
try {
|
|
100
126
|
const data = await this.apiRequest('GET', `/v1/account/${this.account}/mailboxes`);
|
|
101
127
|
this.folders = data.mailboxes || [];
|
|
128
|
+
this._folderTreeCache = null;
|
|
102
129
|
if (this.container) {
|
|
103
130
|
this.renderFolderList();
|
|
104
131
|
}
|
|
@@ -181,7 +208,7 @@ export class EmailEngineClient {
|
|
|
181
208
|
}
|
|
182
209
|
}
|
|
183
210
|
|
|
184
|
-
if (this.container) {
|
|
211
|
+
if (this.container && !this._destroyed) {
|
|
185
212
|
this.renderMessage();
|
|
186
213
|
|
|
187
214
|
// Scroll to top of the email client container
|
|
@@ -321,23 +348,18 @@ export class EmailEngineClient {
|
|
|
321
348
|
_formatSendError(error) {
|
|
322
349
|
// If we have detailed error information from the API
|
|
323
350
|
if (error.details && error.details.fields && Array.isArray(error.details.fields)) {
|
|
324
|
-
const fieldErrors = error.details.fields
|
|
325
|
-
//
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
//
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
message = message.replace('"text"', 'message');
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
return message;
|
|
340
|
-
});
|
|
351
|
+
const fieldErrors = error.details.fields
|
|
352
|
+
// Keep only entries that carry a usable message string.
|
|
353
|
+
.filter(field => field && typeof field.message === 'string')
|
|
354
|
+
// Map technical field names to user-friendly ones. Each replace
|
|
355
|
+
// is a no-op when its pattern is absent, so no includes-guards
|
|
356
|
+
// are needed - and to[N] for any index is handled, not just to[0].
|
|
357
|
+
.map(field =>
|
|
358
|
+
field.message
|
|
359
|
+
.replace(/to\[\d+\]\.address|"address"/g, 'email address')
|
|
360
|
+
.replace(/"subject"/g, 'subject')
|
|
361
|
+
.replace(/"text"/g, 'message')
|
|
362
|
+
);
|
|
341
363
|
|
|
342
364
|
const mainMessage = error.details.message || 'Failed to send email';
|
|
343
365
|
if (fieldErrors.length > 0) {
|
|
@@ -381,21 +403,43 @@ export class EmailEngineClient {
|
|
|
381
403
|
return String(value).replace(/[&<>"']/g, ch => htmlEscapes[ch]);
|
|
382
404
|
}
|
|
383
405
|
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
406
|
+
_authHeaders() {
|
|
407
|
+
const headers = {};
|
|
408
|
+
if (this.accessToken) {
|
|
409
|
+
headers['Authorization'] = `Bearer ${this.accessToken}`;
|
|
410
|
+
}
|
|
411
|
+
return headers;
|
|
412
|
+
}
|
|
390
413
|
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
414
|
+
_saveBlob(blob, filename) {
|
|
415
|
+
const url = window.URL.createObjectURL(blob);
|
|
416
|
+
const a = document.createElement('a');
|
|
417
|
+
a.href = url;
|
|
418
|
+
a.download = filename;
|
|
419
|
+
document.body.appendChild(a);
|
|
420
|
+
a.click();
|
|
421
|
+
document.body.removeChild(a);
|
|
422
|
+
window.URL.revokeObjectURL(url);
|
|
423
|
+
}
|
|
395
424
|
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
425
|
+
// Authenticated GET for binary payloads (attachments, message source).
|
|
426
|
+
// apiRequest is not reused here - it always parses the body as JSON.
|
|
427
|
+
async _fetchBlob(endpoint) {
|
|
428
|
+
const response = await fetch(`${this.apiUrl}${endpoint}`, {
|
|
429
|
+
headers: this._authHeaders(),
|
|
430
|
+
credentials: 'include'
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
if (!response.ok) {
|
|
434
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
return response;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
async downloadAttachment(attachmentId, suggestedFilename = null) {
|
|
441
|
+
try {
|
|
442
|
+
const response = await this._fetchBlob(`/v1/account/${this.account}/attachment/${attachmentId}`);
|
|
399
443
|
|
|
400
444
|
// Get filename from Content-Disposition header if available
|
|
401
445
|
const contentDisposition = response.headers.get('content-disposition');
|
|
@@ -407,18 +451,9 @@ export class EmailEngineClient {
|
|
|
407
451
|
}
|
|
408
452
|
}
|
|
409
453
|
|
|
410
|
-
// Get the attachment data
|
|
454
|
+
// Get the attachment data and trigger the download
|
|
411
455
|
const blob = await response.blob();
|
|
412
|
-
|
|
413
|
-
// Create a download link
|
|
414
|
-
const url = window.URL.createObjectURL(blob);
|
|
415
|
-
const a = document.createElement('a');
|
|
416
|
-
a.href = url;
|
|
417
|
-
a.download = filename;
|
|
418
|
-
document.body.appendChild(a);
|
|
419
|
-
a.click();
|
|
420
|
-
document.body.removeChild(a);
|
|
421
|
-
window.URL.revokeObjectURL(url);
|
|
456
|
+
this._saveBlob(blob, filename);
|
|
422
457
|
} catch (error) {
|
|
423
458
|
console.error('Failed to download attachment:', error);
|
|
424
459
|
this.alertMethod('Failed to download attachment. Please try again.', 'Download Error', null, 'OK');
|
|
@@ -427,19 +462,7 @@ export class EmailEngineClient {
|
|
|
427
462
|
|
|
428
463
|
async downloadOriginalMessage(messageId, subject = null) {
|
|
429
464
|
try {
|
|
430
|
-
const
|
|
431
|
-
if (this.accessToken) {
|
|
432
|
-
headers['Authorization'] = `Bearer ${this.accessToken}`;
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
const response = await fetch(`${this.apiUrl}/v1/account/${this.account}/message/${messageId}/source`, {
|
|
436
|
-
headers,
|
|
437
|
-
credentials: 'include'
|
|
438
|
-
});
|
|
439
|
-
|
|
440
|
-
if (!response.ok) {
|
|
441
|
-
throw new Error(`HTTP error! status: ${response.status}`);
|
|
442
|
-
}
|
|
465
|
+
const response = await this._fetchBlob(`/v1/account/${this.account}/message/${messageId}/source`);
|
|
443
466
|
|
|
444
467
|
// Get the email data
|
|
445
468
|
const blob = await response.blob();
|
|
@@ -450,15 +473,7 @@ export class EmailEngineClient {
|
|
|
450
473
|
const safeSubject = subject ? subject.replace(/[^a-z0-9]/gi, '_').substring(0, 50) : 'email';
|
|
451
474
|
const filename = `${dateStr}_${safeSubject}.eml`;
|
|
452
475
|
|
|
453
|
-
|
|
454
|
-
const url = window.URL.createObjectURL(blob);
|
|
455
|
-
const a = document.createElement('a');
|
|
456
|
-
a.href = url;
|
|
457
|
-
a.download = filename;
|
|
458
|
-
document.body.appendChild(a);
|
|
459
|
-
a.click();
|
|
460
|
-
document.body.removeChild(a);
|
|
461
|
-
window.URL.revokeObjectURL(url);
|
|
476
|
+
this._saveBlob(blob, filename);
|
|
462
477
|
} catch (error) {
|
|
463
478
|
console.error('Failed to download original message:', error);
|
|
464
479
|
this.alertMethod('Failed to download original message. Please try again.', 'Download Error', null, 'OK');
|
|
@@ -1273,18 +1288,14 @@ export class EmailEngineClient {
|
|
|
1273
1288
|
}
|
|
1274
1289
|
`;
|
|
1275
1290
|
document.head.appendChild(style);
|
|
1291
|
+
this._styleElement = style;
|
|
1276
1292
|
}
|
|
1277
1293
|
|
|
1278
|
-
|
|
1279
|
-
if (
|
|
1280
|
-
return
|
|
1294
|
+
buildFolderTree() {
|
|
1295
|
+
if (this._folderTreeCache) {
|
|
1296
|
+
return this._folderTreeCache;
|
|
1281
1297
|
}
|
|
1282
1298
|
|
|
1283
|
-
const pathParts = folder.path.split(folder.delimiter);
|
|
1284
|
-
return Math.max(0, pathParts.length - 1);
|
|
1285
|
-
}
|
|
1286
|
-
|
|
1287
|
-
buildFolderTree() {
|
|
1288
1299
|
const specialFolders = [];
|
|
1289
1300
|
const regularFolders = [];
|
|
1290
1301
|
|
|
@@ -1319,34 +1330,52 @@ export class EmailEngineClient {
|
|
|
1319
1330
|
return a.name.localeCompare(b.name);
|
|
1320
1331
|
});
|
|
1321
1332
|
|
|
1322
|
-
|
|
1323
|
-
|
|
1333
|
+
// Index children by parent in a single pass so the hierarchy walk is
|
|
1334
|
+
// O(n) instead of re-filtering the whole list at every level. A folder
|
|
1335
|
+
// whose parent is not among the regular folders (special-use parent,
|
|
1336
|
+
// missing parent, or no parent) is a root, keyed under null - those must
|
|
1337
|
+
// still surface at the top level rather than be dropped.
|
|
1338
|
+
const regularPaths = new Set(regularFolders.map(f => f.path));
|
|
1339
|
+
const childrenByParent = new Map();
|
|
1340
|
+
regularFolders.forEach(folder => {
|
|
1341
|
+
const key = regularPaths.has(folder.parentPath) ? folder.parentPath : null;
|
|
1342
|
+
const siblings = childrenByParent.get(key);
|
|
1343
|
+
if (siblings) {
|
|
1344
|
+
siblings.push(folder);
|
|
1345
|
+
} else {
|
|
1346
|
+
childrenByParent.set(key, [folder]);
|
|
1347
|
+
}
|
|
1348
|
+
});
|
|
1349
|
+
childrenByParent.forEach(siblings => siblings.sort((a, b) => a.name.localeCompare(b.name)));
|
|
1324
1350
|
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1351
|
+
// Each entry carries its depth in the rendered tree (roots = 0). Depth
|
|
1352
|
+
// comes from tree position, not the path string, so a folder whose
|
|
1353
|
+
// parent is a special-use or missing folder renders flush at the top.
|
|
1354
|
+
const visited = new Set();
|
|
1355
|
+
const walk = (parentKey, depth) => {
|
|
1356
|
+
const result = [];
|
|
1357
|
+
const siblings = childrenByParent.get(parentKey) || [];
|
|
1358
|
+
siblings.forEach(folder => {
|
|
1359
|
+
// Guard against cyclic/self-referential parentPath values.
|
|
1360
|
+
if (visited.has(folder.path)) {
|
|
1361
|
+
return;
|
|
1330
1362
|
}
|
|
1363
|
+
visited.add(folder.path);
|
|
1364
|
+
result.push({ folder, depth });
|
|
1365
|
+
result.push(...walk(folder.path, depth + 1));
|
|
1331
1366
|
});
|
|
1332
|
-
|
|
1333
|
-
children.sort((a, b) => a.name.localeCompare(b.name));
|
|
1334
|
-
|
|
1335
|
-
children.forEach(folder => {
|
|
1336
|
-
result.push(folder);
|
|
1337
|
-
result.push(...buildHierarchy(folders, folder.path, depth + 1));
|
|
1338
|
-
});
|
|
1339
|
-
|
|
1340
1367
|
return result;
|
|
1341
1368
|
};
|
|
1342
1369
|
|
|
1343
|
-
const hierarchicalRegular =
|
|
1370
|
+
const hierarchicalRegular = walk(null, 0);
|
|
1344
1371
|
|
|
1345
|
-
|
|
1372
|
+
const tree = [...specialFolders.map(folder => ({ folder, depth: 0 })), ...hierarchicalRegular];
|
|
1373
|
+
this._folderTreeCache = tree;
|
|
1374
|
+
return tree;
|
|
1346
1375
|
}
|
|
1347
1376
|
|
|
1348
1377
|
renderFolderList() {
|
|
1349
|
-
if (typeof document === 'undefined' || !this.container) {
|
|
1378
|
+
if (typeof document === 'undefined' || !this.container || this._destroyed) {
|
|
1350
1379
|
return;
|
|
1351
1380
|
}
|
|
1352
1381
|
|
|
@@ -1356,13 +1385,15 @@ export class EmailEngineClient {
|
|
|
1356
1385
|
}
|
|
1357
1386
|
|
|
1358
1387
|
const sortedFolders = this.buildFolderTree();
|
|
1388
|
+
// Precompute which paths are some folder's parent so the per-row
|
|
1389
|
+
// has-children check is O(1) instead of scanning this.folders each time.
|
|
1390
|
+
const parentPaths = new Set(this.folders.map(f => f.parentPath));
|
|
1359
1391
|
|
|
1360
1392
|
const html = `
|
|
1361
1393
|
<ul class="ee-folder-list">
|
|
1362
1394
|
${sortedFolders
|
|
1363
|
-
.map(folder => {
|
|
1364
|
-
const
|
|
1365
|
-
const hasChildren = this.folders.some(f => f.parentPath === folder.path);
|
|
1395
|
+
.map(({ folder, depth }) => {
|
|
1396
|
+
const hasChildren = parentPaths.has(folder.path);
|
|
1366
1397
|
return `
|
|
1367
1398
|
<li class="ee-folder-item ${folder.path === this.currentFolder ? 'active' : ''}"
|
|
1368
1399
|
data-path="${this.escapeHtml(folder.path)}"
|
|
@@ -1389,7 +1420,7 @@ export class EmailEngineClient {
|
|
|
1389
1420
|
}
|
|
1390
1421
|
|
|
1391
1422
|
renderMessageList() {
|
|
1392
|
-
if (typeof document === 'undefined' || !this.container) {
|
|
1423
|
+
if (typeof document === 'undefined' || !this.container || this._destroyed) {
|
|
1393
1424
|
return;
|
|
1394
1425
|
}
|
|
1395
1426
|
|
|
@@ -1489,7 +1520,7 @@ export class EmailEngineClient {
|
|
|
1489
1520
|
}
|
|
1490
1521
|
|
|
1491
1522
|
renderMessage() {
|
|
1492
|
-
if (typeof document === 'undefined' || !this.container) {
|
|
1523
|
+
if (typeof document === 'undefined' || !this.container || this._destroyed) {
|
|
1493
1524
|
return;
|
|
1494
1525
|
}
|
|
1495
1526
|
|
|
@@ -1513,8 +1544,7 @@ export class EmailEngineClient {
|
|
|
1513
1544
|
<select class="ee-button" data-action="move">
|
|
1514
1545
|
<option value="">Move to...</option>
|
|
1515
1546
|
${this.buildFolderTree()
|
|
1516
|
-
.map(folder => {
|
|
1517
|
-
const depth = this.calculateFolderDepth(folder);
|
|
1547
|
+
.map(({ folder, depth }) => {
|
|
1518
1548
|
const indent = ' '.repeat(depth);
|
|
1519
1549
|
const prefix = depth > 0 ? '└ ' : '';
|
|
1520
1550
|
return `<option value="${this.escapeHtml(folder.path)}" ${folder.path === this.currentFolder ? 'disabled' : ''}>${indent}${prefix}${this.escapeHtml(folder.name)}</option>`;
|
|
@@ -1627,9 +1657,13 @@ export class EmailEngineClient {
|
|
|
1627
1657
|
|
|
1628
1658
|
this.container.innerHTML = `
|
|
1629
1659
|
<div class="ee-client${this.darkMode ? ' ee-dark-mode' : ''}">
|
|
1630
|
-
|
|
1660
|
+
${
|
|
1661
|
+
this.showDarkModeToggle
|
|
1662
|
+
? `<button class="ee-dark-mode-toggle" title="Toggle dark mode">
|
|
1631
1663
|
<span class="ee-dark-mode-icon">${this.darkMode ? '☀️' : '🌙'}</span>
|
|
1632
|
-
</button
|
|
1664
|
+
</button>`
|
|
1665
|
+
: ''
|
|
1666
|
+
}
|
|
1633
1667
|
<div class="ee-sidebar">
|
|
1634
1668
|
<div class="ee-pane-header">
|
|
1635
1669
|
<span class="ee-pane-title">Folders</span>
|
|
@@ -1721,11 +1755,12 @@ export class EmailEngineClient {
|
|
|
1721
1755
|
});
|
|
1722
1756
|
|
|
1723
1757
|
// Close on Escape key
|
|
1724
|
-
|
|
1758
|
+
this._composeKeydownHandler = e => {
|
|
1725
1759
|
if (e.key === 'Escape' && modal.classList.contains('show')) {
|
|
1726
1760
|
closeModal();
|
|
1727
1761
|
}
|
|
1728
|
-
}
|
|
1762
|
+
};
|
|
1763
|
+
document.addEventListener('keydown', this._composeKeydownHandler);
|
|
1729
1764
|
|
|
1730
1765
|
// Send email
|
|
1731
1766
|
sendButton.addEventListener('click', async () => {
|
|
@@ -1920,12 +1955,14 @@ export class EmailEngineClient {
|
|
|
1920
1955
|
}
|
|
1921
1956
|
}
|
|
1922
1957
|
|
|
1923
|
-
|
|
1924
|
-
|
|
1958
|
+
// Set dark mode from the host application (does not touch the stored
|
|
1959
|
+
// preference - the builtin toggle owns that)
|
|
1960
|
+
setDarkMode(enabled) {
|
|
1961
|
+
this.darkMode = !!enabled;
|
|
1925
1962
|
|
|
1926
|
-
//
|
|
1927
|
-
if (
|
|
1928
|
-
|
|
1963
|
+
// DOM updates only apply to the rendered UI; skip without a container
|
|
1964
|
+
if (!this.container) {
|
|
1965
|
+
return;
|
|
1929
1966
|
}
|
|
1930
1967
|
|
|
1931
1968
|
// Update UI
|
|
@@ -1945,41 +1982,71 @@ export class EmailEngineClient {
|
|
|
1945
1982
|
}
|
|
1946
1983
|
}
|
|
1947
1984
|
|
|
1985
|
+
toggleDarkMode() {
|
|
1986
|
+
this.setDarkMode(!this.darkMode);
|
|
1987
|
+
|
|
1988
|
+
// Save preference
|
|
1989
|
+
if (typeof window !== 'undefined' && window.localStorage) {
|
|
1990
|
+
localStorage.setItem('ee-client-dark-mode', this.darkMode.toString());
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1948
1994
|
destroy() {
|
|
1995
|
+
// Mark destroyed first so any in-flight async completion skips
|
|
1996
|
+
// re-rendering into a torn-down or recreated container.
|
|
1997
|
+
this._destroyed = true;
|
|
1998
|
+
|
|
1949
1999
|
// Clean up keep-alive timer
|
|
1950
2000
|
if (this.keepAliveTimer) {
|
|
1951
2001
|
clearInterval(this.keepAliveTimer);
|
|
1952
2002
|
this.keepAliveTimer = null;
|
|
1953
2003
|
}
|
|
2004
|
+
|
|
2005
|
+
// Remove the compose button's window scroll/resize listeners
|
|
2006
|
+
if (this._composeButtonCleanup) {
|
|
2007
|
+
this._composeButtonCleanup();
|
|
2008
|
+
this._composeButtonCleanup = null;
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
// Remove the document-level Escape keydown listener
|
|
2012
|
+
if (this._composeKeydownHandler && typeof document !== 'undefined') {
|
|
2013
|
+
document.removeEventListener('keydown', this._composeKeydownHandler);
|
|
2014
|
+
this._composeKeydownHandler = null;
|
|
2015
|
+
}
|
|
2016
|
+
|
|
2017
|
+
// Remove the injected stylesheet
|
|
2018
|
+
if (this._styleElement && this._styleElement.parentNode) {
|
|
2019
|
+
this._styleElement.parentNode.removeChild(this._styleElement);
|
|
2020
|
+
this._styleElement = null;
|
|
2021
|
+
}
|
|
1954
2022
|
}
|
|
1955
2023
|
}
|
|
1956
2024
|
|
|
1957
2025
|
export function createEmailEngineClient(options) {
|
|
1958
|
-
if (typeof options
|
|
1959
|
-
options
|
|
1960
|
-
container: typeof document !== 'undefined' ? document.getElementById(options) : null
|
|
1961
|
-
};
|
|
1962
|
-
} else if (typeof HTMLElement !== 'undefined' && options instanceof HTMLElement) {
|
|
1963
|
-
options = {
|
|
1964
|
-
container: options
|
|
1965
|
-
};
|
|
1966
|
-
} else if (typeof options === 'object' && options.containerId) {
|
|
1967
|
-
options.container = typeof document !== 'undefined' ? document.getElementById(options.containerId) : null;
|
|
2026
|
+
if (!options || typeof options !== 'object') {
|
|
2027
|
+
throw new Error('Invalid options: expected an options object');
|
|
1968
2028
|
}
|
|
1969
2029
|
|
|
1970
|
-
if (
|
|
1971
|
-
throw new Error('
|
|
2030
|
+
if (!options.account) {
|
|
2031
|
+
throw new Error('Account identifier is required');
|
|
1972
2032
|
}
|
|
1973
2033
|
|
|
1974
2034
|
if (!options.apiUrl) {
|
|
1975
2035
|
console.warn('No API URL specified, using default http://127.0.0.1:3000');
|
|
1976
2036
|
}
|
|
1977
2037
|
|
|
1978
|
-
|
|
1979
|
-
|
|
2038
|
+
const client = new EmailEngineClient(options);
|
|
2039
|
+
|
|
2040
|
+
// The constructor is the single place that resolves containerId to an
|
|
2041
|
+
// element. In a DOM environment a containerId that matches nothing is a
|
|
2042
|
+
// caller error, so fail loudly here - and tear down the half-built client
|
|
2043
|
+
// so its keep-alive timer does not leak.
|
|
2044
|
+
if (options.containerId && !client.container && typeof document !== 'undefined') {
|
|
2045
|
+
client.destroy();
|
|
2046
|
+
throw new Error('Container element not found');
|
|
1980
2047
|
}
|
|
1981
2048
|
|
|
1982
|
-
return
|
|
2049
|
+
return client;
|
|
1983
2050
|
}
|
|
1984
2051
|
|
|
1985
2052
|
export default EmailEngineClient;
|