-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1862 lines (1638 loc) · 58.7 KB
/
content.js
File metadata and controls
1862 lines (1638 loc) · 58.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Superhuman Power Tools — Content Script
// Runs on mail.superhuman.com
// Feature 1: Auto-clicks "SEND ANYWAY" / "SCHEDULE ANYWAY" popups
// Feature 2: Extracts email data for Gmail filter creation
// Feature 4: Copy email content button
// Feature 5: AI-powered email summarization via Anthropic API
console.log("Superhuman Power Tools loaded!");
// ============================================================================
// FEATURE 3: Hide "Comment & Share Conversation" hover popup
// The .CommentInput-container.isHidden element triggers a tether-positioned
// tooltip when the mouse hovers near the bottom of an email thread.
// We force it to stay invisible and ignore pointer events.
// ============================================================================
const style = document.createElement("style");
style.textContent = `
.CommentInput-container.isHidden {
display: none !important;
pointer-events: none !important;
}
`;
document.documentElement.appendChild(style);
// ============================================================================
// FEATURE 1: Popup Auto-Clicker (Focus-Safe)
// Automatically dismisses subject-line warning popups in Superhuman.
// Polls every 150ms for the alert button, clicks it, then enters a 3s cooldown.
// ============================================================================
let hasClicked = false;
let clickTimeout = null;
let errorReports = [];
// --- Error tracking (rolling buffer of 10) ---
window.addEventListener("error", function (event) {
const report = {
timestamp: new Date().toISOString(),
type: "JavaScript Error",
message: event.message,
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
error: event.error ? event.error.toString() : "Unknown error",
url: window.location.href,
userAgent: navigator.userAgent,
focusInfo: {
activeElement: document.activeElement
? document.activeElement.tagName
: "none",
hasFocus: document.hasFocus(),
},
};
errorReports.push(report);
console.error("EXTENSION ERROR DETECTED:", report);
if (errorReports.length > 10) {
errorReports = errorReports.slice(-10);
}
});
window.addEventListener("unhandledrejection", function (event) {
const report = {
timestamp: new Date().toISOString(),
type: "Unhandled Promise Rejection",
reason: event.reason ? event.reason.toString() : "Unknown rejection",
url: window.location.href,
userAgent: navigator.userAgent,
focusInfo: {
activeElement: document.activeElement
? document.activeElement.tagName
: "none",
hasFocus: document.hasFocus(),
},
};
errorReports.push(report);
console.error("PROMISE REJECTION DETECTED:", report);
if (errorReports.length > 10) {
errorReports = errorReports.slice(-10);
}
});
// --- Environment report ---
function generateEnvironmentReport() {
return {
timestamp: new Date().toISOString(),
url: window.location.href,
userAgent: navigator.userAgent,
windowSize: `${window.innerWidth}x${window.innerHeight}`,
documentReady: document.readyState,
focus: {
documentHasFocus: document.hasFocus(),
activeElement: document.activeElement
? {
tagName: document.activeElement.tagName,
className: document.activeElement.className,
id: document.activeElement.id,
}
: null,
windowFocused: document.hasFocus(),
},
superhuman: {
alertElements: document.querySelectorAll(".Alert-action").length,
selectedAlerts: document.querySelectorAll(".Alert-action.selected").length,
allAlerts: Array.from(document.querySelectorAll(".Alert-action")).map(
(el) => ({
text: el.textContent,
classes: el.className,
visible: el.offsetParent !== null,
})
),
},
recentErrors: errorReports.slice(-5),
};
}
// --- Polling loop (150ms) ---
setInterval(() => {
if (hasClicked) return;
const sendButton = document.querySelector(".Alert-action.selected");
if (!sendButton) return;
const buttonText = sendButton.textContent;
if (buttonText.includes("SEND ANYWAY")) {
console.log("Found SEND ANYWAY button, clicking in 50ms...");
hasClicked = true;
clickTimeout = setTimeout(() => {
triggerFocusSafeClick(sendButton, "SEND ANYWAY");
resetClickFlag();
}, 50);
} else if (buttonText.includes("SCHEDULE ANYWAY")) {
console.log("Found SCHEDULE ANYWAY button, clicking in 50ms...");
hasClicked = true;
clickTimeout = setTimeout(() => {
triggerFocusSafeClick(sendButton, "SCHEDULE ANYWAY");
resetClickFlag();
}, 50);
}
}, 150);
// --- Click cooldown (3 seconds) ---
function resetClickFlag() {
setTimeout(() => {
hasClicked = false;
console.log("Ready for next click");
}, 3000);
}
// --- Focus-safe click ---
function triggerFocusSafeClick(element, buttonType) {
const preClickReport = generateEnvironmentReport();
console.log("PRE-CLICK ENVIRONMENT:", preClickReport);
const originalActiveElement = document.activeElement;
const originalHasFocus = document.hasFocus();
console.log("Focus before click:", {
activeElement: originalActiveElement
? originalActiveElement.tagName
: "none",
hasFocus: originalHasFocus,
});
try {
console.log(`Auto-clicking ${buttonType} button`);
console.log("Button properties:", {
text: element.textContent,
classes: element.className,
visible: element.offsetParent !== null,
disabled: element.disabled,
style: element.style.cssText,
});
element.click();
// Monitor focus changes after click
setTimeout(() => {
const postClickReport = generateEnvironmentReport();
console.log("POST-CLICK ENVIRONMENT:", postClickReport);
const newActiveElement = document.activeElement;
const newHasFocus = document.hasFocus();
console.log("Focus after click:", {
activeElement: newActiveElement ? newActiveElement.tagName : "none",
hasFocus: newHasFocus,
focusChanged: originalActiveElement !== newActiveElement,
focusLost: originalHasFocus && !newHasFocus,
});
if (originalHasFocus && !newHasFocus) {
console.warn("Focus was lost after clicking button!");
setTimeout(() => {
if (!document.hasFocus()) {
console.log("Attempting to restore window focus...");
window.focus();
}
}, 100);
}
const stillExists = document.contains(element);
console.log(`Button still exists after click: ${stillExists}`);
if (stillExists) {
console.warn(
"Button still exists after click - click might not have worked"
);
}
}, 1000);
console.log(`Successfully clicked ${buttonType}`);
} catch (error) {
const errorReport = {
timestamp: new Date().toISOString(),
type: "Click Error",
error: error.toString(),
stack: error.stack,
buttonType: buttonType,
element: {
tagName: element.tagName,
className: element.className,
textContent: element.textContent,
disabled: element.disabled,
},
environment: preClickReport,
};
console.error("Error clicking button:", errorReport);
errorReports.push(errorReport);
}
}
// --- Debug API (call from DevTools console) ---
window.getExtensionErrorReports = function () {
console.log("COMPLETE ERROR REPORT:");
console.log(JSON.stringify(errorReports, null, 2));
return errorReports;
};
window.getExtensionEnvironment = function () {
const report = generateEnvironmentReport();
console.log("CURRENT ENVIRONMENT:");
console.log(JSON.stringify(report, null, 2));
return report;
};
window.checkCurrentFocus = function () {
console.log("CURRENT FOCUS STATE:", {
documentHasFocus: document.hasFocus(),
activeElement: document.activeElement
? {
tagName: document.activeElement.tagName,
className: document.activeElement.className,
id: document.activeElement.id,
}
: "none",
});
};
// ============================================================================
// FEATURE 2: Gmail Filter Data Extraction
// Extracts sender email and subject from the currently open Superhuman email.
// Called by background.js when the user triggers the filter shortcut (Alt+G).
// ============================================================================
function extractEmailData() {
try {
const subjectEl =
document.querySelector(".ThreadPane-subject.isSelectable") ??
document.querySelector('[class*="ThreadPane-subject"]');
const fromEl =
document.querySelector(".ContactPane-email") ??
document.querySelector(".ContactPane-compose-to-link");
const subject = subjectEl?.textContent?.trim() || null;
const from = fromEl?.textContent?.trim() || null;
return { from, subject };
} catch (e) {
return { error: e.message };
}
}
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message.action === "extractEmailData") {
sendResponse(extractEmailData());
}
return true;
});
// ============================================================================
// FEATURE 4: Copy Email Button
// Injects a button near the email header to copy the email body to clipboard.
// Uses MutationObserver to detect email view changes and inject the button.
// ============================================================================
// --- Button styles (shared by Copy and Summarize) ---
const btnStyles = document.createElement("style");
btnStyles.textContent = `
.shpt-copy-btn,
.shpt-summarize-btn {
background: transparent;
border: 1px solid #555;
color: #999;
padding: 3px 10px;
border-radius: 4px;
font-size: 11px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
cursor: pointer;
margin-right: 8px;
transition: all 0.15s ease;
vertical-align: middle;
line-height: 1;
}
.shpt-copy-btn:hover,
.shpt-summarize-btn:hover {
background: rgba(255, 255, 255, 0.1);
border-color: #777;
color: #ccc;
}
.shpt-copy-btn:active,
.shpt-summarize-btn:active {
background: rgba(255, 255, 255, 0.15);
}
.shpt-copy-btn.shpt-copied {
color: #4caf50;
border-color: #4caf50;
}
.shpt-summarize-btn:disabled {
opacity: 0.6;
cursor: wait;
}
/* Summary Sidebar */
.shpt-sidebar {
position: fixed;
top: 0;
right: 0;
width: 380px;
height: 100vh;
background: #1a1a1a;
border-left: 1px solid #333;
display: flex;
flex-direction: column;
z-index: 999999;
box-shadow: -4px 0 16px rgba(0, 0, 0, 0.4);
transform: translateX(100%);
transition: transform 0.2s ease-out;
}
.shpt-sidebar.shpt-sidebar-open {
transform: translateX(0);
}
.shpt-sidebar-body {
padding: 10px;
overflow-y: auto;
flex: 1;
color: #e0e0e0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 13px;
line-height: 1.5;
}
.shpt-sidebar-body h1 {
font-size: 16px;
margin: 1.5em 0 0.4em 0;
}
.shpt-sidebar-body h2 {
font-size: 14px;
margin: 1.4em 0 0.3em 0;
}
.shpt-sidebar-body h3 {
font-size: 13px;
margin: 1.2em 0 0.3em 0;
}
.shpt-sidebar-body h1, .shpt-sidebar-body h2, .shpt-sidebar-body h3 {
color: #fff;
}
.shpt-sidebar-body h1:first-child,
.shpt-sidebar-body h2:first-child,
.shpt-sidebar-body h3:first-child {
margin-top: 0;
}
/* Requires Response highlight */
.shpt-response-yes {
color: #4caf50;
font-weight: 600;
}
.shpt-response-no {
color: #888;
font-weight: 600;
}
.shpt-response-maybe {
color: #ffb74d;
font-weight: 600;
}
.shpt-sidebar-body ul, .shpt-sidebar-body ol {
padding-left: 1.2em;
margin: 0.3em 0;
list-style-type: disc;
}
.shpt-sidebar-body li {
margin: 0.15em 0;
}
/* Nested lists - sub-items should be smaller/different */
.shpt-sidebar-body ul ul,
.shpt-sidebar-body ul ol {
list-style-type: circle;
margin: 0.1em 0;
}
.shpt-sidebar-body ul ul li,
.shpt-sidebar-body ol ul li {
font-size: 0.95em;
color: #c0c0c0;
}
.shpt-sidebar-body p {
margin: 0.3em 0;
}
.shpt-sidebar-body strong {
color: #fff;
}
.shpt-sidebar-body em {
color: #b0b0b0;
}
.shpt-sidebar-body code {
background: #2a2a2a;
padding: 1px 4px;
border-radius: 2px;
font-family: "SF Mono", Monaco, "Cascadia Code", monospace;
font-size: 0.9em;
}
.shpt-sidebar-body pre {
background: #2a2a2a;
padding: 8px;
border-radius: 3px;
overflow-x: auto;
margin: 0.3em 0;
}
.shpt-sidebar-body pre code {
background: none;
padding: 0;
}
.shpt-sidebar-error {
color: #ff6b6b;
background: rgba(255, 107, 107, 0.1);
padding: 8px;
border-radius: 3px;
border: 1px solid rgba(255, 107, 107, 0.3);
}
.shpt-loading {
display: flex;
align-items: center;
gap: 8px;
color: #999;
font-size: 12px;
}
.shpt-spinner {
width: 16px;
height: 16px;
border: 2px solid #333;
border-top-color: #999;
border-radius: 50%;
animation: shpt-spin 1s linear infinite;
}
@keyframes shpt-spin {
to { transform: rotate(360deg); }
}
.shpt-streaming-cursor {
display: inline-block;
width: 2px;
height: 1em;
background: #999;
margin-left: 2px;
animation: shpt-blink 0.8s infinite;
vertical-align: text-bottom;
}
@keyframes shpt-blink {
0%, 50% { opacity: 1; }
51%, 100% { opacity: 0; }
}
/* Paragraph fade-in animation - gentle and smooth */
.shpt-paragraph-new {
animation: shpt-fade-in 0.6s ease-out forwards;
}
/* Ensure heading margins work inside streamed blocks */
.shpt-paragraph-new > h1:first-child,
.shpt-paragraph-new > h2:first-child,
.shpt-paragraph-new > h3:first-child {
margin-top: 0;
}
.shpt-paragraph-new + .shpt-paragraph-new > h1:first-child,
.shpt-paragraph-new + .shpt-paragraph-new > h2:first-child,
.shpt-paragraph-new + .shpt-paragraph-new > h3:first-child {
margin-top: 1.4em;
}
@keyframes shpt-fade-in {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
/* Final block - no animation, just apply the final styling */
.shpt-paragraph-final {
opacity: 1;
color: inherit;
white-space: normal;
}
.shpt-paragraph-final > h1:first-child,
.shpt-paragraph-final > h2:first-child,
.shpt-paragraph-final > h3:first-child {
margin-top: 0;
}
/* Streaming partial text - subtle styling */
.shpt-streaming-partial {
color: #b0b0b0;
white-space: pre-wrap;
font-family: inherit;
}
/* Summary tabs */
.shpt-tabs {
display: flex;
gap: 0;
border-bottom: 1px solid #333;
padding: 0 10px;
flex-shrink: 0;
align-items: center;
}
.shpt-tab {
background: transparent;
border: none;
color: #888;
padding: 12px 16px;
font-size: 13px;
font-weight: 600;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
cursor: pointer;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
transition: all 0.15s ease;
}
.shpt-tab:hover {
color: #bbb;
}
.shpt-tab.shpt-tab-active {
color: #fff;
border-bottom-color: #4a9eff;
}
.shpt-tab:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.shpt-tabs-close {
margin-left: auto;
background: transparent;
border: none;
color: #666;
font-size: 18px;
cursor: pointer;
padding: 4px 8px;
line-height: 1;
}
.shpt-tabs-close:hover {
color: #fff;
}
/* Cost tracker */
.shpt-sidebar-footer {
padding: 8px 12px;
border-top: 1px solid #333;
font-size: 12px;
color: #888;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
flex-shrink: 0;
display: flex;
justify-content: space-between;
}
.shpt-cost-value {
color: #aaa;
}
`;
document.documentElement.appendChild(btnStyles);
// --- Helper to extract clean text from a shadow root (excluding styles/scripts) ---
function extractCleanTextFromShadow(shadowRoot) {
if (!shadowRoot) return '';
// We can't clone the shadow root directly, so we need to work with its children
// Clone each child node into a container
const container = document.createElement('div');
// Get all child nodes and clone them (not the shadowRoot itself)
for (const child of shadowRoot.childNodes) {
// Skip style, script, and link elements
if (child.nodeType === Node.ELEMENT_NODE) {
const tagName = child.tagName.toLowerCase();
if (tagName === 'style' || tagName === 'script' ||
(tagName === 'link' && child.rel === 'stylesheet')) {
continue;
}
}
container.appendChild(child.cloneNode(true));
}
// Also remove any nested style/script elements that were cloned
container.querySelectorAll('style, script, link[rel="stylesheet"]').forEach(el => el.remove());
// Convert to text while preserving line breaks
// Replace block elements with newlines for better formatting
const blockTags = ['div', 'p', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'tr'];
// Walk through and insert newlines before/after block elements
function getTextWithLineBreaks(node) {
let text = '';
for (const child of node.childNodes) {
if (child.nodeType === Node.TEXT_NODE) {
text += child.textContent;
} else if (child.nodeType === Node.ELEMENT_NODE) {
const tagName = child.tagName.toLowerCase();
// Add newline before block elements
if (blockTags.includes(tagName)) {
if (text && !text.endsWith('\n')) {
text += '\n';
}
}
// Handle links - include the URL
if (tagName === 'a' && child.href) {
const linkText = child.textContent.trim();
const href = child.href;
// If link text is different from URL, include both
if (linkText && linkText !== href && !linkText.startsWith('http')) {
text += `${linkText} (${href})`;
} else {
text += href;
}
} else {
// Recursively get text from children
text += getTextWithLineBreaks(child);
}
// Add newline after block elements
if (blockTags.includes(tagName) || tagName === 'br') {
if (!text.endsWith('\n')) {
text += '\n';
}
}
}
}
return text;
}
const text = getTextWithLineBreaks(container);
// Clean up excessive newlines (more than 2 in a row)
return text.replace(/\n{3,}/g, '\n\n').trim();
}
// --- Helper to extract HTML from a shadow root (excluding styles/scripts) ---
function extractCleanHtmlFromShadow(shadowRoot) {
if (!shadowRoot) return '';
const container = document.createElement('div');
for (const child of shadowRoot.childNodes) {
if (child.nodeType === Node.ELEMENT_NODE) {
const tagName = child.tagName.toLowerCase();
if (tagName === 'style' || tagName === 'script' ||
(tagName === 'link' && child.rel === 'stylesheet')) {
continue;
}
}
container.appendChild(child.cloneNode(true));
}
// Remove nested style/script elements
container.querySelectorAll('style, script, link[rel="stylesheet"]').forEach(el => el.remove());
return container.innerHTML;
}
// --- Email body extraction (returns both HTML and plain text) ---
function extractEmailBodyContent() {
// PRIORITY 1: Superhuman renders email content in Shadow DOM inside SandboxedRender elements
const sandboxedRenders = document.querySelectorAll('.SandboxedRender, [class*="SandboxedRender"]');
const shadowContents = [];
for (const sandbox of sandboxedRenders) {
if (sandbox.shadowRoot) {
const text = extractCleanTextFromShadow(sandbox.shadowRoot);
const html = extractCleanHtmlFromShadow(sandbox.shadowRoot);
if (text.length > 20) {
shadowContents.push({ shadowRoot: sandbox.shadowRoot, text, html });
}
}
const nestedShadows = sandbox.querySelectorAll('*');
for (const nested of nestedShadows) {
if (nested.shadowRoot) {
const text = extractCleanTextFromShadow(nested.shadowRoot);
const html = extractCleanHtmlFromShadow(nested.shadowRoot);
if (text.length > 20) {
shadowContents.push({ shadowRoot: nested.shadowRoot, text, html });
}
}
}
}
// Find the focused/expanded message's shadow content (prioritize isFocus)
const focusedPane = document.querySelector('.MessagePane-expanded.isFocus .SandboxedRender');
if (focusedPane && focusedPane.shadowRoot) {
const text = extractCleanTextFromShadow(focusedPane.shadowRoot);
const html = extractCleanHtmlFromShadow(focusedPane.shadowRoot);
if (text.length > 20) {
return { text, html };
}
}
// If we found shadow content, return the largest one (most complete email)
if (shadowContents.length > 0) {
shadowContents.sort((a, b) => b.text.length - a.text.length);
return { text: shadowContents[0].text, html: shadowContents[0].html };
}
// PRIORITY 2: Superhuman also uses sh-color classes for email content
const shColorContainers = document.querySelectorAll('.sh-color, [class*="sh-color"]');
if (shColorContainers.length > 0) {
let bestContainer = null;
let bestLength = 0;
for (const container of shColorContainers) {
const text = container.textContent.trim();
if (text.length < 20) continue;
if (bestContainer && bestContainer.contains(container)) continue;
let hasLargerParent = false;
for (const other of shColorContainers) {
if (other !== container && other.contains(container)) {
const otherText = other.textContent.trim();
if (Math.abs(otherText.length - text.length) < text.length * 0.1) {
hasLargerParent = true;
break;
}
}
}
if (hasLargerParent) continue;
if (text.length > bestLength) {
bestLength = text.length;
bestContainer = container;
}
}
if (bestContainer && bestLength > 20) {
return { text: bestContainer.textContent.trim(), html: bestContainer.innerHTML };
}
}
// PRIORITY 3: Try standard message body selectors
const selectors = [
'.MessageBody',
'[class*="MessageBody-"]',
'[class*="Message-body"]',
'.EmailBody',
'[class*="EmailBody-"]',
'[class*="Message-content"]',
'[class*="MessageContent"]',
'[class*="ThreadMessage-body"]',
'[class*="ThreadPane-message"]',
];
for (const selector of selectors) {
const el = document.querySelector(selector);
if (el && el.textContent.trim()) {
return { text: el.textContent.trim(), html: el.innerHTML };
}
}
// PRIORITY 4: Look for email content in HTML tables (common in formatted emails)
const tables = document.querySelectorAll('table tbody, table');
for (const table of tables) {
const text = table.textContent.trim();
if (text.length > 100 && !text.includes('SEND ANYWAY') && !text.includes('@mention')) {
return { text, html: table.outerHTML };
}
}
// PRIORITY 5: Try message containers, filtering out UI elements
const messageContainers = document.querySelectorAll(
'[class*="Message"]:not([class*="MessageInput"]):not([class*="MessageCompose"])'
);
for (const container of messageContainers) {
const text = container.textContent.trim();
if (text.length > 50 &&
!text.includes('@mention anyone') &&
!text.includes('This comment will be visible') &&
!text.includes('Hit') && !text.includes('to summarize')) {
return { text, html: container.innerHTML };
}
}
console.warn("Superhuman Power Tools: Could not find email body content");
return null;
}
// --- Email body text extraction (wrapper for backwards compatibility) ---
function extractEmailBodyText() {
const content = extractEmailBodyContent();
return content ? content.text : null;
}
// --- Copy handler with visual feedback (copies both HTML and plain text) ---
async function handleCopyClick(btn) {
const content = extractEmailBodyContent();
if (!content) {
btn.textContent = "No content";
setTimeout(() => {
btn.textContent = "Copy";
}, 2000);
return;
}
try {
// Create ClipboardItem with both HTML and plain text formats
// This mimics native Ctrl+C behavior where apps can paste formatted or plain text
const clipboardItem = new ClipboardItem({
'text/html': new Blob([content.html], { type: 'text/html' }),
'text/plain': new Blob([content.text], { type: 'text/plain' })
});
await navigator.clipboard.write([clipboardItem]);
btn.textContent = "Copied!";
btn.classList.add("shpt-copied");
setTimeout(() => {
btn.textContent = "Copy";
btn.classList.remove("shpt-copied");
}, 2000);
} catch (err) {
console.error("Superhuman Power Tools: Rich clipboard write failed, falling back to text", err);
// Fallback to plain text if ClipboardItem isn't supported
try {
await navigator.clipboard.writeText(content.text);
btn.textContent = "Copied!";
btn.classList.add("shpt-copied");
setTimeout(() => {
btn.textContent = "Copy";
btn.classList.remove("shpt-copied");
}, 2000);
} catch (fallbackErr) {
console.error("Superhuman Power Tools: Clipboard write failed", fallbackErr);
btn.textContent = "Failed";
setTimeout(() => {
btn.textContent = "Copy";
}, 2000);
}
}
}
// ============================================================================
// FEATURE 5: AI Email Summarization
// ============================================================================
// Tab configuration
const SUMMARY_TABS = [
{ id: "tldr", label: "TL;DR", promptType: "tldr" },
{ id: "full", label: "Key Takeaways", promptType: "full" }
];
// Track current state
let currentTab = "tldr";
let currentEmailContent = null;
let tabContents = {}; // Cache results per tab
let tabStreaming = {}; // Track which tabs are currently streaming
let tabPartialContent = {}; // Track partial content during streaming
let currentUsageStats = null;
let sidebarCollapsed = false; // Track if sidebar is collapsed vs closed
// --- Cache key generation (simple hash of email content) ---
function generateCacheKey(content) {
// Simple hash function for cache key
let hash = 0;
for (let i = 0; i < Math.min(content.length, 500); i++) {
const char = content.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return 'summary_' + hash.toString(36);
}
// --- Save summary to persistent storage ---
async function saveSummaryToStorage(content, summaries) {
try {
const cacheKey = generateCacheKey(content);
const cacheData = {
emailContent: content.substring(0, 200), // Store snippet for verification
tabContents: summaries,
timestamp: Date.now()
};
await chrome.storage.local.set({ [cacheKey]: cacheData });
} catch (e) {
console.error("Failed to save summary to storage:", e);
}
}
// --- Load summary from persistent storage ---
async function loadSummaryFromStorage(content) {
try {
const cacheKey = generateCacheKey(content);
const result = await chrome.storage.local.get(cacheKey);
const cached = result[cacheKey];
if (cached && cached.tabContents) {
// Check if cache is less than 1 hour old
const oneHour = 60 * 60 * 1000;
if (Date.now() - cached.timestamp < oneHour) {
return cached.tabContents;
}
}
return null;
} catch (e) {
console.error("Failed to load summary from storage:", e);
return null;
}
}
// --- Copy markdown button handler ---
async function handleCopyMarkdown(btn) {
const markdown = tabContents[currentTab];
if (!markdown) {
return;
}
try {
await navigator.clipboard.writeText(markdown);
btn.classList.add("shpt-copied");
btn.innerHTML = "✓"; // Checkmark
setTimeout(() => {
btn.classList.remove("shpt-copied");
btn.innerHTML = "📋"; // Clipboard icon
}, 1500);
} catch (err) {
console.error("Failed to copy markdown:", err);
}
}
// --- Sidebar management ---
function showSummarySidebar(content, isError = false) {
// Remove existing sidebar if any
closeSummarySidebar();
const sidebar = document.createElement("div");
sidebar.className = "shpt-sidebar";
// Create tabs with close button
const tabs = document.createElement("div");
tabs.className = "shpt-tabs";
for (const tab of SUMMARY_TABS) {
const tabBtn = document.createElement("button");
tabBtn.className = "shpt-tab" + (tab.id === currentTab ? " shpt-tab-active" : "");
tabBtn.textContent = tab.label;
tabBtn.dataset.tabId = tab.id;
tabBtn.addEventListener("click", () => handleTabClick(tab.id));
tabs.appendChild(tabBtn);
}
// Close button in tabs row
const closeBtn = document.createElement("button");
closeBtn.className = "shpt-tabs-close";
closeBtn.innerHTML = "×";
closeBtn.title = "Close";
closeBtn.addEventListener("click", closeSummarySidebar);
tabs.appendChild(closeBtn);
const body = document.createElement("div");
body.className = "shpt-sidebar-body";
if (isError) {
body.innerHTML = `<div class="shpt-sidebar-error">${escapeHtml(content)}</div>`;
} else {
body.innerHTML = renderMarkdown(content);
}
// Footer with cost tracking
const footer = document.createElement("div");
footer.className = "shpt-sidebar-footer";
footer.innerHTML = `<span>This call: <span class="shpt-cost-value" data-cost-this>-</span></span><span>Total: <span class="shpt-cost-value" data-cost-total>-</span></span>`;
sidebar.appendChild(tabs);
sidebar.appendChild(body);
sidebar.appendChild(footer);
document.body.appendChild(sidebar);