-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
3151 lines (2803 loc) · 125 KB
/
Copy pathcontent.js
File metadata and controls
3151 lines (2803 loc) · 125 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
(function () {
"use strict";
/* ================================================================
* InboxSort - Content Script (v1.3.2)
* Made by Alex Brecher
* Sorts Gmail inbox visually using CSS transforms.
* Features: 6 sort modes, group-by-sender toggle, stats bar, filters,
* keyboard shortcuts, snooze, per-label prefs, auto-sort toggle.
* ================================================================ */
// ── SVG icon library ──────────────────────────────────────────────
const ICONS = {
oldest:
'<svg viewBox="0 0 16 16" width="14" height="14" fill="none">' +
'<path d="M8 13V3m-3.5 3.5L8 3l3.5 3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
newest:
'<svg viewBox="0 0 16 16" width="14" height="14" fill="none">' +
'<path d="M8 3v10m-3.5-3.5L8 13l3.5-3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
senderAZ:
'<svg viewBox="0 0 16 16" width="14" height="14" fill="none">' +
'<path d="M2 4h4M2 8h7M2 12h10" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>',
senderZA:
'<svg viewBox="0 0 16 16" width="14" height="14" fill="none">' +
'<path d="M2 4h10M2 8h7M2 12h4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>',
unreadFirst:
'<svg viewBox="0 0 16 16" width="14" height="14" fill="none">' +
'<rect x="2" y="4" width="12" height="8" rx="1.5" stroke="currentColor" stroke-width="1.3"/>' +
'<path d="M2 5l6 4 6-4" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/>' +
'<circle cx="12.5" cy="4" r="2" fill="currentColor"/></svg>',
groupSender:
'<svg viewBox="0 0 16 16" width="14" height="14" fill="none">' +
'<path d="M1 3h14M1 6.5h10M1 10h14M1 13.5h10" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/>' +
'<circle cx="13.5" cy="6.5" r="1.2" fill="currentColor"/>' +
'<circle cx="13.5" cy="13.5" r="1.2" fill="currentColor"/></svg>',
starred:
'<svg viewBox="0 0 16 16" width="13" height="13" fill="none">' +
'<path d="M8 1.5l1.76 3.57 3.94.57-2.85 2.78.67 3.93L8 10.67l-3.52 1.68.67-3.93L2.3 5.64l3.94-.57L8 1.5z" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/></svg>',
attachment:
'<svg viewBox="0 0 16 16" width="13" height="13" fill="none">' +
'<path d="M13.5 7.25l-5.75 5.75a3.18 3.18 0 01-4.5-4.5L9.5 2.25a2.12 2.12 0 013 3L6.25 11.5a1.06 1.06 0 01-1.5-1.5L10.5 4.25" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>',
search:
'<svg viewBox="0 0 16 16" width="14" height="14" fill="none">' +
'<circle cx="6.5" cy="6.5" r="4" stroke="currentColor" stroke-width="1.4"/>' +
'<path d="M10 10l4 4" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>',
close:
'<svg viewBox="0 0 16 16" width="12" height="12" fill="none">' +
'<path d="M4.5 4.5l7 7M11.5 4.5l-7 7" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>',
keyboard:
'<svg viewBox="0 0 16 16" width="14" height="14" fill="none">' +
'<rect x="1" y="4" width="14" height="8" rx="1.5" stroke="currentColor" stroke-width="1.2"/>' +
'<path d="M4 6.5h1M7 6.5h2M11 6.5h1M5 9h6" stroke="currentColor" stroke-width="1" stroke-linecap="round"/></svg>',
selectAll:
'<svg viewBox="0 0 14 14" width="11" height="11" fill="none">' +
'<rect x="1.5" y="1.5" width="11" height="11" rx="2" stroke="currentColor" stroke-width="1.3"/>' +
'<path d="M4 7l2 2 4-4" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>'
};
// ── Sort-mode definitions ─────────────────────────────────────────
const SORT_MODES = [
{ id: "oldest", label: "Sorted oldest first", tabLabel: "Oldest", icon: "oldest", group: "date" },
{ id: "newest", label: "Default order", tabLabel: "Newest", icon: "newest", group: "date" },
{ id: "senderAZ", label: "Sorted sender A\u2192Z", tabLabel: "A\u2192Z", icon: "senderAZ", group: "sender" },
{ id: "senderZA", label: "Sorted sender Z\u2192A", tabLabel: "Z\u2192A", icon: "senderZA", group: "sender" },
{ id: "unreadFirst", label: "Unread first", tabLabel: "Unread", icon: "unreadFirst" },
{ id: "starredFirst", label: "Starred first, then newest", tabLabel: "Starred", icon: "starred" }
];
function isKnownSortMode(mode) {
for (let i = 0; i < SORT_MODES.length; i++) {
if (SORT_MODES[i].id === mode) return true;
}
return false;
}
function normalizeSortMode(mode) {
return isKnownSortMode(mode) ? mode : "newest";
}
function normalizeHiddenTabs(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
let normalized = {};
let allowed = ["date", "sender", "unread", "starred", "groupSender"];
for (let i = 0; i < allowed.length; i++) {
if (value[allowed[i]] === true) normalized[allowed[i]] = true;
}
// Migrate the pre-1.3 per-mode preferences to the merged toolbar controls.
if (value.oldest === true && value.newest === true) normalized.date = true;
if (value.senderAZ === true && value.senderZA === true) normalized.sender = true;
if (value.unreadFirst === true) normalized.unread = true;
if (value.starredFirst === true) normalized.starred = true;
return normalized;
}
// Tab groups: merge related sort modes into single toggle buttons.
// "newest" (default Gmail order) is NOT in any group — it's the inactive state.
// Click cycle: inactive → mode[0] → mode[1] → … → inactive (newest).
// NOTE: Group is a separate toggle (not a sort mode). See groupEnabled state.
const TAB_GROUPS = [
{ id: "date", modes: ["oldest"], defaultLabel: "Date", defaultIcon: "newest" },
{ id: "sender", modes: ["senderAZ", "senderZA"], defaultLabel: "Sender", defaultIcon: "senderAZ" },
{ id: "unread", modes: ["unreadFirst"], defaultLabel: "Unread", defaultIcon: "unreadFirst" },
{ id: "starred", modes: ["starredFirst"], defaultLabel: "Starred", defaultIcon: "starred" }
];
// ── Accent colour palette ──────────────────────────────────────────
const ACCENT_COLORS = {
blue: { primary: "#1a73e8", hover: "#1765cc", ink: "#174ea6", light: "#d2e3fc" },
green: { primary: "#1e8e3e", hover: "#188038", ink: "#137333", light: "#ceead6" },
purple: { primary: "#8430ce", hover: "#7627bb", ink: "#5c16a5", light: "#e8d0fe" },
red: { primary: "#c5221f", hover: "#b31412", ink: "#a50e0e", light: "#f4c7c3" },
orange: { primary: "#b85d00", hover: "#a65300", ink: "#8d4900", light: "#fde293" },
teal: { primary: "#007b83", hover: "#006d75", ink: "#005f66", light: "#b2ebf2" }
};
// Dark mode accent variants — softer, higher-contrast colors for dark backgrounds
const DARK_ACCENT_COLORS = {
blue: { primary: "#8ab4f8", hover: "#aecbfa", light: "rgba(138,180,248,0.18)" },
green: { primary: "#81c995", hover: "#a8dab5", light: "rgba(129,201,149,0.18)" },
purple: { primary: "#c58af9", hover: "#d7aefb", light: "rgba(197,138,249,0.18)" },
red: { primary: "#f28b82", hover: "#f6aea9", light: "rgba(242,139,130,0.18)" },
orange: { primary: "#fdd663", hover: "#fde293", light: "rgba(253,214,99,0.18)" },
teal: { primary: "#4ecdc4", hover: "#73d8d0", light: "rgba(78,205,196,0.18)" }
};
// ── Timing & threshold constants ────────────────────────────────
// Centralises all magic numbers for easy tuning and documentation.
const CONFIG = {
// Row cache time-to-live (ms) — how long getVisibleEmailRows() reuses cached results
ROW_CACHE_TTL: 500,
// Row metadata cache TTL (ms) — volatile values are refreshed in stats/filter paths
ROW_META_TTL: 3000,
// Persist state writes are debounced to avoid sync-storage quota spikes
SAVE_STATE_DEBOUNCE: 200,
SAVE_STATE_RETRY_BASE: 1000,
SAVE_STATE_RETRY_MAX: 10000,
// Sort animation
SORT_TRANSITION_DURATION: "0.3s", // CSS transition duration for row transforms
SORT_DELAY_INCREMENT: 6, // ms added per-row for stagger effect
SORT_DELAY_MAX: 300, // cap on per-row stagger delay (ms)
// Group-by-sender style-reapply interval (Gmail aggressively wipes inline styles)
GROUP_FAST_INTERVAL: 400, // aggressive re-check interval (ms) for first 10s
GROUP_SLOW_INTERVAL: 2000, // maintenance interval (ms) after fast phase
GROUP_FAST_TICKS: 25, // ticks in fast phase (25 × 400ms = 10s)
GROUP_MAX_TICKS: 85, // total ticks before auto-stop (≈2 min)
// Pagination poll — waits for Gmail to load the next page of results
PAGINATION_TIMEOUT: 10000, // give up after 10s
PAGINATION_POLL: 200, // poll interval (ms) while waiting for new page
PAGE_SETTLE_DELAY: 800, // ms to wait after page change before re-sorting
// Navigation guard — prevents sort from firing during programmatic hash changes
NAVIGATION_TIMEOUT: 2000,
// Snooze (pause sorting temporarily)
SNOOZE_TICK_INTERVAL: 30000, // badge countdown refresh interval (ms)
// Toast notification
TOAST_DISPLAY: 2000, // how long the toast stays visible (ms)
TOAST_FADE: 250, // fade-out animation duration (ms)
// Auto-sort on page load — polls for rows then applies stored sort
AUTO_SORT_MAX_ATTEMPTS: 40, // max poll iterations before giving up
AUTO_SORT_POLL: 100, // interval between polls (ms)
// Stats bar throttle — avoids excessive DOM updates
STATS_THROTTLE: 1500,
// MutationObserver debounce — batches rapid DOM changes into one handler call
OBSERVER_DEBOUNCE: 250,
// Gmail can replace div[role="main"] without mutating the old node. A cheap
// watchdog reconnects the observer and restores the toolbar when that happens.
OBSERVER_WATCHDOG: 1500,
// Search input debounce — waits for typing to pause before filtering
SEARCH_DEBOUNCE: 150,
// Initialisation — waits for Gmail's main content area to appear
INIT_POLL: 500, // interval to check for div[role="main"]
INIT_TIMEOUT: 30000, // failsafe: stop waiting after 30s
// Cheat-sheet overlay fade duration (ms)
CHEATSHEET_FADE: 200,
// Thread-ID heuristic: strings ≥ this length that are alphanumeric+dash+underscore
// are treated as Gmail thread IDs (triggers single-message view detection)
THREAD_ID_MIN_LENGTH: 15
};
// ── Runtime state ─────────────────────────────────────────────────
// Grouped logically for readability. All state lives inside this IIFE.
// Sort & group mode
let currentSort = "newest";
let groupEnabled = false; // Group-by-sender overlay (combinable with any sort)
let originalPage = null; // Hash to return to after "oldest" pagination
// UI elements & appearance
let container = null; // Toolbar DOM element
let statsBar = null; // Stats bar DOM element
let cheatsheetEl = null; // Keyboard shortcut overlay
let _cheatsheetReturnFocus = null;
let accentColor = "blue";
let isDarkMode = false;
let hiddenTabs = {};
// Filters
let searchQuery = "";
let filterStarred = false;
let filterAttachment = false;
let filterUnread = false;
// Settings (loaded from chrome.storage)
let autoSortEnabled = true;
let perLabelEnabled = false;
// Navigation & auto-sort
let isNavigating = false;
let hasAutoSorted = false;
let _autoSortPending = false; // Mutex: prevents duplicate autoSortWhenReady calls
// Snooze (pause sorting)
let snoozeTimer = null;
let snoozedSort = null;
let snoozedGroup = false;
let snoozeEndTime = 0;
let snoozeTickTimer = null;
// Cache & perf
let lastStatsUpdate = 0;
let _lastStatsKey = "";
let _currentGroupData = null; // Saved group data for interval re-apply
// Timer & interval references (cleaned up on page unload)
let autoSortInterval = null;
let _groupStyleInterval = null; // Persistent group style re-apply
let _observer = null; // MutationObserver instance
let _observerRoot = null; // Current Gmail main node observed for changes
let _observerWatchdog = null; // Reconnects after Gmail replaces the main node
let _observerDebounce = null; // Observer debounce timer
let _initWaitInterval = null; // init() polling interval
let _initSafetyTimeout = null; // init() 30s failsafe timeout
let _waitForNewPage = null; // Pagination poll interval
let _suppressObserver = false; // Prevent observer self-triggers during our own DOM writes
let _lastSortedRowCount = 0; // Row count at last sort — triggers re-sort when rows change
let _lastSortedRowElements = null; // First few row elements for identity-change detection
let _lastRowChangeSort = 0; // Timestamp of last row-change re-sort (throttle)
let _searchDebounce = null; // Search input debounce timer
let _hiddenTabsRetryTimers = []; // Delayed storage re-sync timers for hidden tabs
let _saveStateTimer = null; // Debounced storage write timer
let _saveStatePending = false; // Coalesces rapid save requests
let _saveStateInFlight = false; // Single in-flight sync write guard
let _saveStateRetryDelay = CONFIG.SAVE_STATE_RETRY_BASE;
let _sortInProgress = false; // Reentrancy guard for applySortTransforms
let _resizeDebounce = null; // Debounce timer for viewport resize re-sort
let _lastResizeWidth = 0; // Track viewport width to ignore height-only resizes
let _initialized = false; // Prevent duplicate timers and observers
// ── Current Gmail label ─────────────────────────────────────────
function getCurrentLabel() {
let hash = location.hash;
if (!hash || hash === "#" || hash === "#inbox" || /^#inbox\/p\d+$/.test(hash)) return "inbox";
let cleaned = hash.replace(/^#/, "").replace(/\/p\d+$/, "");
if (!cleaned) return "inbox";
// In thread view hashes (e.g. inbox/<threadId>), normalize to the list label
// so per-label prefs don't get stored under transient thread IDs.
let parts = cleaned.split("/");
let lastPart = parts[parts.length - 1];
let threadLikeTail = !!(lastPart &&
lastPart.length >= CONFIG.THREAD_ID_MIN_LENGTH &&
/^[A-Za-z0-9_-]+$/.test(lastPart));
// Two-segment hashes are often list labels (e.g. label/Work). Only treat
// the last segment as a thread id when the path shape can actually contain
// a thread tail for that root.
let singleRootThreadLabels = {
inbox: true, all: true, sent: true, starred: true, important: true,
drafts: true, snoozed: true, spam: true, trash: true, scheduled: true,
chats: true
};
let canHaveThreadTail =
(parts.length >= 3) ||
(parts.length >= 2 && !!singleRootThreadLabels[parts[0]]);
if (threadLikeTail && canHaveThreadTail) {
parts.pop();
}
let normalized = parts.join("/");
return normalized || "inbox";
}
// Labels where the toolbar is hidden — these folders contain too many
// emails for client-side sorting to work well.
let EXCLUDED_LABELS = { "sent": true, "all": true };
function isExcludedLabel() {
let label = getCurrentLabel();
return !!EXCLUDED_LABELS[label];
}
// ── Extension context validity ───────────────────────────────────
let _contextInvalid = false;
function isExtensionContextValid() {
if (_contextInvalid) return false;
try {
// chrome.runtime.id is undefined when the extension has been
// reloaded / uninstalled while this content-script is still alive.
void chrome.runtime.id;
return true;
} catch (e) {
return false;
}
}
function isContextInvalidatedError(err) {
let msg = "";
try {
msg = String((err && err.message) || err || "");
} catch (_) {
msg = "";
}
return /extension context invalidated/i.test(msg);
}
function hasRuntimeLastError() {
try {
return !!(chrome.runtime && chrome.runtime.lastError);
} catch (_) {
return true;
}
}
function getRuntimeLastErrorMessage() {
try {
if (!chrome.runtime || !chrome.runtime.lastError) return "";
return String(chrome.runtime.lastError.message || chrome.runtime.lastError || "");
} catch (_) {
return "";
}
}
function isStorageQuotaError(msg) {
return /quota|max_write_operations|write operations/i.test(String(msg || ""));
}
function clearAccentColorVars() {
let root = document.documentElement && document.documentElement.style;
if (!root) return;
root.removeProperty("--sort-accent");
root.removeProperty("--sort-accent-hover");
root.removeProperty("--sort-accent-light");
root.removeProperty("--sort-accent-ink");
document.documentElement.classList.remove("gmail-sort-dark-mode");
}
/** Call when we detect the extension context is dead. Tears down the
* observer and removes UI so stale scripts don't keep running. */
function handleContextInvalidated() {
if (_contextInvalid) return; // already handled
_contextInvalid = true;
// Expected during extension reload/uninstall; keep this low-noise.
if (typeof console !== "undefined" && typeof console.debug === "function") {
console.debug("[InboxSort] Extension context invalidated — cleaning up.");
}
// Stop timers/intervals to avoid stale loops after extension reload/uninstall.
if (autoSortInterval) { clearInterval(autoSortInterval); autoSortInterval = null; }
if (_groupStyleInterval) { clearInterval(_groupStyleInterval); _groupStyleInterval = null; }
if (_observerDebounce) { clearTimeout(_observerDebounce); _observerDebounce = null; }
if (_observerWatchdog) { clearInterval(_observerWatchdog); _observerWatchdog = null; }
if (_searchDebounce) { clearTimeout(_searchDebounce); _searchDebounce = null; }
if (snoozeTimer) { clearTimeout(snoozeTimer); snoozeTimer = null; }
if (snoozeTickTimer) { clearInterval(snoozeTickTimer); snoozeTickTimer = null; }
if (_initWaitInterval) { clearInterval(_initWaitInterval); _initWaitInterval = null; }
if (_initSafetyTimeout) { clearTimeout(_initSafetyTimeout); _initSafetyTimeout = null; }
if (_waitForNewPage) { clearInterval(_waitForNewPage); _waitForNewPage = null; }
if (_saveStateTimer) { clearTimeout(_saveStateTimer); _saveStateTimer = null; }
_saveStatePending = false;
_saveStateInFlight = false;
_saveStateRetryDelay = CONFIG.SAVE_STATE_RETRY_BASE;
if (_hiddenTabsRetryTimers.length) {
for (let ti = 0; ti < _hiddenTabsRetryTimers.length; ti++) {
clearTimeout(_hiddenTabsRetryTimers[ti]);
}
_hiddenTabsRetryTimers = [];
}
stopGroupStyleInterval();
if (_observer) { _observer.disconnect(); _observer = null; }
_observerRoot = null;
document.removeEventListener("click", onDocumentClick, true);
document.removeEventListener("mousedown", onDocumentMousedown, true);
document.removeEventListener("input", onDocumentInput, false);
document.removeEventListener("keydown", onDocumentKeydown, true);
// Remove UI elements so users don't see a broken toolbar
let old = document.querySelectorAll(".gmail-sort-container");
for (let i = 0; i < old.length; i++) old[i].remove();
let oldStats = document.querySelectorAll(".gmail-sort-stats");
for (let i = 0; i < oldStats.length; i++) oldStats[i].remove();
container = null;
statsBar = null;
clearAccentColorVars();
}
// ── Persistence (chrome.storage.sync — syncs across devices) ─────
function scheduleSaveState(delay) {
if (_contextInvalid) return;
if (_saveStateTimer) clearTimeout(_saveStateTimer);
_saveStateTimer = setTimeout(flushSaveState, Math.max(0, delay || 0));
}
function finishSaveState(retry) {
_saveStateInFlight = false;
if (_contextInvalid) return;
if (retry) {
_saveStatePending = true;
scheduleSaveState(_saveStateRetryDelay);
_saveStateRetryDelay = Math.min(CONFIG.SAVE_STATE_RETRY_MAX, _saveStateRetryDelay * 2);
return;
}
_saveStateRetryDelay = CONFIG.SAVE_STATE_RETRY_BASE;
if (_saveStatePending) {
scheduleSaveState(CONFIG.SAVE_STATE_DEBOUNCE);
}
}
function persistStateSnapshot(data) {
try {
chrome.storage.sync.set(data, function () {
if (!isExtensionContextValid()) {
handleContextInvalidated();
return;
}
if (hasRuntimeLastError()) {
let errMsg = getRuntimeLastErrorMessage();
if (isContextInvalidatedError(errMsg)) {
handleContextInvalidated();
return;
}
if (isStorageQuotaError(errMsg)) {
finishSaveState(true);
return;
}
console.warn("[InboxSort] saveState set runtime error:", errMsg);
}
finishSaveState(false);
});
} catch (setErr) {
if (isContextInvalidatedError(setErr) || !isExtensionContextValid()) {
handleContextInvalidated();
return;
}
if (isStorageQuotaError(String(setErr && setErr.message || setErr || ""))) {
finishSaveState(true);
return;
}
console.warn("[InboxSort] saveState set error:", setErr);
finishSaveState(false);
}
}
function flushSaveState() {
_saveStateTimer = null;
if (!isExtensionContextValid()) { handleContextInvalidated(); return; }
if (_saveStateInFlight) {
_saveStatePending = true;
return;
}
if (!_saveStatePending) return;
_saveStatePending = false;
_saveStateInFlight = true;
// While paused, currentSort and groupEnabled intentionally hold Gmail's
// default visual state. Persist the state that must return after resume.
let persistedSort = isSnoozedActive() ? (snoozedSort || "newest") : currentSort;
let persistedGroup = isSnoozedActive() ? !!snoozedGroup : groupEnabled;
let data = { accentColor: accentColor, sortMode: persistedSort, groupEnabled: persistedGroup };
if (perLabelEnabled) {
// Per-label prefs need a read-modify-write pass.
try {
chrome.storage.sync.get({ labelPrefs: {} }, function (stored) {
if (!isExtensionContextValid()) {
handleContextInvalidated();
return;
}
if (hasRuntimeLastError()) {
let errMsg = getRuntimeLastErrorMessage();
if (isContextInvalidatedError(errMsg)) {
handleContextInvalidated();
return;
}
if (isStorageQuotaError(errMsg)) {
finishSaveState(true);
return;
}
console.warn("[InboxSort] saveState get runtime error:", errMsg);
finishSaveState(false);
return;
}
let prefs = stored && stored.labelPrefs && typeof stored.labelPrefs === "object" ? stored.labelPrefs : {};
prefs[getCurrentLabel()] = persistedSort;
data.labelPrefs = prefs;
persistStateSnapshot(data);
});
} catch (getErr) {
if (isContextInvalidatedError(getErr) || !isExtensionContextValid()) {
handleContextInvalidated();
return;
}
if (isStorageQuotaError(String(getErr && getErr.message || getErr || ""))) {
finishSaveState(true);
return;
}
console.warn("[InboxSort] saveState get error:", getErr);
finishSaveState(false);
}
return;
}
// Global: save sortMode + accentColor + groupEnabled
persistStateSnapshot(data);
}
function saveState() {
if (!isExtensionContextValid()) { handleContextInvalidated(); return; }
_saveStatePending = true;
scheduleSaveState(CONFIG.SAVE_STATE_DEBOUNCE);
}
function persistSnoozeState(value) {
if (!isExtensionContextValid() || !chrome.storage || !chrome.storage.local) return;
try {
chrome.storage.local.set({ snoozeState: value || null }, function () {
if (!isExtensionContextValid()) handleContextInvalidated();
});
} catch (e) {
if (isContextInvalidatedError(e)) handleContextInvalidated();
}
}
function restorePersistedSnooze(callback) {
if (!chrome.storage || !chrome.storage.local) {
callback();
return;
}
try {
chrome.storage.local.get({ snoozeState: null }, function (localData) {
if (hasRuntimeLastError() || !isExtensionContextValid()) {
if (!isExtensionContextValid()) handleContextInvalidated();
callback();
return;
}
let state = localData && localData.snoozeState;
let endTime = state && Number(state.endTime);
if (!state || !isFinite(endTime) || endTime <= Date.now()) {
if (state) persistSnoozeState(null);
callback();
return;
}
snoozedSort = normalizeSortMode(state.sortMode || currentSort);
snoozedGroup = !!state.groupEnabled;
snoozeEndTime = endTime;
currentSort = "newest";
groupEnabled = false;
startSnoozeTimers(endTime - Date.now());
callback();
});
} catch (e) {
if (isContextInvalidatedError(e)) handleContextInvalidated();
callback();
}
}
function loadState(callback) {
if (!isExtensionContextValid()) { handleContextInvalidated(); callback(); return; }
try {
chrome.storage.sync.get({
sortMode: "newest",
groupEnabled: false,
accentColor: "blue",
autoSort: true,
perLabel: false,
labelPrefs: {},
hiddenTabs: {}
}, function (data) {
if (hasRuntimeLastError() || !isExtensionContextValid()) {
handleContextInvalidated();
callback();
return;
}
accentColor = data.accentColor || "blue";
autoSortEnabled = data.autoSort !== false;
perLabelEnabled = !!data.perLabel;
hiddenTabs = normalizeHiddenTabs(data.hiddenTabs);
groupEnabled = !!data.groupEnabled;
let loadedSort = "newest";
if (perLabelEnabled && data.labelPrefs && data.labelPrefs[getCurrentLabel()]) {
loadedSort = data.labelPrefs[getCurrentLabel()];
} else {
loadedSort = data.sortMode || "newest";
}
// Migrate old groupSender sort mode to new group toggle
if (loadedSort === "groupSender") {
loadedSort = "newest";
groupEnabled = true;
}
currentSort = normalizeSortMode(loadedSort);
restorePersistedSnooze(callback);
});
} catch (e) {
if (isContextInvalidatedError(e) || !isExtensionContextValid()) {
handleContextInvalidated();
} else {
console.warn("[InboxSort] loadState error:", e);
}
callback();
}
}
chrome.storage.onChanged.addListener(function (changes, areaName) {
if (_contextInvalid) return;
// Pause state is stored locally, so mirror it across every open Gmail tab.
// The tab that originated the change already has matching state and exits
// through the equality guards below.
if (areaName === "local") {
if (!changes.snoozeState) return;
let nextSnooze = changes.snoozeState.newValue;
let nextEnd = nextSnooze && Number(nextSnooze.endTime);
if (nextSnooze && isFinite(nextEnd) && nextEnd > Date.now()) {
if (snoozeEndTime === nextEnd && snoozedSort !== null) return;
snoozedSort = normalizeSortMode(nextSnooze.sortMode || currentSort);
snoozedGroup = !!nextSnooze.groupEnabled;
snoozeEndTime = nextEnd;
clearSortTransforms();
currentSort = "newest";
groupEnabled = false;
startSnoozeTimers(nextEnd - Date.now());
refreshUI();
updateStats();
return;
}
if (snoozedSort !== null || snoozedGroup || snoozeEndTime || snoozeTimer || snoozeTickTimer) {
let restoreSort = snoozedSort || "newest";
let restoreGroup = !!snoozedGroup;
if (snoozeTimer) { clearTimeout(snoozeTimer); snoozeTimer = null; }
if (snoozeTickTimer) { clearInterval(snoozeTickTimer); snoozeTickTimer = null; }
snoozedSort = null;
snoozedGroup = false;
snoozeEndTime = 0;
groupEnabled = restoreGroup;
applySort(restoreSort, true);
}
return;
}
if (areaName !== "sync") return;
let sortStateChanged = false;
if (changes.accentColor) {
accentColor = changes.accentColor.newValue;
applyAccentColor();
}
if (changes.autoSort) {
autoSortEnabled = changes.autoSort.newValue !== false;
}
if (changes.perLabel) {
perLabelEnabled = !!changes.perLabel.newValue;
}
if (changes.hiddenTabs) {
hiddenTabs = normalizeHiddenTabs(changes.hiddenTabs.newValue);
applyHiddenTabs();
}
// Sync sort and grouping changes across open Gmail tabs. The originating
// tab already holds these values, so the equality checks prevent loops.
if (changes.groupEnabled && typeof changes.groupEnabled.newValue === "boolean" && isSnoozedActive()) {
snoozedGroup = changes.groupEnabled.newValue;
} else if (changes.groupEnabled && typeof changes.groupEnabled.newValue === "boolean") {
let nextGroup = changes.groupEnabled.newValue;
if (nextGroup !== groupEnabled) {
groupEnabled = nextGroup;
sortStateChanged = true;
}
}
if (!perLabelEnabled && changes.sortMode && isSnoozedActive()) {
snoozedSort = normalizeSortMode(changes.sortMode.newValue);
} else if (!perLabelEnabled && changes.sortMode) {
let nextSort = normalizeSortMode(changes.sortMode.newValue);
if (nextSort !== currentSort) {
currentSort = nextSort;
sortStateChanged = true;
}
} else if (perLabelEnabled && changes.labelPrefs) {
let nextPrefs = changes.labelPrefs.newValue;
let labelMode = nextPrefs && nextPrefs[getCurrentLabel()];
if (labelMode && isSnoozedActive()) {
snoozedSort = normalizeSortMode(labelMode);
} else if (labelMode) {
let nextLabelSort = normalizeSortMode(labelMode);
if (nextLabelSort !== currentSort) {
currentSort = nextLabelSort;
sortStateChanged = true;
}
}
}
if (changes.perLabel) {
loadState(function () {
if (container && isListView() && !isExcludedLabel() && !isSnoozedActive()) {
applySort(currentSort, true);
} else {
refreshUI();
}
});
} else if (sortStateChanged && container && isListView() && !isExcludedLabel() && !isSnoozedActive()) {
applySort(currentSort, true);
}
});
function refreshHiddenTabsFromStorage(callback) {
if (!isExtensionContextValid()) {
handleContextInvalidated();
if (callback) callback();
return;
}
try {
chrome.storage.sync.get({ hiddenTabs: {} }, function (data) {
if (hasRuntimeLastError() || !isExtensionContextValid()) {
handleContextInvalidated();
if (callback) callback();
return;
}
hiddenTabs = normalizeHiddenTabs(data.hiddenTabs);
if (callback) callback();
});
} catch (e) {
if (isContextInvalidatedError(e) || !isExtensionContextValid()) {
handleContextInvalidated();
} else {
console.warn("[InboxSort] refreshHiddenTabsFromStorage error:", e);
}
if (callback) callback();
}
}
// ── Dark-mode detection ───────────────────────────────────────────
let _darkModeDetectedAt = 0;
function detectDarkMode() {
// PERF: Cache detection result for 2s to avoid forced style recalc on every call
let now = Date.now();
if (_darkModeDetectedAt && (now - _darkModeDetectedAt) < 2000) return;
_darkModeDetectedAt = now;
let detected = false;
// Strategy 1: Check body background color (catches some dark themes / system dark mode)
let bg = window.getComputedStyle(document.body).backgroundColor;
if (bg) {
let match = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if (match) {
detected = ((parseInt(match[1]) + parseInt(match[2]) + parseInt(match[3])) / 3) < 100;
}
}
// Strategy 2: Gmail dark themes keep body bg light but flip text to white.
// Check sender / subject text color — if average RGB > 180, text is light → dark mode.
if (!detected) {
let textEl = document.querySelector(".zF, .yP, .bog, .bqe");
if (textEl) {
let tc = window.getComputedStyle(textEl).color;
let m = tc && tc.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
if (m) {
detected = ((parseInt(m[1]) + parseInt(m[2]) + parseInt(m[3])) / 3) > 180;
}
}
}
// Strategy 3: Fall back to prefers-color-scheme media query
if (!detected && !document.querySelector(".zF, .yP, .bog, .bqe")) {
detected = !!(window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches);
}
isDarkMode = detected;
// Propagate dark mode class to <html> so group-by-sender rows (which are
// NOT descendants of .gmail-sort-dark container) can be styled properly.
document.documentElement.classList.toggle("gmail-sort-dark-mode", isDarkMode);
}
// Re-detect dark mode on system theme change
if (window.matchMedia) {
try {
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", function () {
detectDarkMode();
if (container) container.classList.toggle("gmail-sort-dark", isDarkMode);
if (statsBar) statsBar.classList.toggle("gmail-sort-dark", isDarkMode);
applyAccentColor();
// Re-apply group styles with correct dark/light colors
if (groupEnabled && _currentGroupData) {
clearGroupInlineStyles();
applyGroupVisuals(_currentGroupData.sortedRows, {
ac: isDarkMode
? (DARK_ACCENT_COLORS[accentColor] || DARK_ACCENT_COLORS.blue)
: (ACCENT_COLORS[accentColor] || ACCENT_COLORS.blue),
perRow: _currentGroupData.perRow
});
}
});
} catch (_) { /* older browsers */ }
}
// ── Accent colour application ─────────────────────────────────────
function applyAccentColor() {
let c = ACCENT_COLORS[accentColor] || ACCENT_COLORS.blue;
let dc = DARK_ACCENT_COLORS[accentColor] || DARK_ACCENT_COLORS.blue;
let use = isDarkMode ? dc : c;
let root = document.documentElement.style;
root.setProperty("--sort-accent", use.primary);
root.setProperty("--sort-accent-hover", use.hover);
root.setProperty("--sort-accent-light", use.light || c.light);
root.setProperty("--sort-accent-ink", isDarkMode ? use.primary : c.ink);
}
// ── Date parsing ──────────────────────────────────────────────────
function parseGmailDate(text) {
if (!text) return null;
let cleaned = text.replace(/\u200e/g, "").trim();
let d = new Date(cleaned);
if (!isNaN(d.getTime())) return d;
let monthDay = cleaned.match(/^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(\d{1,2})$/i);
if (monthDay) {
let year = new Date().getFullYear();
d = new Date(monthDay[1] + " " + monthDay[2] + ", " + year);
// If parsed date is in the future, it's likely from last year
if (!isNaN(d.getTime()) && d > new Date()) {
d = new Date(monthDay[1] + " " + monthDay[2] + ", " + (year - 1));
}
if (!isNaN(d.getTime())) return d;
}
let timeOnly = cleaned.match(/^\d{1,2}:\d{2}\s*(AM|PM)$/i);
if (timeOnly) {
d = new Date(new Date().toDateString() + " " + cleaned);
if (!isNaN(d.getTime())) return d;
}
let time24 = cleaned.match(/^(\d{1,2}):(\d{2})$/);
if (time24) {
let hours = parseInt(time24[1], 10);
let minutes = parseInt(time24[2], 10);
if (hours <= 23 && minutes <= 59) {
d = new Date();
d.setHours(hours, minutes, 0, 0);
return d;
}
}
return null;
}
// ── Row-data extractors ───────────────────────────────────────────
function getDateFromRow(row) {
let spans = row.querySelectorAll("td span[title]");
for (let i = 0; i < spans.length; i++) {
let d = parseGmailDate(spans[i].getAttribute("title"));
if (d) return d;
}
return null;
}
function getSenderFromRow(row) {
// Gmail uses .bA4 for the complete visible sender or participant label.
// Its nested .zF and .yP elements can represent only one participant.
let el = row.querySelector("span.bA4") ||
row.querySelector("span.zF") ||
row.querySelector("span.yP") ||
row.querySelector("[data-hovercard-id]");
if (!el) return "";
let sender = (el.getAttribute("name") || el.textContent || el.getAttribute("data-hovercard-id") || "").trim();
return sender.toLocaleLowerCase();
}
function isUnread(row) {
return !!(row && row.classList && row.classList.contains("zE"));
}
// ── Starred-row detection ─────────────────────────────────────────
function isRowStarred(row) {
try {
// Fast-path: the standard Gmail starred class
if (row.querySelector("td.apU span.T-KT-Jp")) return true;
// PERF: Single query for the star cell, then walk its subtree once
let starCell = row.querySelector("td.apU");
if (!starCell) return false;
// Check for T-KT subclasses (indicates active star state)
let starSpans = starCell.getElementsByClassName("T-KT");
for (let k = 0; k < starSpans.length; k++) {
let cl = starSpans[k].classList;
for (let m = 0; m < cl.length; m++) {
if (cl[m] !== "T-KT" && cl[m].indexOf("T-KT-") === 0) return true;
}
}
// Check aria-label / title on elements within the star cell
// Supports English ("starred"/"not starred") and uses data attribute
// as a locale-agnostic fallback for non-English Gmail
let allEls = starCell.querySelectorAll("[aria-label], [title], [data-tooltip]");
for (let i = 0; i < allEls.length; i++) {
let lbl = (allEls[i].getAttribute("aria-label") || allEls[i].getAttribute("title") || allEls[i].getAttribute("data-tooltip") || "").toLowerCase();
if (lbl === "starred") return true;
if (lbl.indexOf("starred") !== -1 && lbl.indexOf("not") === -1) return true;
}
// Locale-agnostic fallback: check if the star cell's img/icon has a
// "checked" or "active" state via ARIA or class naming conventions
let ariaChecked = starCell.querySelector("[aria-checked='true'], [data-starred='true']");
if (ariaChecked) return true;
// Check SVG fills (some themes use SVG stars)
let svgs = starCell.getElementsByTagName("svg");
for (let n = 0; n < svgs.length; n++) {
let paths = svgs[n].querySelectorAll("path, polygon");
for (let p = 0; p < paths.length; p++) {
let fill = paths[p].getAttribute("fill");
if (fill && fill !== "none" && fill !== "transparent" && fill !== "currentColor") return true;
}
}
return false;
} catch (e) {
return false;
}
}
// ── Attachment-row detection ──────────────────────────────────────
function isRowHasAttachment(row) {
try {
// PERF: Cheapest class-based checks first (most common Gmail versions)
if (row.querySelector("span.brg, div.brd, span.aZo, span.boo, img.br2")) return true;
if (row.querySelector("td.yf img.yE")) return true;
// Narrower attribute checks only if class checks failed
let tooltipEls = row.querySelectorAll("[data-tooltip]");
for (let j = 0; j < tooltipEls.length; j++) {
if ((tooltipEls[j].getAttribute("data-tooltip") || "").toLowerCase().indexOf("attachment") !== -1) return true;
}
// Fallback: scoped alt check (cheaper than broad [aria-label],[title])
if (row.querySelector('img[alt="Has attachment"]')) return true;
return false;
} catch (e) {
return false;
}
}
// ── Visible email rows (cached for perf) ──────────────────────────
let _rowCache = null;
let _rowCacheTime = 0;
function getVisibleEmailRows(forceRefresh) {
let now = Date.now();
if (!forceRefresh && _rowCache && (now - _rowCacheTime) < CONFIG.ROW_CACHE_TTL) return _rowCache;
let allRows = document.querySelectorAll("tr.zA");
let result = [];
for (let i = 0; i < allRows.length; i++) {
let row = allRows[i];
if (row.offsetHeight === 0) continue;
let table = row.closest("table");
if (table && table.offsetHeight === 0) continue;
result.push(row);
}
_rowCache = result;
_rowCacheTime = now;
return result;
}