-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent-script.js
More file actions
653 lines (560 loc) · 18.4 KB
/
content-script.js
File metadata and controls
653 lines (560 loc) · 18.4 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
// Gmail Row Highlighter Content Script
const STORAGE_KEY = 'gmailRowHighlighterRules';
const DATA_ATTRIBUTE = 'data-highlight-rule-id';
const PROCESSED_ATTRIBUTE = 'data-highlight-processed';
const pendingRemovalTimers = new WeakMap();
let rules = [];
let observer = null;
let processingTimeout = null;
let messageListContainer = null;
let navigationObserver = null;
let navigationCheckTimeout = null;
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
// Watch for Gmail navigation (SPA navigation)
function watchForNavigation() {
// Observe the main content area for major DOM changes
const mainContent = document.querySelector('[role="main"]') || document.body;
if (navigationObserver) {
navigationObserver.disconnect();
}
navigationObserver = new MutationObserver((mutations) => {
// Debounce navigation checks to avoid excessive DOM queries during rapid changes
clearTimeout(navigationCheckTimeout);
navigationCheckTimeout = setTimeout(() => {
// Check if the message list container has been replaced
const currentContainer = findMessageListContainer();
if (currentContainer && currentContainer !== messageListContainer) {
// Container changed - likely a page navigation
console.log('Gmail Row Highlighter: Detected page navigation, re-initializing...');
messageListContainer = currentContainer;
if (messageListContainer) {
// Re-setup observer on new container
setupObserver();
// Process rows after a brief delay to let Gmail finish loading
setTimeout(() => {
processAllRows();
}, 150);
}
}
}, 300);
});
navigationObserver.observe(mainContent, {
childList: true,
subtree: true
});
}
// Main initialization
async function init() {
try {
// Wait for Gmail to load
await waitForGmail();
// Load rules from storage
await loadRules();
// Set up storage change listener
// Note: We add the listener each time, but it's safe to do so
chrome.storage.onChanged.addListener(handleStorageChange);
// Watch for Gmail navigation
watchForNavigation();
// Find message list container
messageListContainer = findMessageListContainer();
if (messageListContainer) {
// Process existing rows
processAllRows();
// Set up MutationObserver
setupObserver();
} else {
console.warn('Gmail Row Highlighter: Could not find message list container');
// Retry after a delay
setTimeout(() => {
messageListContainer = findMessageListContainer();
if (messageListContainer) {
processAllRows();
setupObserver();
}
}, 2000);
}
} catch (error) {
console.error('Gmail Row Highlighter: Initialization error', error);
}
}
// Wait for Gmail to be ready
function waitForGmail() {
return new Promise((resolve, reject) => {
let timeoutId = null;
// Check if Gmail is loaded by looking for common Gmail elements
const checkGmail = () => {
const gmailIndicators = [
document.querySelector('[role="main"]'),
document.querySelector('table[role="grid"]'),
document.querySelector('tbody')
];
if (gmailIndicators.some(el => el !== null)) {
if (timeoutId) {
clearTimeout(timeoutId);
}
resolve();
} else {
setTimeout(checkGmail, 100);
}
};
// Start checking after a short delay
setTimeout(checkGmail, 500);
// Timeout after 10 seconds -> reject for proper error handling
timeoutId = setTimeout(() => {
reject(new Error('Gmail did not load within timeout period'));
}, 10000);
});
}
// Clear any pending removal timers for a row
function clearPendingRemoval(row) {
const pendingTimer = pendingRemovalTimers.get(row);
if (pendingTimer) {
clearTimeout(pendingTimer);
pendingRemovalTimers.delete(row);
}
}
// Schedule a removal after a short delay to avoid flicker during transient mutations
function scheduleRemovalIfStillNonMatching(row, ruleId) {
clearPendingRemoval(row);
const timerId = setTimeout(() => {
pendingRemovalTimers.delete(row);
const latestRule = rules.find(r => r.id === ruleId);
if (!latestRule || latestRule.enabled === false) {
removeHighlight(row);
return;
}
const latestData = extractRowData(row);
const hasData = latestData.sender || latestData.subject || latestData.labels.length > 0;
if (!hasData) {
// If data is still empty, keep the highlight to avoid flicker
return;
}
const stillMatches = checkRuleMatch(latestData, latestRule);
if (!stillMatches) {
removeHighlight(row);
}
}, 250);
pendingRemovalTimers.set(row, timerId);
}
// Find message list container
function findMessageListContainer() {
// Try multiple selectors for robustness
const selectors = [
'table[role="grid"] tbody',
'div[role="main"] table tbody',
'tbody[role="presentation"]',
'table tbody'
];
for (const selector of selectors) {
const container = document.querySelector(selector);
if (container) {
return container;
}
}
return null;
}
// Load rules from storage
function loadRules() {
return new Promise((resolve) => {
chrome.storage.sync.get([STORAGE_KEY], (result) => {
try {
if (result[STORAGE_KEY] && Array.isArray(result[STORAGE_KEY])) {
// Keep ALL rules (including disabled) so we can check them when removing highlights
rules = result[STORAGE_KEY];
} else {
rules = [];
}
} catch (error) {
console.error('Gmail Row Highlighter: Error loading rules', error);
rules = [];
}
resolve();
});
});
}
// Handle storage changes
function handleStorageChange(changes, areaName) {
if (areaName === 'sync' && changes[STORAGE_KEY]) {
loadRules().then(() => {
// Re-process all visible rows when rules change
// Use a small delay to ensure DOM is ready
setTimeout(() => {
processAllRows();
}, 100);
});
}
}
// Set up MutationObserver
function setupObserver() {
if (!messageListContainer) return;
// Disconnect existing observer
if (observer) {
observer.disconnect();
}
observer = new MutationObserver((mutations) => {
// Debounce processing
clearTimeout(processingTimeout);
processingTimeout = setTimeout(() => {
processMutationChanges(mutations);
}, 100);
});
observer.observe(messageListContainer, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['class', 'aria-label']
});
}
// Process mutation changes
function processMutationChanges(mutations) {
const rowsToProcess = new Set();
for (const mutation of mutations) {
// Handle added nodes
if (mutation.addedNodes) {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
// Check if it's a row or contains rows
if (isMessageRow(node)) {
rowsToProcess.add(node);
} else {
// Check for rows within the added node
const rows = node.querySelectorAll && node.querySelectorAll('tr');
if (rows) {
rows.forEach(row => {
if (isMessageRow(row)) {
rowsToProcess.add(row);
}
});
}
}
}
}
}
// Handle attribute changes (e.g., read/unread status, labels)
// But skip our own attributes to avoid infinite loops
if (mutation.type === 'attributes' && mutation.target) {
const attrName = mutation.attributeName;
if (attrName && !attrName.startsWith('data-highlight')) {
const row = findParentRow(mutation.target);
if (row && isMessageRow(row)) {
rowsToProcess.add(row);
}
}
}
}
// Process collected rows
rowsToProcess.forEach(row => processRow(row));
}
// Check if element is a message row
function isMessageRow(element) {
if (!element || element.tagName !== 'TR') return false;
// Check for Gmail row indicators
const hasRowClass = element.classList.contains('zA') ||
element.classList.contains('zE') ||
element.classList.contains('yO');
const hasRowRole = element.getAttribute('role') === 'row';
return hasRowClass || hasRowRole;
}
// Find parent row element
function findParentRow(element) {
let current = element;
while (current && current.tagName !== 'TR') {
current = current.parentElement;
if (!current || current === document.body) return null;
}
return current;
}
// Process all visible rows
function processAllRows() {
if (!messageListContainer) {
// Try to find container again
messageListContainer = findMessageListContainer();
if (!messageListContainer) {
console.warn('Gmail Row Highlighter: Cannot process rows - container not found');
return;
}
}
const rows = messageListContainer.querySelectorAll('tr');
let processedCount = 0;
rows.forEach(row => {
if (isMessageRow(row)) {
processRow(row);
processedCount++;
}
});
if (processedCount > 0) {
console.log(`Gmail Row Highlighter: Processed ${processedCount} rows`);
}
}
// Process a single row
function processRow(row) {
if (!row) return;
try {
// Extract row data
const rowData = extractRowData(row);
// Check if we have valid data (at least one field populated)
const hasValidData = rowData.sender || rowData.subject || rowData.labels.length > 0;
// Check rules
const matchingRule = findMatchingRule(rowData);
// Get current highlight state
const currentRuleId = row.getAttribute(DATA_ATTRIBUTE);
const currentRule = currentRuleId ? rules.find(r => r.id === currentRuleId) : null;
// Apply or update highlight
if (matchingRule) {
clearPendingRemoval(row);
// We found a matching rule - apply it
// Only update if it's different from current
if (!currentRuleId || currentRuleId !== matchingRule.id) {
applyHighlight(row, matchingRule);
}
} else if (currentRuleId) {
// No matching rule found, but row has a highlight
// First check if the current rule exists and is enabled
if (!currentRule) {
// Rule was deleted - remove highlight
clearPendingRemoval(row);
removeHighlight(row);
} else if (currentRule.enabled === false) {
// Rule is disabled - always remove highlight
clearPendingRemoval(row);
removeHighlight(row);
} else if (hasValidData) {
// Rule exists and is enabled, but doesn't match current data
// Re-check if current rule still matches with current data
const stillMatches = checkRuleMatch(rowData, currentRule);
if (!stillMatches) {
// Rule no longer matches - schedule removal to avoid flicker during rapid DOM updates
scheduleRemovalIfStillNonMatching(row, currentRule.id);
}
// If it still matches, keep the highlight
else {
clearPendingRemoval(row);
}
}
// If we don't have valid data and rule is enabled, preserve existing highlight (defensive approach)
} else {
// No matching rule and no existing highlight - ensure it's clean
clearPendingRemoval(row);
removeHighlight(row);
}
// Mark as processed
row.setAttribute(PROCESSED_ATTRIBUTE, 'true');
} catch (error) {
console.error('Gmail Row Highlighter: Error processing row', error);
}
}
// Check if text contains any of the comma-separated patterns (OR logic)
// Each pattern is matched as a complete phrase (not word-by-word)
function matchesAnyPattern(text, patternString) {
if (!text || !patternString) return false;
const textLower = text.toLowerCase();
// Split by comma and trim each term
const patterns = patternString.split(',').map(p => p.trim()).filter(p => p.length > 0);
// Check if any complete pattern matches
for (const pattern of patterns) {
if (textLower.includes(pattern.toLowerCase())) {
return true;
}
}
return false;
}
// Check if a specific rule matches row data
function checkRuleMatch(rowData, rule) {
if (!rule || rule.enabled === false || !rule.pattern) return false;
const pattern = rule.pattern.trim();
switch (rule.type) {
case 'sender_contains':
return rowData.sender && matchesAnyPattern(rowData.sender, pattern);
case 'subject_contains':
return rowData.subject && matchesAnyPattern(rowData.subject, pattern);
case 'sender_or_subject_contains':
const senderMatch = rowData.sender && matchesAnyPattern(rowData.sender, pattern);
const subjectMatch = rowData.subject && matchesAnyPattern(rowData.subject, pattern);
return senderMatch || subjectMatch;
case 'label_contains':
if (!rowData.labels || rowData.labels.length === 0) return false;
return rowData.labels.some(label => matchesAnyPattern(label, pattern));
default:
return false;
}
}
// Extract data from row
function extractRowData(row) {
const data = {
sender: '',
subject: '',
labels: []
};
try {
// Check if we have cached sender data (from previous extraction)
const cachedSender = row.getAttribute('data-cached-sender');
if (cachedSender && cachedSender.includes('@')) {
data.sender = cachedSender;
}
// Extract sender - try multiple approaches
// First, try to get email attribute
if (!data.sender) {
const emailAttrElements = row.querySelectorAll('[email]');
for (const el of emailAttrElements) {
const email = el.getAttribute('email');
if (email && email.includes('@')) {
data.sender = email.trim();
break;
}
}
}
// If no email attribute, try text content from sender cell
if (!data.sender) {
const senderSelectors = [
'.yW span[email]',
'.yW',
'span[data-hovercard-id]',
'td span[email]',
'td[class*="yW"] span',
'td[class*="yW"]'
];
for (const selector of senderSelectors) {
const senderEl = row.querySelector(selector);
if (senderEl) {
const email = senderEl.getAttribute('email') || senderEl.textContent || '';
if (email.trim()) {
data.sender = email.trim();
// If it's not an email, try to extract email from it
if (!data.sender.includes('@')) {
const emailMatch = data.sender.match(/[\w.-]+@[\w.-]+\.\w+/);
if (emailMatch) {
data.sender = emailMatch[0];
}
}
if (data.sender && data.sender.includes('@')) break;
}
}
}
}
// Fallback: search for email-like patterns in the entire row
if (!data.sender || !data.sender.includes('@')) {
const emailPattern = /[\w.-]+@[\w.-]+\.\w+/;
const rowText = row.textContent || '';
const match = rowText.match(emailPattern);
if (match) {
data.sender = match[0];
}
}
// Cache the sender for future use
if (data.sender && data.sender.includes('@')) {
row.setAttribute('data-cached-sender', data.sender);
}
// Extract subject
const subjectSelectors = [
'.bqe',
'.y6',
'span[data-thread-perm-id]',
'.bog'
];
for (const selector of subjectSelectors) {
const subjectEl = row.querySelector(selector);
if (subjectEl) {
data.subject = (subjectEl.textContent || '').trim();
if (data.subject) break;
}
}
// Extract labels
const labelSelectors = [
'.ar',
'.at',
'[data-label-name]',
'span[title]'
];
const labelElements = [];
for (const selector of labelSelectors) {
const elements = row.querySelectorAll(selector);
labelElements.push(...Array.from(elements));
}
// Get unique label texts
const labelTexts = new Set();
labelElements.forEach(el => {
const labelText = el.getAttribute('data-label-name') ||
el.getAttribute('title') ||
el.textContent || '';
if (labelText.trim()) {
labelTexts.add(labelText.trim());
}
});
data.labels = Array.from(labelTexts);
} catch (error) {
console.error('Gmail Row Highlighter: Error extracting row data', error);
}
return data;
}
// Find matching rule
function findMatchingRule(rowData) {
// Ensure we have valid row data
if (!rowData) return null;
for (const rule of rules) {
if (rule.enabled === false) continue;
if (!rule.pattern || !rule.pattern.trim()) continue;
const pattern = rule.pattern.trim();
switch (rule.type) {
case 'sender_contains':
if (rowData.sender && matchesAnyPattern(rowData.sender, pattern)) {
return rule;
}
break;
case 'subject_contains':
if (rowData.subject && matchesAnyPattern(rowData.subject, pattern)) {
return rule;
}
break;
case 'sender_or_subject_contains':
const senderMatch = rowData.sender && matchesAnyPattern(rowData.sender, pattern);
const subjectMatch = rowData.subject && matchesAnyPattern(rowData.subject, pattern);
if (senderMatch || subjectMatch) {
return rule;
}
break;
case 'label_contains':
if (rowData.labels && rowData.labels.length > 0) {
for (const label of rowData.labels) {
if (label && matchesAnyPattern(label, pattern)) {
return rule;
}
}
}
break;
}
}
return null;
}
// Apply highlight to row
function applyHighlight(row, rule) {
try {
// Remove any existing highlight
removeHighlight(row);
// Apply new highlight
row.setAttribute(DATA_ATTRIBUTE, rule.id);
row.classList.add('gmail-row-highlighter');
// Use a safe color fallback
const color = rule.backgroundColor || '#FFF7CC';
row.style.backgroundColor = color;
// Store rule ID and color for reference
row.setAttribute('data-highlight-color', color);
} catch (error) {
console.error('Gmail Row Highlighter: Error applying highlight', error);
}
}
// Remove highlight from row
function removeHighlight(row) {
try {
row.removeAttribute(DATA_ATTRIBUTE);
row.removeAttribute('data-highlight-color');
row.classList.remove('gmail-row-highlighter');
row.style.backgroundColor = '';
} catch (error) {
console.error('Gmail Row Highlighter: Error removing highlight', error);
}
}