@postalsys/ee-client 1.0.1 → 1.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.
Files changed (5) hide show
  1. package/README.md +69 -13
  2. package/index.d.ts +1 -0
  3. package/index.js +486 -5
  4. package/package.json +3 -10
  5. package/index.cjs +0 -1188
package/README.md CHANGED
@@ -52,18 +52,6 @@ const { messages } = await client.loadMessages('INBOX');
52
52
  const message = await client.loadMessage(messages[0].id);
53
53
  ```
54
54
 
55
- ### CommonJS
56
-
57
- ```javascript
58
- const { EmailEngineClient } = require('@postalsys/ee-client');
59
-
60
- const client = new EmailEngineClient({
61
- apiUrl: 'https://your-emailengine-server.com',
62
- account: 'your-account-id',
63
- accessToken: 'your-access-token'
64
- });
65
- ```
66
-
67
55
  ## API
68
56
 
69
57
  ### Constructor Options
@@ -72,6 +60,8 @@ const client = new EmailEngineClient({
72
60
  - `account` (string, required): Account identifier
73
61
  - `accessToken` (string, optional): Access token for authentication
74
62
  - `container` (HTMLElement, optional): DOM container for UI components (browser only)
63
+ - `confirmMethod` (function, optional): Custom confirm dialog method. Receives `(message, title, cancelText, okText)` parameters. Can be sync or async. Defaults to browser's `confirm()` with standard parameters.
64
+ - `alertMethod` (function, optional): Custom alert dialog method. Receives `(message, title, cancelText, okText)` parameters where `cancelText` is `null` for alerts. Can be sync or async. Defaults to browser's `alert()` with standard parameters.
75
65
 
76
66
  ### Methods
77
67
 
@@ -99,6 +89,14 @@ Delete a message.
99
89
 
100
90
  Move a message to another folder.
101
91
 
92
+ #### `sendMessage(to: string | object | array, subject: string, text: string): Promise<object>`
93
+
94
+ Send a new email message. The `to` parameter can be:
95
+
96
+ - A string email address: `'user@example.com'`
97
+ - An object with name and address: `{ name: 'John Doe', address: 'john@example.com' }`
98
+ - An array of strings or objects for multiple recipients
99
+
102
100
  ## Browser UI
103
101
 
104
102
  When used in a browser with a container element, the client automatically creates a full email interface with:
@@ -117,11 +115,69 @@ When used in a browser with a container element, the client automatically create
117
115
  apiUrl: 'https://your-emailengine-server.com',
118
116
  account: 'your-account-id',
119
117
  accessToken: 'your-access-token',
120
- container: document.getElementById('email-client')
118
+ container: document.getElementById('email-client'),
119
+ // Optional: Custom confirm dialog
120
+ confirmMethod: async message => {
121
+ return await myCustomDialog.confirm(message);
122
+ }
121
123
  });
122
124
  </script>
123
125
  ```
124
126
 
127
+ ### Custom Dialog Methods
128
+
129
+ You can provide custom alert and confirm dialog methods that will be used instead of the browser's default dialogs. This is useful for integrating with UI frameworks or custom dialog systems:
130
+
131
+ ```javascript
132
+ const client = new EmailEngineClient({
133
+ apiUrl: 'https://your-emailengine-server.com',
134
+ account: 'your-account-id',
135
+ accessToken: 'your-access-token',
136
+ container: document.getElementById('email-client'),
137
+
138
+ // Custom alert method
139
+ alertMethod: async (message, title, cancelText, okText) => {
140
+ return await MyModal.alert({
141
+ title: title, // e.g., "Success", "Error", "Notice"
142
+ message: message,
143
+ okButton: okText // e.g., "OK"
144
+ // cancelText is null for alerts
145
+ });
146
+ },
147
+
148
+ // Custom confirm method
149
+ confirmMethod: async (message, title, cancelText, okText) => {
150
+ return await MyModal.confirm({
151
+ title: title, // e.g., "Delete Message", "Confirm"
152
+ message: message,
153
+ cancelButton: cancelText, // e.g., "Cancel"
154
+ okButton: okText // e.g., "Delete", "OK"
155
+ });
156
+ }
157
+ });
158
+ ```
159
+
160
+ #### Dialog Method Signatures
161
+
162
+ Both methods receive the same parameters:
163
+
164
+ - `message` (string): The message to display
165
+ - `title` (string): Dialog title (defaults: "Confirm" for confirm, "Notice" for alert)
166
+ - `cancelText` (string|null): Cancel button text ("Cancel" for confirm, `null` for alert)
167
+ - `okText` (string): OK/action button text (defaults: "OK")
168
+
169
+ #### Built-in Dialog Types
170
+
171
+ The library uses contextually appropriate titles and button texts:
172
+
173
+ - **Validation errors**: `alertMethod(message, "Validation Error", null, "OK")`
174
+ - **Success messages**: `alertMethod(message, "Success", null, "OK")`
175
+ - **Send errors**: `alertMethod(message, "Send Error", null, "OK")`
176
+ - **Download errors**: `alertMethod(message, "Download Error", null, "OK")`
177
+ - **Delete confirmation**: `confirmMethod(message, "Delete Message", "Cancel", "Delete")`
178
+
179
+ Both methods can be synchronous or asynchronous and should return a boolean for confirm dialogs.
180
+
125
181
  ## License
126
182
 
127
183
  MIT © Postal Systems OÜ
package/index.d.ts CHANGED
@@ -50,6 +50,7 @@ export interface EmailEngineClientOptions {
50
50
  accessToken?: string;
51
51
  container?: HTMLElement;
52
52
  containerId?: string;
53
+ confirmMethod?: (message: string) => boolean | Promise<boolean>;
53
54
  }
54
55
 
55
56
  export declare class EmailEngineClient {
package/index.js CHANGED
@@ -4,6 +4,11 @@ export class EmailEngineClient {
4
4
  this.account = options.account;
5
5
  this.accessToken = options.accessToken;
6
6
  this.container = options.container;
7
+ this.confirmMethod =
8
+ options.confirmMethod ||
9
+ ((message, _title = 'Confirm', _cancelText = 'Cancel', _okText = 'OK') => confirm(message));
10
+ this.alertMethod =
11
+ options.alertMethod || ((message, _title = 'Notice', _cancelText = null, _okText = 'OK') => alert(message));
7
12
 
8
13
  this.currentFolder = null;
9
14
  this.currentMessage = null;
@@ -57,7 +62,18 @@ export class EmailEngineClient {
57
62
 
58
63
  const response = await fetchFn(url, options);
59
64
  if (!response.ok) {
60
- throw new Error(`API request failed: ${response.statusText}`);
65
+ let errorDetails;
66
+ try {
67
+ errorDetails = await response.json();
68
+ } catch (parseError) {
69
+ // If JSON parsing fails, fall back to status text
70
+ errorDetails = { message: response.statusText };
71
+ }
72
+
73
+ const error = new Error(`API request failed: ${response.statusText}`);
74
+ error.statusCode = response.status;
75
+ error.details = errorDetails;
76
+ throw error;
61
77
  }
62
78
 
63
79
  return await response.json();
@@ -97,9 +113,13 @@ export class EmailEngineClient {
97
113
  this.nextPageCursor = data.nextPageCursor || null;
98
114
  this.prevPageCursor = data.prevPageCursor || null;
99
115
 
116
+ // Clear active email selection when folder changes
117
+ this.currentMessage = null;
118
+
100
119
  if (this.container) {
101
120
  this.renderMessageList();
102
121
  this.renderFolderList(); // Re-render to update active state
122
+ this.renderMessage(); // Clear message viewer
103
123
  }
104
124
 
105
125
  return {
@@ -238,6 +258,73 @@ export class EmailEngineClient {
238
258
  }
239
259
  }
240
260
 
261
+ async sendMessage(to, subject, text) {
262
+ try {
263
+ const toAddresses = Array.isArray(to)
264
+ ? to.map(addr => (typeof addr === 'string' ? { address: addr } : addr))
265
+ : [typeof to === 'string' ? { address: to } : to];
266
+
267
+ const messageData = {
268
+ to: toAddresses,
269
+ subject: subject,
270
+ text: text
271
+ };
272
+
273
+ const response = await this.apiRequest('POST', `/v1/account/${this.account}/submit`, messageData);
274
+ return response;
275
+ } catch (error) {
276
+ console.error('Failed to send message:', error);
277
+ // Try to parse detailed error information
278
+ this._parseApiError(error);
279
+ throw error;
280
+ }
281
+ }
282
+
283
+ _parseApiError(error) {
284
+ try {
285
+ // If error has response text, try to parse it
286
+ if (error.message && error.message.includes('API request failed:')) {
287
+ // This is our custom error from apiRequest, the actual response might have more details
288
+ error.isDetailedError = false;
289
+ }
290
+ } catch (parseError) {
291
+ // If parsing fails, just use the original error
292
+ console.error('Failed to parse error details:', parseError);
293
+ }
294
+ }
295
+
296
+ _formatSendError(error) {
297
+ // If we have detailed error information from the API
298
+ if (error.details && error.details.fields && Array.isArray(error.details.fields)) {
299
+ const fieldErrors = error.details.fields.map(field => {
300
+ // Try to make field errors more user-friendly
301
+ let message = field.message;
302
+
303
+ // Map technical field names to user-friendly names
304
+ if (message.includes('to[0].address') || message.includes('"address"')) {
305
+ message = message.replace(/to\[\d+\]\.address|"address"/g, 'email address');
306
+ }
307
+ if (message.includes('"subject"')) {
308
+ message = message.replace('"subject"', 'subject');
309
+ }
310
+ if (message.includes('"text"')) {
311
+ message = message.replace('"text"', 'message');
312
+ }
313
+
314
+ return message;
315
+ });
316
+
317
+ const mainMessage = error.details.message || 'Failed to send email';
318
+ if (fieldErrors.length > 0) {
319
+ return `${mainMessage}:\n\n• ${fieldErrors.join('\n• ')}`;
320
+ }
321
+ return mainMessage;
322
+ }
323
+
324
+ // Fallback to generic error message
325
+ return 'Failed to send email. Please check your input and try again.';
326
+ }
327
+
241
328
  formatDate(dateStr) {
242
329
  const date = new Date(dateStr);
243
330
  const now = new Date();
@@ -301,7 +388,7 @@ export class EmailEngineClient {
301
388
  window.URL.revokeObjectURL(url);
302
389
  } catch (error) {
303
390
  console.error('Failed to download attachment:', error);
304
- alert('Failed to download attachment');
391
+ this.alertMethod('Failed to download attachment. Please try again.', 'Download Error', null, 'OK');
305
392
  }
306
393
  }
307
394
 
@@ -341,7 +428,7 @@ export class EmailEngineClient {
341
428
  window.URL.revokeObjectURL(url);
342
429
  } catch (error) {
343
430
  console.error('Failed to download original message:', error);
344
- alert('Failed to download original message');
431
+ this.alertMethod('Failed to download original message. Please try again.', 'Download Error', null, 'OK');
345
432
  }
346
433
  }
347
434
 
@@ -362,6 +449,7 @@ export class EmailEngineClient {
362
449
  color: #333;
363
450
  background: #fff;
364
451
  border: 1px solid #ddd;
452
+ position: relative;
365
453
  }
366
454
 
367
455
  .ee-client * {
@@ -758,6 +846,185 @@ export class EmailEngineClient {
758
846
  flex: 1;
759
847
  overflow-y: auto;
760
848
  }
849
+
850
+ .ee-compose-button {
851
+ position: fixed;
852
+ bottom: 20px;
853
+ right: 20px;
854
+ width: 56px;
855
+ height: 56px;
856
+ background: #007bff;
857
+ border: none;
858
+ border-radius: 50%;
859
+ color: white;
860
+ font-size: 24px;
861
+ cursor: pointer;
862
+ box-shadow: 0 4px 12px rgba(0,123,255,0.3);
863
+ z-index: 1000;
864
+ transition: all 0.2s ease;
865
+ }
866
+
867
+ .ee-compose-button:hover {
868
+ background: #0056b3;
869
+ transform: scale(1.05);
870
+ box-shadow: 0 6px 16px rgba(0,123,255,0.4);
871
+ }
872
+
873
+ .ee-compose-modal {
874
+ display: none;
875
+ position: fixed;
876
+ top: 0;
877
+ left: 0;
878
+ width: 100%;
879
+ height: 100%;
880
+ background: rgba(0, 0, 0, 0.5);
881
+ z-index: 2000;
882
+ }
883
+
884
+ .ee-compose-modal.show {
885
+ display: flex;
886
+ align-items: center;
887
+ justify-content: center;
888
+ }
889
+
890
+ .ee-compose-dialog {
891
+ background: white;
892
+ border-radius: 8px;
893
+ width: 90%;
894
+ max-width: 600px;
895
+ max-height: 80vh;
896
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
897
+ display: flex;
898
+ flex-direction: column;
899
+ }
900
+
901
+ .ee-compose-header {
902
+ padding: 16px 20px;
903
+ border-bottom: 1px solid #e0e0e0;
904
+ display: flex;
905
+ justify-content: space-between;
906
+ align-items: center;
907
+ flex-shrink: 0;
908
+ }
909
+
910
+ .ee-compose-title {
911
+ font-size: 18px;
912
+ font-weight: 600;
913
+ margin: 0;
914
+ }
915
+
916
+ .ee-compose-close {
917
+ background: none;
918
+ border: none;
919
+ font-size: 24px;
920
+ color: #666;
921
+ cursor: pointer;
922
+ padding: 0;
923
+ width: 30px;
924
+ height: 30px;
925
+ border-radius: 50%;
926
+ display: flex;
927
+ align-items: center;
928
+ justify-content: center;
929
+ }
930
+
931
+ .ee-compose-close:hover {
932
+ background: #f0f0f0;
933
+ }
934
+
935
+ .ee-compose-form {
936
+ padding: 20px;
937
+ display: flex;
938
+ flex-direction: column;
939
+ gap: 16px;
940
+ flex: 1;
941
+ overflow-y: auto;
942
+ }
943
+
944
+ .ee-compose-field {
945
+ display: flex;
946
+ flex-direction: column;
947
+ gap: 4px;
948
+ }
949
+
950
+ .ee-compose-label {
951
+ font-weight: 500;
952
+ color: #333;
953
+ }
954
+
955
+ .ee-compose-input {
956
+ padding: 8px 12px;
957
+ border: 1px solid #ddd;
958
+ border-radius: 4px;
959
+ font-size: 14px;
960
+ font-family: inherit;
961
+ }
962
+
963
+ .ee-compose-input:focus {
964
+ outline: none;
965
+ border-color: #007bff;
966
+ box-shadow: 0 0 0 2px rgba(0,123,255,0.1);
967
+ }
968
+
969
+ .ee-compose-textarea {
970
+ padding: 12px;
971
+ border: 1px solid #ddd;
972
+ border-radius: 4px;
973
+ font-size: 14px;
974
+ font-family: inherit;
975
+ resize: vertical;
976
+ min-height: 200px;
977
+ }
978
+
979
+ .ee-compose-textarea:focus {
980
+ outline: none;
981
+ border-color: #007bff;
982
+ box-shadow: 0 0 0 2px rgba(0,123,255,0.1);
983
+ }
984
+
985
+ .ee-compose-actions {
986
+ padding: 16px 20px;
987
+ border-top: 1px solid #e0e0e0;
988
+ display: flex;
989
+ gap: 12px;
990
+ justify-content: flex-end;
991
+ flex-shrink: 0;
992
+ }
993
+
994
+ .ee-compose-send {
995
+ background: #007bff;
996
+ color: white;
997
+ border: none;
998
+ padding: 10px 20px;
999
+ border-radius: 4px;
1000
+ font-size: 14px;
1001
+ font-weight: 500;
1002
+ cursor: pointer;
1003
+ }
1004
+
1005
+ .ee-compose-send:hover:not(:disabled) {
1006
+ background: #0056b3;
1007
+ }
1008
+
1009
+ .ee-compose-send:disabled {
1010
+ background: #6c757d;
1011
+ cursor: not-allowed;
1012
+ opacity: 0.6;
1013
+ }
1014
+
1015
+ .ee-compose-cancel {
1016
+ background: #6c757d;
1017
+ color: white;
1018
+ border: none;
1019
+ padding: 10px 20px;
1020
+ border-radius: 4px;
1021
+ font-size: 14px;
1022
+ cursor: pointer;
1023
+ }
1024
+
1025
+ .ee-compose-cancel:hover {
1026
+ background: #545b62;
1027
+ }
761
1028
  `;
762
1029
  document.head.appendChild(style);
763
1030
  }
@@ -1072,8 +1339,14 @@ export class EmailEngineClient {
1072
1339
  this.markAsRead(msg.id, currentlyUnseen);
1073
1340
  });
1074
1341
 
1075
- viewer.querySelector('[data-action="delete"]').addEventListener('click', () => {
1076
- if (confirm('Delete this message?')) {
1342
+ viewer.querySelector('[data-action="delete"]').addEventListener('click', async () => {
1343
+ const result = await this.confirmMethod(
1344
+ 'Are you sure you want to delete this message? This action cannot be undone.',
1345
+ 'Delete Message',
1346
+ 'Cancel',
1347
+ 'Delete'
1348
+ );
1349
+ if (result) {
1077
1350
  this.deleteMessage(msg.id);
1078
1351
  }
1079
1352
  });
@@ -1097,6 +1370,12 @@ export class EmailEngineClient {
1097
1370
  this.downloadAttachment(attachmentId, attachment ? attachment.filename : null);
1098
1371
  });
1099
1372
  });
1373
+
1374
+ // Scroll message viewer back to top when new email is displayed
1375
+ const messageContent = viewer.querySelector('.ee-message-content');
1376
+ if (messageContent) {
1377
+ messageContent.scrollTop = 0;
1378
+ }
1100
1379
  }
1101
1380
 
1102
1381
  createLayout() {
@@ -1124,7 +1403,209 @@ export class EmailEngineClient {
1124
1403
  <div class="ee-empty-state">Select a message to view</div>
1125
1404
  </div>
1126
1405
  </div>
1406
+ <button class="ee-compose-button" title="Compose Email">✉</button>
1407
+ <div class="ee-compose-modal">
1408
+ <div class="ee-compose-dialog">
1409
+ <div class="ee-compose-header">
1410
+ <h3 class="ee-compose-title">Compose Email</h3>
1411
+ <button class="ee-compose-close">×</button>
1412
+ </div>
1413
+ <form class="ee-compose-form">
1414
+ <div class="ee-compose-field">
1415
+ <label class="ee-compose-label">To:</label>
1416
+ <input type="email" class="ee-compose-input" name="to" placeholder="recipient@example.com" required>
1417
+ </div>
1418
+ <div class="ee-compose-field">
1419
+ <label class="ee-compose-label">Subject:</label>
1420
+ <input type="text" class="ee-compose-input" name="subject" placeholder="Enter subject">
1421
+ </div>
1422
+ <div class="ee-compose-field">
1423
+ <label class="ee-compose-label">Message:</label>
1424
+ <textarea class="ee-compose-textarea" name="message" placeholder="Type your message here..." required></textarea>
1425
+ </div>
1426
+ </form>
1427
+ <div class="ee-compose-actions">
1428
+ <button type="button" class="ee-compose-cancel">Cancel</button>
1429
+ <button type="button" class="ee-compose-send">Send</button>
1430
+ </div>
1431
+ </div>
1432
+ </div>
1127
1433
  `;
1434
+
1435
+ // Wire up compose modal events
1436
+ this.setupComposeModal();
1437
+
1438
+ // Position compose button correctly
1439
+ this.positionComposeButton();
1440
+ }
1441
+
1442
+ setupComposeModal() {
1443
+ if (typeof document === 'undefined' || !this.container) {
1444
+ return;
1445
+ }
1446
+
1447
+ const composeButton = this.container.querySelector('.ee-compose-button');
1448
+ const modal = this.container.querySelector('.ee-compose-modal');
1449
+ const closeButton = this.container.querySelector('.ee-compose-close');
1450
+ const cancelButton = this.container.querySelector('.ee-compose-cancel');
1451
+ const sendButton = this.container.querySelector('.ee-compose-send');
1452
+ const form = this.container.querySelector('.ee-compose-form');
1453
+
1454
+ // Open modal
1455
+ composeButton.addEventListener('click', () => {
1456
+ modal.classList.add('show');
1457
+ // Focus the To field
1458
+ const toField = form.querySelector('input[name="to"]');
1459
+ setTimeout(() => toField.focus(), 100);
1460
+ });
1461
+
1462
+ // Close modal handlers
1463
+ const closeModal = () => {
1464
+ modal.classList.remove('show');
1465
+ form.reset();
1466
+ };
1467
+
1468
+ closeButton.addEventListener('click', closeModal);
1469
+ cancelButton.addEventListener('click', closeModal);
1470
+
1471
+ // Close on backdrop click
1472
+ modal.addEventListener('click', e => {
1473
+ if (e.target === modal) {
1474
+ closeModal();
1475
+ }
1476
+ });
1477
+
1478
+ // Close on Escape key
1479
+ document.addEventListener('keydown', e => {
1480
+ if (e.key === 'Escape' && modal.classList.contains('show')) {
1481
+ closeModal();
1482
+ }
1483
+ });
1484
+
1485
+ // Send email
1486
+ sendButton.addEventListener('click', async () => {
1487
+ const formData = new FormData(form);
1488
+ const to = formData.get('to').trim();
1489
+ const subject = formData.get('subject').trim();
1490
+ const message = formData.get('message').trim();
1491
+
1492
+ if (!to || !message) {
1493
+ // Close modal temporarily to show alert, then reopen
1494
+ modal.classList.remove('show');
1495
+ await this.alertMethod(
1496
+ 'Please fill in the recipient and message fields.',
1497
+ 'Validation Error',
1498
+ null,
1499
+ 'OK'
1500
+ );
1501
+ modal.classList.add('show');
1502
+ // Re-focus the appropriate field
1503
+ const fieldToFocus = !to
1504
+ ? form.querySelector('input[name="to"]')
1505
+ : form.querySelector('textarea[name="message"]');
1506
+ setTimeout(() => fieldToFocus.focus(), 100);
1507
+ return;
1508
+ }
1509
+
1510
+ // Disable send button and show loading state
1511
+ const originalText = sendButton.textContent;
1512
+ sendButton.disabled = true;
1513
+ sendButton.textContent = 'Sending...';
1514
+
1515
+ try {
1516
+ await this.sendMessage(to, subject, message);
1517
+ // Close modal before showing success alert
1518
+ closeModal();
1519
+ await this.alertMethod('Email sent successfully!', 'Success', null, 'OK');
1520
+ } catch (error) {
1521
+ console.error('Failed to send email:', error);
1522
+ // Close modal before showing error alert
1523
+ modal.classList.remove('show');
1524
+ const errorMessage = this._formatSendError(error);
1525
+ await this.alertMethod(errorMessage, 'Send Error', null, 'OK');
1526
+
1527
+ // Reopen modal with preserved values after error alert
1528
+ modal.classList.add('show');
1529
+ // Re-focus the To field to allow user to continue editing
1530
+ const toField = form.querySelector('input[name="to"]');
1531
+ setTimeout(() => toField.focus(), 100);
1532
+ } finally {
1533
+ // Re-enable send button
1534
+ sendButton.disabled = false;
1535
+ sendButton.textContent = originalText;
1536
+ }
1537
+ });
1538
+
1539
+ // Handle Enter key in form (Ctrl+Enter to send)
1540
+ form.addEventListener('keydown', e => {
1541
+ if (e.key === 'Enter' && e.ctrlKey) {
1542
+ e.preventDefault();
1543
+ sendButton.click();
1544
+ }
1545
+ });
1546
+ }
1547
+
1548
+ positionComposeButton() {
1549
+ if (typeof document === 'undefined' || !this.container) {
1550
+ return;
1551
+ }
1552
+
1553
+ const composeButton = this.container.querySelector('.ee-compose-button');
1554
+ if (!composeButton) {
1555
+ return;
1556
+ }
1557
+
1558
+ const updateButtonPosition = () => {
1559
+ const containerRect = this.container.getBoundingClientRect();
1560
+ const buttonSize = 56; // Button width/height
1561
+ const margin = 20; // Desired margin from edges
1562
+
1563
+ // Calculate the ideal position (bottom-right of container with margin)
1564
+ const idealBottom = window.innerHeight - containerRect.bottom + margin;
1565
+ const idealRight = window.innerWidth - containerRect.right + margin;
1566
+
1567
+ // Ensure button stays within viewport bounds
1568
+ const minBottom = margin;
1569
+ const minRight = margin;
1570
+
1571
+ // Also ensure button stays within container horizontal bounds
1572
+ const maxRight = window.innerWidth - containerRect.left - buttonSize - margin;
1573
+
1574
+ // Calculate final position
1575
+ const bottom = Math.max(minBottom, idealBottom);
1576
+ const right = Math.min(Math.max(minRight, idealRight), maxRight);
1577
+
1578
+ // Apply positioning
1579
+ composeButton.style.bottom = `${bottom}px`;
1580
+ composeButton.style.right = `${right}px`;
1581
+ };
1582
+
1583
+ // Initial positioning
1584
+ updateButtonPosition();
1585
+
1586
+ // Update position on scroll and resize
1587
+ const updateWithThrottle = this.throttle(updateButtonPosition, 16); // ~60fps
1588
+ window.addEventListener('scroll', updateWithThrottle);
1589
+ window.addEventListener('resize', updateWithThrottle);
1590
+
1591
+ // Store cleanup function for potential future use
1592
+ this._composeButtonCleanup = () => {
1593
+ window.removeEventListener('scroll', updateWithThrottle);
1594
+ window.removeEventListener('resize', updateWithThrottle);
1595
+ };
1596
+ }
1597
+
1598
+ throttle(func, limit) {
1599
+ let inThrottle;
1600
+ return function () {
1601
+ const args = arguments;
1602
+ const context = this;
1603
+ if (!inThrottle) {
1604
+ func.apply(context, args);
1605
+ inThrottle = true;
1606
+ setTimeout(() => (inThrottle = false), limit);
1607
+ }
1608
+ };
1128
1609
  }
1129
1610
 
1130
1611
  init() {