-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
3528 lines (3084 loc) · 115 KB
/
content.js
File metadata and controls
3528 lines (3084 loc) · 115 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
// Wrap everything in an IIFE to avoid global scope pollution
(function() {
'use strict';
console.log("WaterlooWorks Navigator - Loading extension v47.1 (Button Position Adjusted)...");
console.log("Current URL:", window.location.href);
// Verify we're on WaterlooWorks
if (!window.location.href.includes('waterlooworks.uwaterloo.ca')) {
console.warn('Not on WaterlooWorks site, extension will not activate');
return; // Exit early if not on WaterlooWorks
}
console.log('✓ On WaterlooWorks site, extension activating...');
/**
* SHORTLIST FEATURE v47.1:
* Stars appear in BOTH the job listing table AND modal views!
*
* How it works:
* 1. Each job has its actual ID from WaterlooWorks (e.g., "435669")
* 2. Stars appear on the RIGHT side of job titles in the table (☆ = not shortlisted, ⭐ = shortlisted)
* 3. Click stars in the table for quick shortlisting without opening jobs
* 4. Stars also appear in the modal when you open a job
* 5. All stars sync together and persist using localStorage
*
* IMPORTANT: By default, ALL jobs start as NOT shortlisted (empty star ☆)
*
* Controls:
* - Click any ☆/⭐ star to toggle shortlist (in table or modal)
* - Press Up Arrow in modal to toggle via WaterlooWorks integration
* - Press Ctrl+Shift+C to clear ALL shortlists (reset everything)
* - Stars persist across page refreshes and browser sessions
*/
// Global variables
let jobLinks = [];
let currentJobIndex = -1;
let sectionOrder = [];
let collapsedSections = {};
let fieldOrder = {};
let collapsedFields = {};
let dualColumnEnabled = {}; // Track whether dual column layout is enabled for each panel
let isEnhancing = false;
let modalObserver = null;
// Track shortlisted jobs (persisted to localStorage)
let shortlistedJobs = new Set();
// Track the ACTUAL job ID when a modal is opened
let currentModalJobId = null;
// Track if UI enhancements are enabled (default: true)
let uiEnhancementsEnabled = true;
// Load saved preferences
function loadPreferences() {
try {
const saved = localStorage.getItem('ww-navigator-prefs');
if (saved) {
const prefs = JSON.parse(saved);
sectionOrder = prefs.sectionOrder || [];
collapsedSections = prefs.collapsedSections || {};
fieldOrder = prefs.fieldOrder || {};
collapsedFields = prefs.collapsedFields || {};
dualColumnEnabled = prefs.dualColumnEnabled || {};
// Migrate old field order format to new columns format
let migrated = false;
for (const panelTitle in fieldOrder) {
const order = fieldOrder[panelTitle];
// Check if it's the old array format
if (Array.isArray(order)) {
console.log(`Migrating old field order format for ${panelTitle}`);
fieldOrder[panelTitle] = {
columns: {
left: order,
right: []
}
};
migrated = true;
}
}
if (migrated) {
savePreferences();
console.log('Migrated field order to new format');
}
console.log('Loaded preferences:', prefs);
}
// Load shortlisted jobs
const savedShortlist = localStorage.getItem('ww-navigator-shortlist');
if (savedShortlist) {
console.log('=== LOADING SHORTLIST FROM LOCALSTORAGE ===');
console.log('Raw saved data:', savedShortlist);
const parsed = JSON.parse(savedShortlist);
console.log('Parsed data:', parsed);
// Convert old format (job_XXXXX) to new format (just XXXXX)
const cleanedJobs = parsed.map(id => {
if (typeof id === 'string' && id.startsWith('job_')) {
return id.substring(4); // Remove "job_" prefix
}
return String(id); // Ensure all IDs are strings
}).filter(id => /^\d+$/.test(String(id))); // Only keep pure numbers
console.log('Cleaned jobs:', cleanedJobs);
shortlistedJobs = new Set(cleanedJobs.map(String)); // Ensure all are strings
console.log(`Loaded ${shortlistedJobs.size} shortlisted jobs from localStorage: ${Array.from(shortlistedJobs).join(', ')}`);
console.log('==========================================');
// Save cleaned version if we made changes
if (cleanedJobs.length !== parsed.length || cleanedJobs.some((id, i) => String(id) !== String(parsed[i]))) {
console.log(`Cleaned up job ID format`);
saveShortlist();
}
} else {
console.log('No saved shortlist found in localStorage');
}
// Load UI enhancement preference
const uiEnabled = localStorage.getItem('ww-navigator-ui-enabled');
if (uiEnabled !== null) {
uiEnhancementsEnabled = uiEnabled === 'true';
console.log(`UI Enhancements: ${uiEnhancementsEnabled ? 'Enabled' : 'Disabled'}`);
}
} catch (e) {
console.error('Error loading preferences:', e);
}
}
// Save preferences
function savePreferences() {
try {
const prefs = {
sectionOrder: sectionOrder,
collapsedSections: collapsedSections,
fieldOrder: fieldOrder,
collapsedFields: collapsedFields,
dualColumnEnabled: dualColumnEnabled
};
localStorage.setItem('ww-navigator-prefs', JSON.stringify(prefs));
} catch (e) {
console.error('Error saving preferences:', e);
}
}
// Removed - No local storage for shortlist
// Get all job links and add stars to table rows
function getAllJobLinks() {
console.log('Getting all job links...');
// CRITICAL DEBUG: Log what's in shortlistedJobs
console.log('=== SHORTLIST DEBUG ===');
console.log(`shortlistedJobs contains ${shortlistedJobs.size} items:`, Array.from(shortlistedJobs));
console.log('======================');
// Try multiple selectors - WaterlooWorks uses Vue.js with dynamic attributes
const selectors = [
// Primary selectors
'tbody tr a.overflow--ellipsis',
'tbody[data-v-612a1958] a',
'.table__row--body a[href="javascript:void(0)"]',
// Fallback selectors
'table tbody a[onclick]',
'tr.table__row--body a',
'.dashboard-table tbody a',
// Last resort
'tbody a'
];
let links = [];
for (const selector of selectors) {
const found = document.querySelectorAll(selector);
if (found.length > 0) {
console.log(`Found ${found.length} links with selector: "${selector}"`);
links = found;
break;
}
}
if (links.length === 0) {
console.error('ERROR: No job links found with any selector!');
console.log('Debug info:');
console.log('- Tables found:', document.querySelectorAll('table').length);
console.log('- Tbody found:', document.querySelectorAll('tbody').length);
console.log('- All links:', document.querySelectorAll('a').length);
console.log('- Sample HTML:', document.querySelector('tbody')?.innerHTML?.substring(0, 200));
}
jobLinks = Array.from(links);
console.log(`Total job links found: ${jobLinks.length}`);
// Clear ALL existing stars first (prevents duplicates on pagination)
// Use multiple selectors to ensure we catch all stars
const allStars = document.querySelectorAll('.ww-row-star, span[data-job-id], [class*="star"]');
console.log(`Found ${allStars.length} stars to clear`);
allStars.forEach(star => {
if (star.className && star.className.includes('ww-row-star')) {
star.remove();
}
});
// Double-check by clearing from table rows directly
document.querySelectorAll('tbody tr').forEach(row => {
const star = row.querySelector('.ww-row-star');
if (star) star.remove();
});
console.log('✅ Cleared all existing stars');
// Add fresh stars to each table row
console.log('=== ADDING STARS TO ROWS ===');
links.forEach((link, index) => {
const row = link.closest('tr');
if (row) {
const jobId = getJobIdFromRow(row);
// Get the job title for debugging
const titleText = link.textContent || 'Unknown';
console.log(`Row ${index + 1}: "${titleText}" -> Job ID = ${jobId}`);
// Check if this job should have a star
const shouldHaveStar = shortlistedJobs.has(String(jobId));
console.log(` -> Should have star? ${shouldHaveStar} (checking "${jobId}" in Set)`);
addStarToTableRow(row);
} else {
console.log(`Warning: No row found for link ${index + 1}`);
}
});
console.log('============================');
return jobLinks;
}
// Add a star indicator to a table row
function addStarToTableRow(row) {
const jobId = getJobIdFromRow(row);
if (!jobId) {
console.log('No job ID found for row');
return;
}
// Simple debug
const jobIdStr = String(jobId);
const isInSet = shortlistedJobs.has(jobIdStr);
// Special check for problematic job
if (jobIdStr === "436327") {
console.log(`🚨 PROBLEM JOB 436327 DETECTED!`);
console.log(` Current shortlist:`, Array.from(shortlistedJobs));
console.log(` Is 436327 in shortlist? ${shortlistedJobs.has("436327")}`);
console.log(` Row HTML:`, row.innerHTML.substring(0, 300));
}
console.log(`Star check: Job ${jobIdStr} -> ${isInSet ? '⭐ YES' : '☆ NO'}`);
// Check if star already exists for this specific job ID
if (row.querySelector(`.ww-row-star[data-job-id="${jobId}"]`)) {
console.log(`Star already exists for job ${jobId}`);
return;
}
const isShortlisted = shortlistedJobs.has(jobIdStr);
// Extra debugging for problem cases
if (jobIdStr === "436327" || isShortlisted !== isInSet) {
console.log(`⚠️ DETAILED CHECK for Job ${jobIdStr}:`);
console.log(` jobIdStr type: ${typeof jobIdStr}`);
console.log(` isInSet: ${isInSet}`);
console.log(` isShortlisted: ${isShortlisted}`);
console.log(` shortlistedJobs.has(jobIdStr): ${shortlistedJobs.has(jobIdStr)}`);
console.log(` shortlistedJobs.has("436327"): ${shortlistedJobs.has("436327")}`);
// Check if there's any similar ID in the set
let found = false;
shortlistedJobs.forEach(id => {
if (id.includes("436") || jobIdStr.includes(id) || id.includes(jobIdStr)) {
console.log(` Found similar ID in set: "${id}"`);
found = true;
}
});
if (!found) {
console.log(` No similar IDs found in set`);
}
}
console.log(`FINAL DECISION: Job ${jobIdStr} shortlisted = ${isShortlisted}`);
// Find the job title cell - try multiple selectors
let titleLink = row.querySelector('td a.overflow--ellipsis');
if (!titleLink) {
titleLink = row.querySelector('a[href*="javascript"]');
}
if (!titleLink) {
console.log('No title link found in row');
return;
}
const titleCell = titleLink.closest('td');
if (!titleCell) {
console.log('No title cell found');
return;
}
// Create star button with inline styles to ensure visibility
const star = document.createElement('span');
star.className = 'ww-row-star';
star.setAttribute('data-job-id', jobId); // Add job ID as data attribute
star.innerHTML = isShortlisted ? '⭐' : '☆';
star.title = isShortlisted ? 'Remove from shortlist' : 'Add to shortlist';
// Add inline styles - simple absolute positioning
star.style.cssText = `
position: absolute !important;
right: 15px !important;
top: 50% !important;
transform: translateY(-50%) !important;
font-size: 18px !important;
cursor: pointer !important;
color: ${isShortlisted ? '#ffd700' : '#999'} !important;
z-index: 10 !important;
`;
star.addEventListener('click', async (e) => {
console.log(`=== STAR CLICKED ===`);
console.log(`Job ID: ${jobId}`);
console.log(`Type: ${typeof jobId}`);
e.preventDefault();
e.stopPropagation();
// Toggle in our tracking (ensure jobId is a string)
const jobIdStr = String(jobId);
console.log(`Converting to string: "${jobIdStr}"`);
// Special check for problem job
if (jobIdStr === "436327") {
console.log(`🚨 USER CLICKED ON PROBLEM JOB 436327!`);
console.log(`Before click - Is in shortlist? ${shortlistedJobs.has(jobIdStr)}`);
}
if (shortlistedJobs.has(jobIdStr)) {
console.log(`REMOVING job ${jobIdStr} from shortlist`);
shortlistedJobs.delete(jobIdStr);
star.innerHTML = '☆';
star.title = 'Add to shortlist';
} else {
console.log(`ADDING job ${jobIdStr} to shortlist`);
shortlistedJobs.add(jobIdStr);
star.innerHTML = '⭐';
star.title = 'Remove from shortlist';
}
console.log(`shortlistedJobs now contains:`, Array.from(shortlistedJobs));
saveShortlist();
console.log(`Saved to localStorage`);
console.log(`===================`);
// If modal is open for this job, update its star too
if (getCurrentJobId() === jobId) {
updateShortlistIndicator();
}
});
// Find the container div inside the td and append star
const containerDiv = titleCell.querySelector('div');
try {
if (containerDiv) {
console.log(`Appending star to container div for job ${jobId}`);
containerDiv.appendChild(star);
} else {
console.log(`Appending star directly to td for job ${jobId}`);
titleCell.appendChild(star);
}
console.log(`✅ Star added successfully for job ${jobId}`);
} catch (error) {
console.error('ERROR adding star:', error);
}
}
// Update all table row stars
function updateTableRowStars() {
const rows = document.querySelectorAll('tbody[data-v-612a1958] tr');
rows.forEach(row => {
const jobId = getJobIdFromRow(row);
if (jobId) {
// Find the star for this specific job ID
const star = row.querySelector(`.ww-row-star[data-job-id="${jobId}"]`);
if (star) {
const isShortlisted = shortlistedJobs.has(String(jobId)); // CRITICAL: Convert to string!
star.innerHTML = isShortlisted ? '⭐' : '☆';
star.title = isShortlisted ? 'Remove from shortlist' : 'Add to shortlist';
// Update inline color to ensure visibility
star.style.color = isShortlisted ? '#ffd700' : '#999';
}
}
});
}
// Check if modal is open
function isModalOpen() {
return document.querySelector('div[data-v-70e7ded6-s]') !== null;
}
// Get job ID from the clicked row (from table)
function getJobIdFromRow(row) {
// Check if this row contains "Coding Instructor"
if (row.textContent.includes("Coding Instructor")) {
console.log(`🔍 FOUND ROW WITH "Coding Instructor"`);
console.log(`Row HTML:`, row.innerHTML.substring(0, 600));
}
// Method 1: Look for checkbox with job ID as value
const checkbox = row.querySelector('input[type="checkbox"][name="dataViewerSelection"]');
if (checkbox && checkbox.value) {
const id = String(checkbox.value);
if (row.textContent.includes("Coding Instructor")) {
console.log(`🔍 Coding Instructor row -> Extracted ID from checkbox: "${id}"`);
}
return id;
}
// Method 2: Look for job ID in the first column
const firstTh = row.querySelector('th');
if (firstTh) {
// Look for spans with numbers
const spans = firstTh.querySelectorAll('span');
for (const span of spans) {
const text = span.textContent.trim();
if (/^\d{6}$/.test(text)) {
const id = String(text);
if (row.textContent.includes("Coding Instructor")) {
console.log(`🔍 Coding Instructor row -> Extracted ID from span: "${id}"`);
}
return id;
}
}
}
// Method 3: Look for any 6-digit number in the row
const rowText = row.textContent;
const match = rowText.match(/\b\d{6}\b/);
if (match) {
const id = String(match[0]);
if (row.textContent.includes("Coding Instructor")) {
console.log(`🔍 Coding Instructor row -> Extracted ID from regex: "${id}"`);
}
return id;
}
console.log('ERROR: Could not find job ID in row');
console.log('Row HTML (first 500 chars):', row.innerHTML.substring(0, 500));
return null;
}
// Get current job ID from modal (uses the stored ID from when modal was opened)
function getCurrentJobId() {
// CRITICAL: Use the stored job ID from when the modal was opened
if (currentModalJobId) {
console.log(`Using stored modal job ID: ${currentModalJobId}`);
return String(currentModalJobId); // Ensure it's a string
}
// Fallback: If somehow we don't have the stored ID, try to get it from current index
if (currentJobIndex >= 0 && jobLinks[currentJobIndex]) {
const row = jobLinks[currentJobIndex].closest('tr');
if (row) {
const id = getJobIdFromRow(row);
if (id) {
const idStr = String(id);
console.log(`Using job ID from current index ${currentJobIndex}: ${idStr}`);
currentModalJobId = idStr; // Store it for future use as string
return idStr;
}
}
}
console.log('ERROR: Could not determine current job ID!');
return null;
}
// Save shortlisted jobs to localStorage
function saveShortlist() {
try {
// Ensure all IDs are strings before saving
const jobsArray = Array.from(shortlistedJobs).map(id => String(id));
localStorage.setItem('ww-navigator-shortlist', JSON.stringify(jobsArray));
console.log(`Saved ${shortlistedJobs.size} shortlisted jobs to localStorage:`, jobsArray);
} catch (e) {
console.error('Error saving shortlist:', e);
}
}
// Save UI enhancement preference
function saveUIPreference() {
try {
localStorage.setItem('ww-navigator-ui-enabled', uiEnhancementsEnabled.toString());
console.log(`Saved UI Enhancement preference: ${uiEnhancementsEnabled}`);
} catch (e) {
console.error('Error saving UI preference:', e);
}
}
// Show notification for shortlist actions
function showNotification(message, type = 'add') {
const existing = document.getElementById('ww-notification');
if (existing) existing.remove();
const notification = document.createElement('div');
notification.id = 'ww-notification';
notification.textContent = message;
let background, icon;
if (type === 'add') {
background = 'linear-gradient(135deg, #4caf50, #8bc34a)';
icon = '⭐';
} else if (type === 'remove') {
background = 'linear-gradient(135deg, #f44336, #ff9800)';
icon = '☆';
} else if (type === 'error') {
background = 'linear-gradient(135deg, #d32f2f, #c62828)';
icon = '❌';
} else {
background = 'linear-gradient(135deg, #757575, #424242)';
icon = 'ℹ️';
}
notification.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: ${background};
color: white;
padding: 20px 32px;
border-radius: 12px;
font-size: 18px;
font-weight: bold;
z-index: 1000002;
box-shadow: 0 6px 30px rgba(0,0,0,0.4);
animation: notificationPulse 0.5s ease;
display: flex;
align-items: center;
gap: 10px;
`;
// Add icon to notification
notification.innerHTML = `${icon} ${message}`;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.opacity = '0';
notification.style.transition = 'opacity 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 1500);
}
// Helper function to wait for element with specific content
async function waitForElementWithText(text, timeout = 5000) {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
// First try to find p.label elements specifically (from user's HTML)
const labelPs = document.querySelectorAll('p.label');
for (const p of labelPs) {
if (p.textContent.trim().toLowerCase() === text.toLowerCase()) {
console.log(`✓ Found p.label with "${text}"!`);
return p;
}
}
// Then try any p tag
const allPs = document.querySelectorAll('p');
for (const p of allPs) {
if (p.textContent.trim().toLowerCase() === text.toLowerCase()) {
console.log(`✓ Found p tag with "${text}"!`);
return p;
}
}
// Finally try any small element
const allElements = document.querySelectorAll('*');
for (const elem of allElements) {
// Check for direct text content (not from children)
const directText = Array.from(elem.childNodes)
.filter(node => node.nodeType === Node.TEXT_NODE)
.map(node => node.textContent.trim())
.join(' ');
if (directText.toLowerCase() === text.toLowerCase()) {
console.log(`✓ Found ${elem.tagName} with direct text "${text}"!`);
return elem;
}
}
await new Promise(resolve => setTimeout(resolve, 200));
}
console.log(`Timeout: Could not find element with text "${text}"`);
return null;
}
// Toggle shortlist for current job IN WATERLOOWORKS
async function toggleShortlist() {
const jobId = getCurrentJobId();
if (!jobId) {
console.log('No job ID found');
return;
}
const modal = document.querySelector('div[data-v-70e7ded6-s]');
const jobTitle = modal?.querySelector('h4')?.textContent?.trim();
console.log(`Toggling shortlist for: "${jobTitle}" (ID: ${jobId})`);
// CRITICAL: Select the correct row in the table first!
// WaterlooWorks uses the selected row to determine which job's folder to show
const allRows = document.querySelectorAll('tbody[data-v-612a1958] tr');
let foundRow = null;
for (const row of allRows) {
const rowJobId = getJobIdFromRow(row);
if (rowJobId === jobId) {
foundRow = row;
// The checkbox has name="dataViewerSelection" and value is the job ID
const checkbox = row.querySelector('input[type="checkbox"][name="dataViewerSelection"]');
if (checkbox) {
console.log(`Found checkbox with value: ${checkbox.value}`);
if (!checkbox.checked) {
console.log(`Selecting row for job ${jobId} to sync with WaterlooWorks`);
checkbox.checked = true;
// Trigger both change and click events to ensure WaterlooWorks registers it
checkbox.dispatchEvent(new Event('change', { bubbles: true }));
checkbox.dispatchEvent(new Event('click', { bubbles: true }));
// Wait for WaterlooWorks to register the selection
await new Promise(resolve => setTimeout(resolve, 300));
} else {
console.log('Row already selected');
}
} else {
console.log('WARNING: No checkbox found in row');
}
break;
}
}
if (!foundRow) {
console.error(`ERROR: Could not find table row for job ${jobId}`);
showNotification('Cannot find job in table - try refreshing', 'error');
return;
}
// Check if currently shortlisted (CRITICAL: Convert to string!)
const isCurrentlyShortlisted = shortlistedJobs.has(String(jobId));
// CRITICAL: The folder button is in the TABLE ROW, not the modal!
console.log('Looking for folder button in the table row...');
let folderButton = null;
// Find the folder button in the selected row
if (foundRow) {
// Look for the folder button in this specific row
const rowButtons = foundRow.querySelectorAll('button');
console.log(`Found ${rowButtons.length} buttons in the row`);
for (const btn of rowButtons) {
// Check both the button's aria-label and icon
const ariaLabel = btn.getAttribute('aria-label');
const icon = btn.querySelector('i.material-icons');
if (ariaLabel) {
console.log(` Button aria-label: "${ariaLabel}"`);
}
if (icon) {
const iconText = icon.textContent.trim();
console.log(` Button icon: "${iconText}"`);
// Looking for folder-related buttons
if (iconText === 'folder_open' ||
iconText === 'create_new_folder' ||
(ariaLabel && ariaLabel.toLowerCase().includes('folder'))) {
folderButton = btn;
console.log('✓ Found folder button in table row!');
break;
}
}
}
}
// Fallback: Try searching in modal if not found in row
if (!folderButton) {
console.log('Folder button not in row, searching modal...');
let buttonSearchAttempts = 0;
while (buttonSearchAttempts < 5 && !folderButton) {
const modalArea = document.querySelector('div[data-v-70e7ded6-s]');
if (modalArea) {
const allButtons = modalArea.querySelectorAll('button');
console.log(`Attempt ${buttonSearchAttempts + 1}: Found ${allButtons.length} total buttons in modal`);
// Find the create_new_folder button
allButtons.forEach((btn, index) => {
const icon = btn.querySelector('i.material-icons');
if (icon && icon.textContent.trim() === 'create_new_folder') {
folderButton = btn;
console.log(`✓ Found Save to My Jobs Folder button at index ${index}!`);
// Log its location for debugging
const parent = btn.parentElement;
console.log(`Button parent class: ${parent?.className}`);
console.log(`Button classes: ${btn.className}`);
}
});
}
// Also try searching ALL buttons on the page
if (!folderButton) {
const allPageButtons = document.querySelectorAll('button');
console.log(`Searching ${allPageButtons.length} buttons on entire page...`);
for (const btn of allPageButtons) {
const icon = btn.querySelector('i.material-icons');
if (icon && icon.textContent.trim() === 'create_new_folder') {
folderButton = btn;
console.log('✓ Found folder button in page-wide search!');
// Check if it's visible
const isVisible = btn.offsetParent !== null;
console.log(`Button visibility: ${isVisible}`);
if (!isVisible) {
console.log('Button found but not visible, continuing search...');
folderButton = null;
} else {
break;
}
}
}
}
if (!folderButton) {
await new Promise(resolve => setTimeout(resolve, 300));
buttonSearchAttempts++;
}
}
}
if (!folderButton) {
console.log('ERROR: Save to My Jobs Folder button not found after extensive search');
console.log('Attempting to list all visible buttons for debugging:');
document.querySelectorAll('button').forEach((btn, i) => {
const icon = btn.querySelector('i.material-icons');
if (icon) {
console.log(`Button ${i}: icon="${icon.textContent.trim()}", visible=${btn.offsetParent !== null}`);
}
});
showNotification('Cannot find WaterlooWorks folder button', 'error');
return;
}
// Close any existing panels first
const existingPanel = document.querySelector('.sidebar--action__content, .sidebar--action');
if (existingPanel) {
console.log('Closing existing panel first...');
closeSidePanels();
await new Promise(resolve => setTimeout(resolve, 500));
}
// Click the button to open side panel
console.log('Clicking Save to My Jobs Folder button...');
folderButton.click();
// ULTRA SIMPLE: Just wait for "shortlist" text to appear anywhere
console.log('Waiting for shortlist option to appear...');
// First, let's see what's in the sidebar immediately
await new Promise(resolve => setTimeout(resolve, 500));
const immediateCheck = document.querySelector('.sidebar--action');
if (immediateCheck) {
console.log('Immediate sidebar check:');
console.log(` - Has content: ${immediateCheck.innerHTML.length > 0}`);
console.log(` - HTML length: ${immediateCheck.innerHTML.length}`);
console.log(` - Contains "shortlist": ${immediateCheck.innerHTML.toLowerCase().includes('shortlist')}`);
// CRITICAL: Check what job the side panel is showing
const sidePanelJobTitle = immediateCheck.querySelector('h3')?.textContent?.trim();
console.log(` - Side panel shows job: "${sidePanelJobTitle}"`);
console.log(` - Modal shows job: "${jobTitle}"`);
if (sidePanelJobTitle && sidePanelJobTitle !== jobTitle) {
console.error('WARNING: Side panel is showing DIFFERENT job than modal!');
console.error(`Expected: "${jobTitle}", Got: "${sidePanelJobTitle}"`);
showNotification('ERROR: WaterlooWorks panel showing wrong job!', 'error');
closeSidePanels();
return; // STOP - don't shortlist wrong job!
}
}
const shortlistElement = await waitForElementWithText('shortlist', 8000);
if (!shortlistElement) {
console.log('ERROR: Shortlist text never appeared in sidebar');
showNotification('Shortlist option not found - try creating a shortlist folder first', 'error');
closeSidePanels();
return;
}
console.log(`✓ Found shortlist in ${shortlistElement.tagName} element`);
console.log(` Element text: "${shortlistElement.textContent.trim()}"`);
console.log(` Element HTML: ${shortlistElement.outerHTML.substring(0, 200)}...`);
// Find the checkbox associated with this shortlist element
let shortlistCheckbox = null;
// Start from the element and work our way up/around to find the checkbox
let searchElement = shortlistElement;
let searchAttempts = 0;
while (!shortlistCheckbox && searchAttempts < 5) {
// Try current element
shortlistCheckbox = searchElement.querySelector('input[type="checkbox"]');
// Try siblings
if (!shortlistCheckbox && searchElement.parentElement) {
shortlistCheckbox = searchElement.parentElement.querySelector('input[type="checkbox"]');
}
// Move up one level
searchElement = searchElement.parentElement;
searchAttempts++;
if (!searchElement) break;
}
// Final attempt: Find ANY checkbox with ID containing numbers (like "960")
if (!shortlistCheckbox) {
console.log('Searching for any checkbox near shortlist text...');
const allCheckboxes = document.querySelectorAll('input[type="checkbox"]');
for (const cb of allCheckboxes) {
// Check if this checkbox is near the shortlist text
const label = cb.closest('label');
if (label && label.textContent.toLowerCase().includes('shortlist')) {
shortlistCheckbox = cb;
console.log(`✓ Found shortlist checkbox! ID: ${cb.id}`);
break;
}
}
}
if (!shortlistCheckbox) {
console.log('ERROR: Shortlist checkbox not found');
closeSidePanels();
showNotification('Failed to find shortlist option', 'error');
return;
}
// Toggle the checkbox if needed
const currentState = shortlistCheckbox.checked;
const desiredState = !isCurrentlyShortlisted; // We want to toggle to the opposite state
console.log(`Checkbox state: current=${currentState}, desired=${desiredState}`);
if (currentState !== desiredState) {
console.log('Clicking checkbox to toggle...');
shortlistCheckbox.click();
await new Promise(resolve => setTimeout(resolve, 200));
}
// Find and click the Save button
const saveButton = Array.from(document.querySelectorAll('button')).find(btn =>
btn.textContent.trim().toLowerCase() === 'save'
);
if (saveButton) {
console.log('✓ Clicking Save button...');
saveButton.click();
await new Promise(resolve => setTimeout(resolve, 500));
} else {
console.log('WARNING: Save button not found');
}
// Update our tracking (ensure jobId is a string)
const jobIdStr = String(jobId);
if (isCurrentlyShortlisted) {
shortlistedJobs.delete(jobIdStr);
showNotification('Removed from WaterlooWorks shortlist', 'remove');
} else {
shortlistedJobs.add(jobIdStr);
showNotification('Added to WaterlooWorks shortlist', 'add');
}
// Save to localStorage
saveShortlist();
// Update both modal star and table row star
updateShortlistIndicator();
updateTableRowStars();
console.log(`✅ Shortlist updated in WaterlooWorks! Total shortlisted: ${shortlistedJobs.size}`);
}
// Update shortlist indicator in modal
function updateShortlistIndicator() {
const jobId = getCurrentJobId();
if (!jobId) {
console.log('Cannot update star - no job ID');
return;
}
const isShortlisted = shortlistedJobs.has(String(jobId)); // CRITICAL: Convert to string!
console.log(`Updating star for job ${jobId}: ${isShortlisted ? '⭐ SHORTLISTED' : '☆ NOT SHORTLISTED'}`);
// Debug: Show all currently shortlisted jobs
if (shortlistedJobs.size > 0) {
console.log(`Currently tracking ${shortlistedJobs.size} shortlisted jobs:`, Array.from(shortlistedJobs));
}
// Add star to modal header
const modalContainer = document.querySelector('div[data-v-70e7ded6-s]');
if (modalContainer) {
// Remove existing star if any
const existingStar = modalContainer.querySelector('#ww-shortlist-star');
if (existingStar) existingStar.remove();
// Find a good place to add the star - try the modal header area
const modalHeader = modalContainer.querySelector('[role="tabpanel"]');
if (modalHeader) {
const starButton = document.createElement('button');
starButton.id = 'ww-shortlist-star';
starButton.innerHTML = isShortlisted ? '⭐' : '☆';
starButton.title = isShortlisted ? 'Remove from shortlist (↑)' : 'Add to shortlist (↑)';
starButton.style.cssText = `
position: absolute;
top: 12px;
right: 500px;
background: ${isShortlisted ? 'linear-gradient(135deg, #ffd700, #ffed4e)' : 'white'};
color: ${isShortlisted ? '#333' : '#999'};
border: ${isShortlisted ? '2px solid #ffd700' : '2px solid #ddd'};
border-radius: 50%;
width: 48px;
height: 48px;
font-size: 30px;
cursor: pointer;
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
box-shadow: ${isShortlisted ? '0 3px 15px rgba(255, 215, 0, 0.4)' : '0 2px 10px rgba(0,0,0,0.15)'};
transition: all 0.3s ease;
`;
starButton.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
toggleShortlist(); // Try WaterlooWorks integration
});
starButton.addEventListener('mouseenter', () => {
starButton.style.transform = 'scale(1.15) rotate(10deg)';
if (shortlistedJobs.has(String(jobId))) { // Check current state (convert to string!)
starButton.style.boxShadow = '0 5px 20px rgba(255, 215, 0, 0.6)';
} else {
starButton.style.boxShadow = '0 4px 15px rgba(0,0,0,0.25)';
}
});
starButton.addEventListener('mouseleave', () => {
starButton.style.transform = 'scale(1) rotate(0deg)';
if (shortlistedJobs.has(String(jobId))) { // Check current state (convert to string!)
starButton.style.boxShadow = '0 3px 15px rgba(255, 215, 0, 0.4)';
} else {
starButton.style.boxShadow = '0 2px 10px rgba(0,0,0,0.15)';
}
});
modalHeader.appendChild(starButton);
console.log('Star button added to modal');
}
}
// Remove any existing inline star if it exists (cleanup)
const existingInlineStar = document.querySelector('#ww-inline-star');
if (existingInlineStar) existingInlineStar.remove();
}
// Pre-hide modal to prevent FOUC (ONLY if UI enhancements are enabled)
function preHideModal() {
// CRITICAL: Only hide modal if UI enhancements are ON
if (!uiEnhancementsEnabled) {
// Remove any existing hide styles if UI enhancements are OFF
const existingStyle = document.getElementById('ww-prehide-style');
if (existingStyle) {
existingStyle.remove();
console.log('Removed modal hiding styles - UI enhancements OFF');
}
return;
}