-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpanel.js
More file actions
883 lines (775 loc) · 26.2 KB
/
panel.js
File metadata and controls
883 lines (775 loc) · 26.2 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
console.clear();
// setup the styles for swal
const TOAST_CONFIG = {
toast: true,
position: "top-end",
showConfirmButton: false,
timer: 2000,
timerProgressBar: true,
background: "#f3e9dc",
color: "#895737",
};
const SWAL_THEME = {
background: "#f3e9dc",
color: "#895737",
iconColor: "#c08552",
confirmButtonColor: "#c08552",
cancelButtonColor: "#dab49d",
width: "360px",
customClass: { title: "darumadrop-one-regular" },
};
// API Key Management
async function checkAndPromptForApiKey() {
const result = await chrome.storage.local.get(["claudeApiKey"]);
if (!result.claudeApiKey) {
const { value: apiKey } = await Swal.fire({
title: "Hi there!",
html: `
<p style="margin-bottom: 15px; font-weight: bold;">You need a Claude API key to continue.</p>
<p style="font-size: 12px; font-weight: bold; color: #895737;">Get it from <a href="https://console.anthropic.com/settings/keys" target="_blank" style="color: #c08552; text-decoration: underline;">console.anthropic.com</a> ☺︎</p>
`,
input: "text",
inputPlaceholder: "sk-ant-...",
showCancelButton: false,
allowOutsideClick: false,
allowEscapeKey: false,
confirmButtonText: "Save",
inputValidator: (value) => {
if (!value) {
return "Please enter an API key";
}
if (!value.startsWith("sk-ant-")) {
return "API key should start with sk-ant-";
}
},
...SWAL_THEME,
});
if (apiKey) {
await chrome.storage.local.set({ claudeApiKey: apiKey });
Swal.fire({
icon: "success",
timer: 2000,
showConfirmButton: false,
...SWAL_THEME,
});
}
}
}
const FOLDERS_CONTAINER_HTML = `<div id="folders-container" class="grid grid-cols-3 gap-4"></div>`;
// DOM ELEMENTS
const form = document.querySelector("#add-job");
const companyInput = document.getElementById("company-input");
const roleInput = document.getElementById("role-input");
const locationInput = document.getElementById("location-input");
const typeInput = document.getElementById("type-input");
const linkInput = document.getElementById("link-input");
const deadlineInput = document.getElementById("deadline-input");
const notesTextarea = document.getElementById("notes-textarea");
const submitBtn = document.getElementById("add-btn");
const addAppBtn = document.getElementById("add-app-btn");
const myJobsBtn = document.getElementById("my-jobs-btn");
const cancelBtn = document.getElementById("cancel-changes-btn");
const autofillBtn = document.getElementById("autofill-btn");
const backToFoldersBtn = document.getElementById("backToFolders");
const reorganizeBtn = document.getElementById("reorganizeBtn");
const filterBtns = document.querySelectorAll(".filter-btn");
// different sections / displays
const intro = document.getElementById("intro");
const addSection = document.getElementById("add");
const jobsSection = document.getElementById("jobs");
const jobDisplay = document.getElementById("job-display");
const emptyState = document.getElementById("empty-state");
let jobList = [];
let currentFilter = "all";
let cachedCategories = null;
let editingJobId = null;
// initally hidden
addSection.style.display = "none";
jobsSection.style.display = "none";
cancelBtn.style.display = "none";
backToFoldersBtn.style.display = "none";
// Navigation Functions
const showAddSection = () => {
jobsSection.style.display = "none";
addSection.style.display = "block";
};
const showJobsSection = () => {
jobsSection.style.display = "block";
addSection.style.display = "none";
};
const resetFormState = () => {
editingJobId = null;
form.reset();
cancelBtn.style.display = "none";
autofillBtn.style.display = "block";
submitBtn.textContent = "Add Job to Wishlist";
};
addAppBtn.addEventListener("click", () => {
resetFormState();
showAddSection();
});
myJobsBtn.addEventListener("click", () => {
showJobsSection();
setFilter("all");
});
cancelBtn.addEventListener("click", () => {
resetFormState();
showJobsSection();
setFilter("all");
});
const addJob = (e) => {
e.preventDefault();
// construct new job
const jobData = {
company: companyInput.value,
role: roleInput.value,
location: locationInput.value,
type: typeInput.value,
status: "Wishlist",
deadline: deadlineInput.value,
link: linkInput.value,
notes: notesTextarea.value,
};
// check if editing a job -> flow is different
if (editingJobId) {
updateJob(editingJobId, jobData);
} else {
const newJob = { id: Date.now(), ...jobData };
jobList.push(newJob);
// Add to "Uncategorized" folder without re-categorizing
if (cachedCategories && cachedCategories.length > 0) {
// Find or create "Uncategorized" category
let uncategorized = cachedCategories.find(
(cat) => cat.name === "Uncategorized"
);
if (!uncategorized) {
uncategorized = { name: "Uncategorized", jobIds: [] };
cachedCategories.push(uncategorized);
}
uncategorized.jobIds.push(newJob.id);
} else {
// If no categories exist, create initial "Uncategorized" category
cachedCategories = [{ name: "Uncategorized", jobIds: [newJob.id] }];
}
showToast("Job Added Successfully!");
chrome.storage.local.set({ jobs: jobList, categories: cachedCategories });
form.reset(); // clean flow!
}
if (editingJobId) {
resetFormState();
}
};
form.addEventListener("submit", addJob);
// filter and show
const resetToFolderView = () => {
jobDisplay.innerHTML = FOLDERS_CONTAINER_HTML;
backToFoldersBtn.style.display = "none";
};
const setFilter = (filter) => {
currentFilter = filter;
filterBtns.forEach((btn) => {
btn.classList.remove("underline");
if (btn.dataset.filter === filter) {
btn.classList.add("underline");
}
});
console.log(
"setFilter called with:",
filter,
"jobList:",
jobList,
"cachedCategories:",
cachedCategories
);
resetToFolderView();
displayFolders();
};
filterBtns.forEach((btn) =>
btn.addEventListener("click", () => setFilter(btn.dataset.filter))
);
const showToast = (title, icon = "success") => {
Swal.fire({ ...TOAST_CONFIG, icon, title });
};
const saveJobs = () => {
chrome.storage.local.set(
{ jobs: jobList, categories: cachedCategories },
() => {
cachedCategories ? displayFolders() : autoCategorize();
}
);
};
const loadJobs = () => {
chrome.storage.local.get(["jobs", "categories"], (result) => {
jobList = result.jobs || [];
// Fix: Ensure categories is always an array
let categories = result.categories;
if (categories && !Array.isArray(categories)) {
categories = [categories];
}
cachedCategories = categories?.length > 0 ? categories : null;
cachedCategories ? displayFolders() : autoCategorize();
// ok its getting them.
console.log(jobList);
});
};
const attachJobCardListeners = (jobs) => {
jobs.forEach((job) => {
const jobHeader = document.querySelector(`[data-toggle-id="${job.id}"]`);
const editBtn = document.querySelector(`[data-edit-id="${job.id}"]`);
const deleteBtn = document.querySelector(`[data-delete-id="${job.id}"]`);
const statusDropdown = document.querySelector(
`[data-status-id="${job.id}"]`
);
if (jobHeader)
jobHeader.addEventListener("click", () => toggleJobCard(job.id));
if (editBtn) editBtn.addEventListener("click", () => openEditModal(job.id));
if (deleteBtn) deleteBtn.addEventListener("click", () => deleteJob(job.id));
if (statusDropdown)
statusDropdown.addEventListener("change", () => changeStatus(job.id));
});
};
const displayJobs = (jobs = jobList) => {
if (jobs.length === 0) {
jobDisplay.innerHTML = FOLDERS_CONTAINER_HTML;
emptyState.style.display = "block";
reorganizeBtn.style.display = "none";
return;
}
emptyState.style.display = "none";
reorganizeBtn.style.display = "inline-block";
jobDisplay.innerHTML = jobs
.map((j, index) => createJobCard(j, index + 1))
.join("");
const cards = jobDisplay.querySelectorAll("[data-job-id]");
cards.forEach((card) => card.classList.add("fade-in-bounce-delayed"));
attachJobCardListeners(jobs);
};
const toggleJobCard = (jobId) => {
const details = document.getElementById(`details-${jobId}`);
const card = document.querySelector(`[data-job-id="${jobId}"]`);
const icon = card.querySelector(".toggle-icon");
if (details.style.maxHeight === "0px" || !details.style.maxHeight) {
details.style.maxHeight = details.scrollHeight + "px";
icon.style.transform = "rotate(180deg)";
} else {
details.style.maxHeight = "0px";
icon.style.transform = "rotate(0deg)";
}
};
const displayFolders = (roles = cachedCategories, allJobs = jobList) => {
const container = document.getElementById("folders-container");
if (!container) return;
console.log(
"displayFolders called with roles:",
roles,
"allJobs:",
allJobs,
"currentFilter:",
currentFilter
);
// Show loading spinner if categories are being generated
if (!roles || roles.length === 0) {
console.log(
"No roles, jobList.length:",
jobList.length,
"cachedCategories:",
cachedCategories
);
if (jobList.length > 0 && !cachedCategories) {
container.innerHTML = `
<div id="loading-categories" class="col-span-3 text-center py-8">
<div class="inline-block w-8 h-8 border-4 border-[var(--neutral-brown)] border-t-transparent rounded-full animate-spin"></div>
</div>
`;
return;
}
container.innerHTML = "";
return;
}
const filteredJobs =
currentFilter === "all"
? allJobs
: allJobs.filter((j) => j.status === currentFilter);
console.log("filteredJobs:", filteredJobs);
const filteredRoles = roles
.map((role) => ({
...role,
jobIds: role.jobIds.filter((id) => filteredJobs.some((j) => j.id == id)), // Use == instead of === to handle string/number mismatch
}))
.filter((role) => role.jobIds.length > 0);
console.log("filteredRoles:", filteredRoles);
container.innerHTML = "";
const hasJobs = filteredRoles.length > 0;
console.log("hasJobs:", hasJobs);
emptyState.style.display = hasJobs ? "none" : "block";
reorganizeBtn.style.display =
hasJobs && currentFilter === "all" ? "inline-block" : "none";
if (!hasJobs) {
console.log("No jobs to display, returning early");
return;
}
filteredRoles.forEach((role) => {
const folderDiv = document.createElement("div");
folderDiv.className =
"folder flex flex-col text-center fade-in-bounce-delayed";
folderDiv.innerHTML = `
<img class="folder-img" src="/media/folder-icon.png" />
<span class="folder-label">${role.name}</span>
`;
folderDiv.addEventListener("click", () =>
showJobsInFolder(role, filteredJobs)
);
container.appendChild(folderDiv);
});
};
const showJobsInFolder = (role, filteredJobs) => {
const jobsInFolder = filteredJobs.filter((j) => role.jobIds.includes(j.id));
document.getElementById("folders-container").style.display = "none";
displayJobs(jobsInFolder);
reorganizeBtn.style.display = "none";
showBackButton();
};
const showBackButton = () => {
backToFoldersBtn.style.display = "block";
backToFoldersBtn.textContent = "⬅︎";
backToFoldersBtn.onclick = () => {
resetToFolderView();
displayFolders();
};
};
// not using the number parameter rn -> for tracking & displaying index, might add
const createJobCard = (job, number) => {
return `
<div class="mb-5 max-w-sm mx-auto" data-job-id="${job.id}">
<div class="p-3 rounded-lg flex justify-between items-center cursor-pointer transition-all duration-200 bg-white/50 hover:bg-white" data-toggle-id="${
job.id
}">
<div class="text-left flex-1">
<h3 class="m-0 text-sm font-normal nanum-gothic-extrabold text-[var(--warm-brown)]">${
job.role
} @ ${job.company}</h3>
</div>
<div class="flex items-center gap-3">
<span class="toggle-icon text-sm text-[var(--warm-brown)] transition-transform duration-300 ease-in-out">▼</span>
</div>
</div>
<div class="job-details max-h-0 overflow-hidden transition-all duration-300 ease-in-out" id="details-${
job.id
}">
<div class="p-4 rounded-b-lg -mt-px bg-white/50">
<div class="flex justify-between">
<a href="${
job.link
}" target="_blank" class="darumadrop-one-regular my-2 text-left uppercase text-[var(--neutral-brown)] hover:underline text-sm font-bold">View job posting</a>
<select class="darumadrop-one-regular my-2 text-center text-[var(--tan)] text-sm focus:outline-none font-bold hover:cursor-pointer" data-status-id="${
job.id
}">
<option disabled selected>✱ ${job.status.toUpperCase()} ✱</option>
<option>Wishlist</option>
<option>Applied</option>
<option>Interview</option>
<option>Offer</option>
</select>
</div>
<p class="my-2 text-xs text-left"><strong>Location</strong><br> ${
job.location
} (${job.type})</p>
<p class="my-2 text-xs text-left"><strong>Deadline</strong><br> ${
job.deadline || "None"
}</p>
<p class="my-2 text-xs text-left"><strong>Notes</strong><br> ${
job.notes ? job.notes.replace(/\n/g, "<br>") : "None"
}</p>
<div class="mt-4 flex justify-end gap-2">
<button class="px-3 py-1.5 border border-gray-400 rounded-lg bg-white/50 cursor-pointer transition-all duration-200 text-xs hover:bg-gray-50" data-edit-id="${
job.id
}">Edit</button>
<button class="px-3 py-1.5 border border-gray-400 rounded-lg bg-white/50 cursor-pointer transition-all duration-200 text-xs hover:bg-gray-50" data-delete-id="${
job.id
}">Delete</button>
</div>
</div>
</div>
</div>
`;
};
const removeJobFromCategories = (jobId) => {
// check if already
if (!cachedCategories) return;
cachedCategories.forEach(
(cat) => (cat.jobIds = cat.jobIds.filter((id) => id !== jobId))
);
cachedCategories = cachedCategories.filter((cat) => cat.jobIds.length > 0);
};
const openEditModal = (jobId) => {
const job = jobList.find((j) => j.id === jobId);
if (!job) return;
// set stuff
editingJobId = jobId;
companyInput.value = job.company;
roleInput.value = job.role;
typeInput.value = job.type;
locationInput.value = job.location;
deadlineInput.value = job.deadline;
linkInput.value = job.link;
notesTextarea.value = job.notes || "";
// change stuff, show stuff / hide stuff
cancelBtn.style.display = "block";
autofillBtn.style.display = "none";
submitBtn.textContent = "Save Edits";
showAddSection();
};
const updateJob = (jobId, updatedData) => {
const index = jobList.findIndex((j) => j.id === jobId);
if (index === -1) return;
jobList[index] = { ...jobList[index], ...updatedData };
saveJobs();
showToast("Successfully Updated! ˚⟡˖");
showJobsSection();
resetToFolderView();
setFilter(jobList[index].status);
};
const changeStatus = (jobId) => {
const index = jobList.findIndex((j) => j.id === jobId);
if (index === -1) return;
const newStatus = document.querySelector(
`[data-job-id="${jobId}"] select`
).value;
jobList[index].status = newStatus;
saveJobs();
resetToFolderView();
setFilter(newStatus);
};
const deleteJob = (jobId) => {
Swal.fire({
title: "Are you sure you want to delete?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Delete",
cancelButtonText: "Cancel",
reverseButtons: true,
...SWAL_THEME,
}).then((result) => {
if (result.isConfirmed) {
removeJobFromCategories(jobId);
jobList = jobList.filter((j) => j.id !== jobId);
// If no jobs left, clear categories and show empty state
if (jobList.length === 0) {
cachedCategories = null;
chrome.storage.local.set({ jobs: [], categories: null }, () => {
const container = document.getElementById("folders-container");
if (container) {
container.innerHTML = "";
}
emptyState.style.display = "block";
reorganizeBtn.style.display = "none";
});
} else {
saveJobs();
}
showToast("Successfully Deleted!");
resetToFolderView();
}
});
};
// LOADING THING
const setLoadingState = (isLoading) => {
const loadingElement = document.getElementById("loading-categories");
if (loadingElement)
loadingElement.style.display = isLoading ? "block" : "none";
const setElementState = (el) => {
el.disabled = isLoading;
el.style.opacity = isLoading ? "0.5" : "1";
el.style.cursor = isLoading ? "not-allowed" : "pointer";
};
setElementState(reorganizeBtn);
filterBtns.forEach(setElementState);
};
// AUTOCATEGORIZE
async function autoCategorize() {
if (cachedCategories) {
displayFolders(cachedCategories, jobList);
return;
}
// If no jobs, show empty state
if (jobList.length === 0) {
const container = document.getElementById("folders-container");
if (container) {
container.innerHTML = "";
}
emptyState.style.display = "block";
reorganizeBtn.style.display = "none";
return;
}
// spinner (fix, right after you add a job -> then click see jobs doesn't show up)
const container = document.getElementById("folders-container");
if (container) {
container.innerHTML = `
<div id="loading-categories" class="col-span-3 text-center py-8">
<div class="inline-block w-8 h-8 border-4 border-[var(--neutral-brown)] border-t-transparent rounded-full animate-spin"></div>
</div>
`;
}
setLoadingState(true);
chrome.storage.local.get(["jobs"], (result) => {
const jobs = result.jobs || [];
console.log("Categorizing jobs:", jobs);
chrome.runtime.sendMessage(
{ action: "categorizeJobs", jobs },
(response) => {
setLoadingState(false);
console.log("Categorize response:", response);
if (chrome.runtime.lastError) {
console.error("Runtime error:", chrome.runtime.lastError);
showToast("Failed to categorize jobs", "error");
return;
}
if (response && response.success) {
cachedCategories = response.categories;
chrome.storage.local.set({ categories: cachedCategories });
console.log("Categories created:", cachedCategories);
displayFolders(response.categories, jobs);
} else {
console.error("Categorization failed:", response);
showToast(
"Failed to categorize jobs: " +
(response?.error || "Unknown error"),
"error"
);
}
}
);
});
}
reorganizeBtn.addEventListener("click", () => {
const container = document.getElementById("folders-container");
if (container) {
// can probably clean this up
container.innerHTML = `
<div id="loading-categories" class="col-span-3 text-center py-8">
<div class="inline-block w-8 h-8 border-4 border-[var(--neutral-brown)] border-t-transparent rounded-full animate-spin"></div>
</div>
`;
}
cachedCategories = null;
chrome.storage.local.remove("categories", () => autoCategorize());
});
// AUTOFILL
const setFormLoadingState = (isLoading) => {
const formElements = [
companyInput,
roleInput,
locationInput,
typeInput,
linkInput,
deadlineInput,
notesTextarea,
submitBtn,
autofillBtn,
];
formElements.forEach((element) => {
element.disabled = isLoading;
element.style.opacity = isLoading ? "0.5" : "1";
element.style.cursor = isLoading ? "not-allowed" : "";
});
// loadin button
autofillBtn.textContent = isLoading ? "Autofilling..." : "Autofill";
};
autofillBtn.addEventListener("click", async () => {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const spinner = document.getElementById("autofill-spinner");
// errors
if (
!tab.url ||
tab.url.startsWith("chrome://") ||
tab.url.startsWith("chrome-extension://")
) {
showToast(
"Sorry, Coco cannot autofill from this page. Please navigate to a job posting website! ˚⟡˖ ࣪",
"error"
);
return;
}
spinner.classList.remove("hidden");
setFormLoadingState(true);
chrome.tabs.sendMessage(tab.id, { action: "getPageContent" }, (response) => {
if (chrome.runtime.lastError) {
spinner.classList.add("hidden");
showToast(
"Sorry, Coco cannot access this page. Try refreshing first! ˚⟡˖",
"error"
);
setFormLoadingState(false);
return;
}
if (response) {
chrome.runtime.sendMessage(
{ action: "extractJobInfo", pageText: response.text },
(result) => {
if (chrome.runtime.lastError) {
spinner.classList.add("hidden");
showToast("Could not extract job info", "error");
setFormLoadingState(false);
return;
}
if (result && result.success) {
roleInput.value = result.jobInfo.title || "";
companyInput.value = result.jobInfo.company || "";
locationInput.value = result.jobInfo.location || "";
typeInput.value = result.jobInfo.type || "";
deadlineInput.value = result.jobInfo.deadline || "";
linkInput.value = response.url;
notesTextarea.value = result.jobInfo.requirements || "";
spinner.classList.add("hidden");
setFormLoadingState(false);
showToast("Done! ˚⟡˖", "success");
} else {
spinner.classList.add("hidden");
showToast(
"Sorry, Coco could not extract the job information.",
"error"
);
setFormLoadingState(false);
}
}
);
}
});
});
// RESUME ANALYSIS
const analyzeResumeBtn = document.getElementById("analyze-resume-btn");
pdfjsLib.GlobalWorkerOptions.workerSrc = "pkgs/pdf.worker.min.js";
async function extractTextFromPDF(file) {
const arrayBuffer = await file.arrayBuffer();
const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
let fullText = "";
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const textContent = await page.getTextContent();
const pageText = textContent.items.map((item) => item.str).join(" ");
fullText += pageText + "\n";
}
return fullText;
}
analyzeResumeBtn.addEventListener("click", async () => {
const input = document.createElement("input");
input.type = "file";
input.accept = "application/pdf";
input.onchange = async (e) => {
const file = e.target.files[0];
if (!file) return;
if (file.type !== "application/pdf") {
showToast("Please upload a valid file, Coco needs a pdf ˚⟡˖", "error");
return;
}
Swal.fire({
// want to add an animation to this !!
title: "Analyzing...˚⟡˖",
allowOutsideClick: false,
didOpen: () => Swal.showLoading(),
...SWAL_THEME,
});
try {
const resumeText = await extractTextFromPDF(file);
chrome.runtime.sendMessage(
{ action: "analyzeResume", resumeText, jobs: jobList },
(response) => {
if (chrome.runtime.lastError) {
Swal.fire({
title: "Error",
text:
chrome.runtime.lastError.message ||
"Sorry, Coco could not analyze your resume.",
icon: "error",
...SWAL_THEME,
});
return;
}
if (response && response.success) {
const formattedAnalysis = response.analysis.replace(
/<h3>YOUR ACTION PLAN/i,
"<br><h3>YOUR ACTION PLAN"
// clean it, just adding extra newline
);
Swal.fire({
title: "Your Priority Skills:",
//CLEAN THIS UP
html: `<div style="text-align: left; font-size: 14px; line-height: 1.6;">${formattedAnalysis}</div>`,
icon: "success",
confirmButtonText: "Got it!",
width: "550px",
...SWAL_THEME,
customClass: {
title: "darumadrop-one-regular",
htmlContainer: "nanum-gothic-regular",
},
});
} else {
console.error("Analysis failed:", response);
Swal.fire({
title: "Error",
text:
response?.error ||
"Sorry, your resume analysis failed. Check the console for details",
icon: "error",
...SWAL_THEME,
});
}
}
);
} catch (error) {
Swal.fire({
title: "Error",
text: "Oops! Failed to read pdf file:" + error.message,
icon: "error",
...SWAL_THEME,
});
}
};
input.click();
});
// Reset API Key Button
const resetApiKeyBtn = document.getElementById("reset-api-key-btn");
resetApiKeyBtn.addEventListener("click", async () => {
const result = await Swal.fire({
title: "Are you sure?",
html: `
<p style="font-weight: bold;">This will delete your current key and prompt you to enter a new one.</p>
`,
icon: "warning",
showCancelButton: true,
confirmButtonText: "Yes, reset",
cancelButtonText: "Cancel",
...SWAL_THEME,
});
if (result.isConfirmed) {
chrome.runtime.sendMessage({ action: "deleteApiKey" }, async (response) => {
if (response && response.success) {
Swal.fire({
icon: "success",
timer: 2000,
showConfirmButton: false,
...SWAL_THEME,
});
// Prompt for new API key
await checkAndPromptForApiKey();
} else {
Swal.fire({
title: "Error",
text: "Failed to reset API key.",
icon: "error",
...SWAL_THEME,
});
}
});
}
});
// Check for API key on load
checkAndPromptForApiKey();
loadJobs();
// todo.
//- reformulate prompts to be more coco-like
//- add feedback button
//- add count to number of jobs (inside "all", at least)
//- futher filter by location etc. (more semantic... and custom)
//- hover over ai features✔︎✔︎ (tooltip)