Repository navigation
Expand file tree
/
Copy pathcontentScript.js
More file actions
910 lines (785 loc) · 27.5 KB
/
Copy pathcontentScript.js
File metadata and controls
910 lines (785 loc) · 27.5 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
/**
* Content Script - Detects professor names and injects rating badges
* Works on University of Houston course catalog and schedule pages
*/
// Configuration for DOM selectors
const SELECTORS = {
// TODO: Update these selectors based on actual UH course catalog pages
// Common patterns to look for:
// - Table cells with instructor names
// - Spans/divs with class names like "instructor", "faculty", "professor"
// - Elements within course listings
instructorElements: [
// PeopleSoft (UH, UNT, UT Austin, UTD native)
'span.ps_box-value[id*="SSR_INSTR_LONG"]',
// Ellucian Banner Self-Service (UTSA)
'td[data-property="instructor"] a.email',
'td[data-property="instructor"] a[href^="mailto:"]',
// CollegeScheduler (UTD via collegescheduler.com) — first child span only
'[id^="instructor-option-"] > span:first-child',
// Generic fallbacks
'.instructor-name',
'.faculty-name',
'[data-instructor]',
'td.instructor',
'.course-instructor',
'span[title*="Instructor"]',
],
// Elements to exclude (navigation, headers, etc.)
excludeElements: [
'nav',
'header',
'footer',
'.navigation',
'.menu'
]
};
// Track processed elements to avoid duplicates
let processedElements = new WeakSet();
// Track active badges
const activeBadges = new Map();
let courseMateTooltip = null;
const hoverState = {
activeBadge: null,
hideTimeout: null,
requestId: 0
};
/**
* Extract professor name from element
*/
function extractProfessorName(element) {
// Banner SSB / CollegeScheduler — trust the element contents are a professor name.
// Strip role markers and accept without strict pattern validation so that
// hyphenated names, compound surnames (De La Cruz), multi-word names, etc. all work.
const isBannerSsb = !!element.closest('td[data-property="instructor"]');
const isCollegeScheduler = !!element.closest('[id^="instructor-option-"]');
if (isBannerSsb || isCollegeScheduler) {
const source = element.tagName === 'A'
? element
: element.querySelector('a[title], a[aria-label], a[href^="mailto:"], a.email, a');
const rawText =
source?.getAttribute('title') ||
source?.getAttribute('aria-label') ||
element.getAttribute('title') ||
element.getAttribute('aria-label') ||
source?.textContent ||
element.textContent;
let text = rawText
.replace(/\s*\((Primary|Secondary|Co-Instructor|Teaching Assistant)\)\s*/gi, '')
.replace(/\.{3,}|…/g, '')
.replace(/\s+/g, ' ')
.trim();
if (!text || text.length < 3) return null;
if (/^(TBA|TBD|Staff|Various|Multiple|Online)$/i.test(text)) return null;
if (/^\d+$/.test(text)) return null;
return text;
}
let text = element.textContent.trim();
// Skip empty or very short text
if (!text || text.length < 3) return null;
// Skip common non-name patterns
const skipPatterns = [
/^(TBA|TBD|Staff|Various|Multiple|Online)$/i,
/^\d+$/,
/^[A-Z]{2,5}\s*\d{4}$/,
];
for (const pattern of skipPatterns) {
if (pattern.test(text)) return null;
}
// PeopleSoft / generic selectors — stricter validation
const namePatterns = [
/^([A-Z][a-zA-Z'\-]+),\s*([A-Z])/, // Last, First (allows hyphens, apostrophes)
/^([A-Z][a-zA-Z'\-]+)\s+([A-Z]\.?\s+)?([A-Z][a-zA-Z'\-]+)$/, // First [M.] Last
/^([A-Z][A-Z'\-\s]+),\s*([A-Z][A-Z'\-\s]+)$/ // ALL CAPS: LAST, FIRST
];
for (const pattern of namePatterns) {
if (pattern.test(text)) return text;
}
return null;
}
/**
* Try to find a course code near the instructor element
*/
function findCourseInfo(element) {
const container = element.closest('tr') || element.closest('[role="row"]') || element.parentElement;
if (!container) return null;
// Banner SSB: subject and course number are in dedicated data-property cells
const subjectCell = container.querySelector('td[data-property="subject"]');
const courseNumberCell = container.querySelector('td[data-property="courseNumber"]');
if (subjectCell && courseNumberCell) {
const subject = (subjectCell.getAttribute('title') || subjectCell.textContent).trim().toUpperCase();
const catalog = (courseNumberCell.getAttribute('title') || courseNumberCell.textContent).trim();
if (subject && catalog) {
return { subject, catalog, display: `${subject} ${catalog}` };
}
}
// PeopleSoft: scan row text for a course code pattern
const coursePattern = /\b([A-Z]{2,4})\s*([0-9]{4})\b/;
const match = container.textContent.match(coursePattern);
if (!match) return null;
const subject = match[1].toUpperCase();
const catalog = match[2];
return { subject, catalog, display: `${subject} ${catalog}` };
}
function findSectionContainer(element) {
let node = element;
while (node && node !== document.body) {
if (node.matches && node.matches('tr, [role="row"]')) {
const text = node.textContent.toUpperCase();
if (/\bLECTURE\b|\bLEC\b|\bLABORATORY\b|\bLAB\b/.test(text)) {
return node;
}
}
node = node.parentElement;
}
return element.closest('tr') || element.closest('[role="row"]') || element.parentElement;
}
function isLabSection(element) {
// Banner SSB: check the explicit scheduleType cell
const row = element.closest('tr');
const scheduleTypeCell = row && row.querySelector('td[data-property="scheduleType"]');
if (scheduleTypeCell) {
const type = (scheduleTypeCell.getAttribute('title') || scheduleTypeCell.textContent).toUpperCase();
return /\bLAB\b|\bLABORATORY\b/.test(type) && !/\bLECTURE\b/.test(type);
}
// PeopleSoft: scan section container text
const container = findSectionContainer(element);
if (!container) return false;
const text = container.textContent.toUpperCase();
const hasLab = /\bLAB\b|\bLABORATORY\b/.test(text);
const hasLecture = /\bLEC\b|\bLECTURE\b/.test(text);
return hasLab && !hasLecture;
}
function isDuplicateOptionRow(element, professorName) {
const row = element.closest('tr');
if (!row || !professorName) {
return false;
}
const cells = Array.from(row.children).filter(node => node.nodeType === Node.ELEMENT_NODE);
if (cells.length === 0) {
return false;
}
const firstCellText = cells[0].textContent.trim();
if (firstCellText !== '') {
return false;
}
const previousRow = row.previousElementSibling;
if (!previousRow || !previousRow.matches('tr')) {
return false;
}
const previousText = previousRow.textContent || '';
if (!previousText.includes(professorName)) {
return false;
}
const upper = previousText.toUpperCase();
const hasLecture = /\bLEC\b|\bLECTURE\b/.test(upper);
return hasLecture || !/\bLAB\b|\bLABORATORY\b/.test(upper);
}
function shouldShowForLectureOnly(element) {
const row = element.closest('tr');
if (!row) {
return true;
}
let classGroups = Array.from(
row.querySelectorAll('td.CMPNT_CLASS_NBR .ps_box-link')
);
if (classGroups.length === 0) {
classGroups = Array.from(
row.querySelectorAll('td.CMPNT_CLASS_NBR a[id*="SSR_CLSRCH_F_WK_SSR_CMPNT_DESCR"]')
);
}
if (classGroups.length === 0) {
return true;
}
const cell = element.closest('td');
if (!cell) {
return true;
}
const instructorGroup = element.closest('.ps_box-longedit, .ps_box-edit, .ps_box-link') || element;
const instructorGroups = Array.from(
cell.querySelectorAll('.ps_box-longedit, .ps_box-edit, .ps_box-link')
);
const elementIndex = instructorGroups.indexOf(instructorGroup);
const classIndex = elementIndex >= 0 && elementIndex < classGroups.length ? elementIndex : 0;
const classText = (classGroups[classIndex]?.textContent || '').toUpperCase();
if (!classText) {
return true;
}
const isLecture = /\bLEC\b|\bLECTURE\b/.test(classText);
const isLab = /\bLAB\b|\bLABORATORY\b/.test(classText);
return isLecture || !isLab;
}
function escapeHtml(value) {
return String(value || '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function truncateText(text, maxLength) {
if (!text || text.length <= maxLength) {
return text;
}
return `${text.slice(0, maxLength - 3).trim()}...`;
}
function ensureTooltip() {
if (courseMateTooltip) {
return courseMateTooltip;
}
courseMateTooltip = document.createElement('div');
courseMateTooltip.className = 'coursemate-tooltip';
courseMateTooltip.addEventListener('mouseenter', () => {
if (hoverState.hideTimeout) {
clearTimeout(hoverState.hideTimeout);
}
});
courseMateTooltip.addEventListener('mouseleave', () => {
scheduleHideTooltip();
});
document.body.appendChild(courseMateTooltip);
return courseMateTooltip;
}
function positionTooltip(target) {
const tooltip = ensureTooltip();
const rect = target.getBoundingClientRect();
const tooltipRect = tooltip.getBoundingClientRect();
const padding = 10;
let top = rect.bottom + padding;
let left = rect.left;
if (top + tooltipRect.height > window.innerHeight) {
top = rect.top - tooltipRect.height - padding;
}
if (left + tooltipRect.width > window.innerWidth - padding) {
left = window.innerWidth - tooltipRect.width - padding;
}
if (left < padding) {
left = padding;
}
tooltip.style.top = `${top}px`;
tooltip.style.left = `${left}px`;
}
function renderTooltipContent({ professorName, baseData, hoverData, courseInfo, loading, error }) {
const tooltip = ensureTooltip();
const displayName = professorName || baseData?.name || 'Professor';
const rating = baseData?.overallRating ? baseData.overallRating.toFixed(1) : 'N/A';
const difficulty = baseData?.difficulty !== undefined ? baseData.difficulty.toFixed(1) : 'N/A';
const wouldTakeAgain = baseData?.wouldTakeAgainPercent !== undefined ? `${baseData.wouldTakeAgainPercent}%` : 'N/A';
const rmpUrl = baseData?.rmpUrl;
const reviews = hoverData?.reviews || [];
const isLoading = loading && !hoverData;
const reviewsHtml = isLoading
? '<div class="coursemate-tooltip-loading">Loading reviews...</div>'
: reviews.length > 0 ? reviews.map(review => `
<div class="coursemate-review">"${escapeHtml(truncateText(review.comment || '', 160))}"</div>
`).join('') : '<div class="coursemate-tooltip-loading">No recent reviews found.</div>';
tooltip.innerHTML = `
<div class="coursemate-tooltip-header">
<div class="coursemate-tooltip-name">${escapeHtml(displayName)}</div>
<div class="coursemate-tooltip-rating">${rating} *</div>
</div>
<div class="coursemate-tooltip-subheader">Difficulty: ${difficulty} | ${wouldTakeAgain} Would Take Again</div>
<div class="coursemate-tooltip-section">
<div class="coursemate-tooltip-section-title">Recent Reviews</div>
${reviewsHtml}
</div>
<div class="coursemate-tooltip-footer">
${rmpUrl ? `<a class="coursemate-tooltip-link" href="${rmpUrl}" target="_blank" rel="noreferrer">View on RMP -></a>` : '<span></span>'}
</div>
`;
if (error) {
tooltip.innerHTML += `<div class="coursemate-tooltip-loading">${escapeHtml(error)}</div>`;
}
}
function scheduleHideTooltip() {
if (hoverState.hideTimeout) {
clearTimeout(hoverState.hideTimeout);
}
hoverState.hideTimeout = setTimeout(() => {
const tooltip = ensureTooltip();
tooltip.classList.remove('show');
hoverState.activeBadge = null;
}, 150);
}
async function showTooltipForBadge(badge, baseData, context) {
const tooltip = ensureTooltip();
hoverState.activeBadge = badge;
hoverState.requestId += 1;
const requestId = hoverState.requestId;
renderTooltipContent({
professorName: context.professorName,
baseData,
hoverData: context.hoverData,
courseInfo: context.courseInfo,
loading: !context.hoverData
});
tooltip.classList.add('show');
positionTooltip(badge);
if (context.hoverData || context.loadingPromise) {
return;
}
context.loadingPromise = chrome.runtime.sendMessage({
action: 'getHoverData',
professorName: context.professorName,
teacherId: baseData?.rmpId,
courseInfo: context.courseInfo
}).then((response) => {
context.hoverData = response || null;
}).catch((error) => {
context.hoverData = { error: error.message };
}).finally(() => {
context.loadingPromise = null;
if (hoverState.activeBadge !== badge || requestId !== hoverState.requestId) {
return;
}
renderTooltipContent({
professorName: context.professorName,
baseData,
hoverData: context.hoverData,
courseInfo: context.courseInfo,
loading: false,
error: context.hoverData?.error
});
positionTooltip(badge);
});
}
/**
* Check if element should be excluded
*/
function shouldExclude(element) {
// Never process an element that is (or lives inside) a badge we already inserted
if (element.closest('.coursemate-badge')) return true;
// Check if element or any parent matches exclude selectors
for (const selector of SELECTORS.excludeElements) {
if (element.closest(selector)) {
return true;
}
}
// Check if already processed
if (processedElements.has(element)) {
return true;
}
return false;
}
/**
* Create loading badge
*/
function createLoadingBadge() {
const badge = document.createElement('span');
badge.className = 'coursemate-badge coursemate-loading';
badge.textContent = '...';
badge.title = 'Loading professor rating...';
return badge;
}
/**
* Create rating badge
*/
function createRatingBadge(data, context) {
const badge = document.createElement('span');
badge.className = 'coursemate-badge coursemate-found';
const hasRatings = data.numRatings > 0 && data.overallRating > 0;
const rating = hasRatings ? data.overallRating.toFixed(1) : 'N/A';
const ratingClass = !hasRatings ? 'rating-none'
: rating >= 4.0 ? 'rating-high'
: rating >= 3.0 ? 'rating-medium'
: 'rating-low';
badge.innerHTML = `
<span class="rating ${ratingClass}">${rating}</span>
<span class="rating-count">(${data.numRatings})</span>
`;
// Build accessible label
const tooltipParts = [
`Overall: ${rating}/5.0`,
`${data.numRatings} ratings`
];
if (data.wouldTakeAgainPercent !== undefined) {
tooltipParts.push(`Would take again: ${data.wouldTakeAgainPercent}%`);
}
if (data.difficulty !== undefined) {
tooltipParts.push(`Difficulty: ${data.difficulty.toFixed(1)}/5.0`);
}
badge.setAttribute('aria-label', tooltipParts.join('. '));
// Click handler to open RMP page
badge.style.cursor = 'pointer';
badge.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
if (data.rmpUrl) {
window.open(data.rmpUrl, '_blank');
}
});
const badgeContext = {
professorName: context?.professorName,
courseInfo: context?.courseInfo,
hoverData: null,
loadingPromise: null
};
activeBadges.set(badge, { baseData: data, context: badgeContext });
function triggerTooltip() {
const state = activeBadges.get(badge);
if (state) showTooltipForBadge(badge, state.baseData, state.context);
}
badge.addEventListener('mouseenter', triggerTooltip);
badge.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
triggerTooltip();
});
badge.addEventListener('mouseleave', () => {
scheduleHideTooltip();
});
return badge;
}
/**
* Create "not found" badge with hover tooltip linking to add a rating
*/
function createNotFoundBadge(professorName) {
const badge = document.createElement('span');
badge.className = 'coursemate-badge coursemate-not-found';
badge.textContent = '?';
badge.style.cursor = 'pointer';
function showNotFoundTooltip() {
if (hoverState.hideTimeout) clearTimeout(hoverState.hideTimeout);
hoverState.activeBadge = badge;
const tooltip = ensureTooltip();
tooltip.innerHTML = `
<div class="coursemate-tooltip-header">
<div class="coursemate-tooltip-name">${escapeHtml(professorName || 'Professor')}</div>
</div>
<div class="coursemate-tooltip-section">
<div class="coursemate-tooltip-loading">No RMP rating found for this professor.</div>
</div>
<div class="coursemate-tooltip-footer">
<a class="coursemate-tooltip-link" href="https://www.ratemyprofessors.com/add/professor" target="_blank" rel="noreferrer">Rate this professor -></a>
</div>
`;
tooltip.classList.add('show');
positionTooltip(badge);
}
badge.addEventListener('mouseenter', showNotFoundTooltip);
badge.addEventListener('mouseleave', () => scheduleHideTooltip());
badge.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
showNotFoundTooltip();
});
return badge;
}
/**
* Create error badge
*/
function createErrorBadge(message) {
const badge = document.createElement('span');
badge.className = 'coursemate-badge coursemate-error';
badge.textContent = '!';
badge.title = `Error: ${message}`;
return badge;
}
/**
* Insert badge next to professor name
*/
function insertBadge(element, badge) {
// Anchor tag (Banner SSB with an instructor link): insert badge as sibling after the anchor
if (element.tagName === 'A') {
const next = element.nextElementSibling;
if (next && next.classList.contains('coursemate-badge')) {
activeBadges.delete(next);
next.replaceWith(badge);
} else {
element.insertAdjacentElement('afterend', badge);
}
return;
}
// TD cell (Banner SSB plain-text instructor, no email link):
// insert badge after any anchor inside, or prepend to cell content
if (element.tagName === 'TD') {
const existingBadge = element.querySelector('.coursemate-badge');
if (existingBadge) {
activeBadges.delete(existingBadge);
existingBadge.replaceWith(badge);
} else {
const anchor = element.querySelector('a[href^="mailto:"], a.email');
if (anchor) {
anchor.insertAdjacentElement('afterend', badge);
} else {
element.insertAdjacentElement('afterbegin', badge);
}
}
return;
}
// CollegeScheduler: span inside role="option" — insert after the span as a sibling
if (element.tagName === 'SPAN' && element.parentElement?.getAttribute('role') === 'option') {
const next = element.nextElementSibling;
if (next && next.classList.contains('coursemate-badge')) {
activeBadges.delete(next);
next.replaceWith(badge);
} else {
element.insertAdjacentElement('afterend', badge);
}
return;
}
// PeopleSoft span / other elements: append badge inside the element
const existingBadge = element.querySelector('.coursemate-badge');
if (existingBadge) {
activeBadges.delete(existingBadge);
existingBadge.replaceWith(badge);
} else {
element.appendChild(document.createTextNode(' '));
element.appendChild(badge);
}
}
// Returns the .results-linked div in the Banner SSB linked column of the same row.
function getBannerLinkedDiv(element) {
const row = element.closest('tr');
if (!row) return null;
const cell = row.querySelector('td[data-property="linked"]');
if (!cell) return null;
return cell.querySelector('.results-linked') || cell;
}
// Place a badge inside the linked column, replacing any prior badge there.
function insertLinkedBadge(linkedDiv, badge) {
if (!linkedDiv) return;
const existing = linkedDiv.querySelector('.coursemate-badge');
if (existing) { activeBadges.delete(existing); existing.replaceWith(badge); }
else { linkedDiv.appendChild(badge); }
}
function getBannerBadgeContainer(element) {
return getBannerLinkedDiv(element);
}
function insertProfessorBadge(element, badge) {
const bannerContainer = getBannerBadgeContainer(element);
if (bannerContainer) {
insertLinkedBadge(bannerContainer, badge);
return;
}
insertBadge(element, badge);
}
// Remove any CourseMate badge inserted next to element (used when no rating found)
function removeBadge(element) {
const bannerContainer = getBannerBadgeContainer(element);
if (bannerContainer) {
const badge = bannerContainer.querySelector('.coursemate-badge');
if (badge) { activeBadges.delete(badge); badge.remove(); }
return;
}
if (element.tagName === 'A' || (element.tagName === 'SPAN' && element.parentElement?.getAttribute('role') === 'option')) {
const next = element.nextElementSibling;
if (next && next.classList.contains('coursemate-badge')) {
activeBadges.delete(next);
next.remove();
}
return;
}
if (element.tagName === 'TD') {
const badge = element.querySelector('.coursemate-badge');
if (badge) { activeBadges.delete(badge); badge.remove(); }
return;
}
const badge = element.querySelector('.coursemate-badge');
if (badge) { activeBadges.delete(badge); badge.remove(); }
}
/**
* Process a single professor name element
*/
async function processProfessorElement(element) {
// Skip if already processed or should be excluded
if (shouldExclude(element)) {
return;
}
const professorName = extractProfessorName(element);
if (!professorName) {
return;
}
if (isLabSection(element) || isDuplicateOptionRow(element, professorName) || !shouldShowForLectureOnly(element)) {
return;
}
// Mark as processed
processedElements.add(element);
const courseInfo = findCourseInfo(element);
console.log(`[CourseMate] Found professor: ${professorName}`);
if (courseInfo) {
console.log(`[CourseMate] Matched course: ${courseInfo.display}`);
}
const loadingBadge = createLoadingBadge();
insertProfessorBadge(element, loadingBadge);
// Extension context invalidated (e.g. extension reloaded while tab was open)
if (!chrome?.runtime?.sendMessage) {
removeBadge(element);
processedElements.delete(element);
return;
}
try {
const response = await chrome.runtime.sendMessage({
action: 'getProfessorData',
professorName: professorName,
school: window.location.hostname,
courseInfo: courseInfo
});
// Service worker sleeping — remove loading badge and retry on next rescan
if (!response) {
processedElements.delete(element);
removeBadge(element);
return;
}
if (response.found && response.data) {
// Has a rating — show the rating badge
insertProfessorBadge(element, createRatingBadge(response.data, { professorName, courseInfo }));
} else {
// Confirmed not on RMP — show ? so student can add a rating
insertProfessorBadge(element, createNotFoundBadge(professorName));
}
} catch (error) {
// Unknown error — silently retry rather than show a misleading badge
console.error('[CourseMate] Error processing professor:', error);
removeBadge(element);
processedElements.delete(element);
}
}
/**
* Scan page for professor names
*/
function scanPage() {
console.log('[CourseMate] Scanning page for professors...');
// Banner SSB: process every instructor cell directly.
// Each cell may contain an <a mailto> link or plain text (no email on file).
// We use the anchor when present for clean text and precise badge placement,
// otherwise fall back to the <td> itself.
const bannerCells = document.querySelectorAll('td[data-property="instructor"]');
if (bannerCells.length > 0) {
console.log(`[CourseMate] Found ${bannerCells.length} Banner SSB instructor cells`);
bannerCells.forEach(cell => {
const anchor = cell.querySelector('a[href^="mailto:"], a.email');
const target = anchor || cell;
processProfessorElement(target);
});
}
// PeopleSoft and generic selectors
for (const selector of SELECTORS.instructorElements) {
// Skip Banner SSB selectors — handled above
if (selector.includes('data-property="instructor"')) continue;
try {
const elements = document.querySelectorAll(selector);
if (elements.length > 0) {
console.log(`[CourseMate] Found ${elements.length} elements matching "${selector}"`);
elements.forEach(element => processProfessorElement(element));
}
} catch (error) {
console.error(`[CourseMate] Error with selector "${selector}":`, error);
}
}
}
/**
* Initialize MutationObserver to watch for dynamic content
*/
function initMutationObserver() {
const observer = new MutationObserver((mutations) => {
let shouldScan = false;
for (const mutation of mutations) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
shouldScan = true;
break;
}
}
}
// Banner SSB reveals results by removing display:none — catch style/class changes
// on any element (not just TR/TD/TBODY) since some schools toggle a parent div
if (mutation.type === 'attributes' && mutation.target.nodeType === Node.ELEMENT_NODE) {
shouldScan = true;
}
if (shouldScan) break;
}
if (shouldScan) {
clearTimeout(window.courseMateScanTimeout);
window.courseMateScanTimeout = setTimeout(scanPage, 800);
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['style', 'class']
});
console.log('[CourseMate] MutationObserver initialized');
}
// Banner SSB / CollegeScheduler: listen for clicks that trigger dynamic content loads
function initBannerSsbSearchListener() {
document.addEventListener('click', (e) => {
// Banner SSB search buttons
const isBannerSearch = !!e.target.closest('button, input[type="submit"], a[id*="search"], a[class*="search"]');
// CollegeScheduler instructor dropdown trigger (any click that could open it)
const isCollegeSchedulerTrigger = !!e.target.closest('[class*="dropdown"], [class*="filter"], [class*="instructor"]');
if (isBannerSearch || isCollegeSchedulerTrigger) {
setTimeout(scanPage, 800);
setTimeout(scanPage, 2000);
}
}, true);
}
/**
* Initialize content script
*/
function init() {
console.log('[CourseMate] Content script loaded');
// Wait for DOM to be fully loaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
return;
}
// Initial scan
scanPage();
// Watch for dynamic changes
initMutationObserver();
// Extra fallback for Banner SSB (Ellucian) search results
initBannerSsbSearchListener();
// Re-scan when page visibility changes (in case content loaded while tab was hidden)
document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
console.log('[CourseMate] Page became visible, re-scanning...');
scanPage();
}
});
window.addEventListener('scroll', () => {
scheduleHideTooltip();
}, { passive: true });
window.addEventListener('resize', () => {
if (hoverState.activeBadge) {
positionTooltip(hoverState.activeBadge);
}
});
}
// Start the extension
init();
/**
* TESTING HELPER FUNCTIONS
* These can be called from the browser console for debugging
*/
window.courseMateDebug = {
// Force re-scan
scan: scanPage,
// Test name extraction
testName: (text) => {
const div = document.createElement('div');
div.textContent = text;
return extractProfessorName(div);
},
// Show current selectors
showSelectors: () => {
console.log('Current selectors:', SELECTORS);
},
// Add custom selector
addSelector: (selector) => {
SELECTORS.instructorElements.push(selector);
console.log(`Added selector: ${selector}`);
scanPage();
},
// Clear processed cache and re-scan
reset: () => {
processedElements = new WeakSet();
activeBadges.clear();
// Remove existing badges
document.querySelectorAll('.coursemate-badge').forEach(b => b.remove());
scanPage();
}
};
console.log('[CourseMate] Debug helpers available: window.courseMateDebug');