-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidepanel.js
More file actions
630 lines (541 loc) · 25.4 KB
/
sidepanel.js
File metadata and controls
630 lines (541 loc) · 25.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
// sidepanel.js - Controller for the side panel
// Connect to background to track panel open/close state
const panelPort = chrome.runtime.connect({ name: "sidepanel" });
document.addEventListener('DOMContentLoaded', () => {
// Elements
const mainView = document.getElementById('mainView');
const settingsView = document.getElementById('settingsView');
const summarizeBtn = document.getElementById('summarizeBtn');
summarizeBtn.disabled = true; // Disabled until model is ready or non-ondevice provider confirmed
const btnText = summarizeBtn.querySelector('.btn-text');
const btnLoader = summarizeBtn.querySelector('.btn-loader');
const btnCancel = summarizeBtn.querySelector('.btn-cancel');
const settingsBtn = document.getElementById('settingsBtn');
const themeBtn = document.getElementById('themeBtn');
const popoutBtn = document.getElementById('popoutBtn');
const backBtn = document.getElementById('backBtn');
const saveSettingsBtn = document.getElementById('saveSettingsBtn');
const apiKeyInput = document.getElementById('apiKey');
const resultsDiv = document.getElementById('results');
// Model Provider Elements
const providerSelect = document.getElementById('provider');
const geminiSettings = document.getElementById('geminiSettings');
const ollamaSettings = document.getElementById('ollamaSettings');
const ollamaUrlInput = document.getElementById('ollamaUrl');
const ollamaModelSelect = document.getElementById('ollamaModel');
const refreshOllamaBtn = document.getElementById('refreshOllamaBtn');
const resetSettingsBtn = document.getElementById('resetSettingsBtn');
const statusMsg = document.getElementById('statusMsg');
const useSummarizerCheckbox = document.getElementById('useSummarizer');
const geminiModelSelect = document.getElementById('geminiModel');
const ondeviceSettings = document.getElementById('ondeviceSettings');
const onDeviceAPISelect = document.getElementById('onDeviceAPI');
const preparseProviderSelect = document.getElementById('preparseProvider');
const errorBanner = document.getElementById('errorBanner');
const statusBanner = document.getElementById('statusBanner');
function showError(msg) {
errorBanner.textContent = msg;
errorBanner.classList.remove('hidden');
hideStatus();
}
function hideError() {
errorBanner.classList.add('hidden');
errorBanner.textContent = '';
}
function showStatus(msg, type = 'status-loading') {
statusBanner.textContent = msg;
statusBanner.className = `status-banner ${type}`;
statusBanner.classList.remove('hidden');
}
function hideStatus() {
statusBanner.classList.add('hidden');
statusBanner.textContent = '';
}
// Initialize on-device model on startup, keep button disabled until ready
(async () => {
const config = await chrome.storage.local.get(['provider']);
if ((config.provider || 'ondevice') === 'ondevice') {
showStatus('Initializing on-device model...', 'status-loading');
const result = await initOnDeviceModel();
summarizeBtn.disabled = false;
if (result.success) {
showStatus('AI model ready.', 'status-info');
setTimeout(hideStatus, 2000);
} else {
showStatus(`On-device AI unavailable: ${result.reason}`, 'status-warn');
}
} else {
summarizeBtn.disabled = false; // Non-ondevice provider — ready immediately
}
})();
let initialSettings = {};
// Navigation
settingsBtn.addEventListener('click', () => {
// Store current state for reset
initialSettings = {
provider: providerSelect.value,
apiKey: apiKeyInput.value,
geminiModel: geminiModelSelect.value,
ollamaUrl: ollamaUrlInput.value,
ollamaModel: ollamaModelSelect.value,
onDeviceAPI: onDeviceAPISelect.value,
useSummarizer: useSummarizerCheckbox.checked,
preparseProvider: preparseProviderSelect.value
};
mainView.classList.add('hidden');
settingsView.classList.remove('hidden');
statusMsg.classList.add('hidden');
if (providerSelect.value === 'ollama') {
loadOllamaModels();
}
});
backBtn.addEventListener('click', () => {
saveSettings(true); // silent save
settingsView.classList.add('hidden');
mainView.classList.remove('hidden');
hideError();
});
// Theme Toggle
const sunIcon = themeBtn.querySelector('.sun-icon');
const moonIcon = themeBtn.querySelector('.moon-icon');
themeBtn.addEventListener('click', () => {
const isLight = document.body.getAttribute('data-theme') === 'light';
if (isLight) {
document.body.removeAttribute('data-theme');
sunIcon?.classList.remove('hidden');
moonIcon?.classList.add('hidden');
chrome.storage.local.set({ theme: 'dark' });
} else {
document.body.setAttribute('data-theme', 'light');
sunIcon?.classList.add('hidden');
moonIcon?.classList.remove('hidden');
chrome.storage.local.set({ theme: 'light' });
}
});
// Font Size Controls
const fontIncBtn = document.getElementById('fontIncBtn');
const fontDecBtn = document.getElementById('fontDecBtn');
let fontSize = 100;
fontIncBtn.addEventListener('click', () => {
if (fontSize < 150) {
fontSize += 10;
document.documentElement.style.fontSize = fontSize + '%';
chrome.storage.local.set({ fontSize });
}
});
fontDecBtn.addEventListener('click', () => {
if (fontSize > 70) {
fontSize -= 10;
document.documentElement.style.fontSize = fontSize + '%';
chrome.storage.local.set({ fontSize });
}
});
useSummarizerCheckbox.addEventListener('change', (e) => {
preparseProviderSelect.disabled = !e.target.checked;
});
// Pop-out
popoutBtn.addEventListener('click', () => {
chrome.runtime.sendMessage({ action: "popout" }, (response) => {
if (response && response.success) {
window.close();
}
});
});
// Provider Toggle
providerSelect.addEventListener('change', (e) => {
toggleProviderSettings(e.target.value);
hideError();
if (e.target.value === 'ollama') {
loadOllamaModels();
}
});
function toggleProviderSettings(provider) {
if (provider === 'gemini') {
geminiSettings.classList.remove('hidden');
ollamaSettings.classList.add('hidden');
ondeviceSettings.classList.add('hidden');
} else if (provider === 'ollama') {
geminiSettings.classList.add('hidden');
ollamaSettings.classList.remove('hidden');
ondeviceSettings.classList.add('hidden');
} else {
// ondevice
geminiSettings.classList.add('hidden');
ollamaSettings.classList.add('hidden');
ondeviceSettings.classList.remove('hidden');
}
}
async function loadOllamaModels(selectedModel = null) {
const baseUrl = ollamaUrlInput.value.trim();
const models = await fetchOllamaModels(baseUrl);
ollamaModelSelect.innerHTML = '';
if (models.length === 0) {
const option = document.createElement('option');
option.value = "";
option.textContent = "No models found. Check URL.";
ollamaModelSelect.appendChild(option);
return;
}
models.forEach(m => {
const option = document.createElement('option');
option.value = m;
option.textContent = m;
ollamaModelSelect.appendChild(option);
});
// Use passed selectedModel or fetch from storage
const targetModel = selectedModel || (await chrome.storage.local.get(['ollamaModel'])).ollamaModel;
if (targetModel && models.includes(targetModel)) {
ollamaModelSelect.value = targetModel;
}
}
refreshOllamaBtn.addEventListener('click', () => loadOllamaModels());
ollamaUrlInput.addEventListener('blur', () => {
if (providerSelect.value === 'ollama' && ollamaUrlInput.value.trim()) {
loadOllamaModels();
}
});
// Load saved settings
chrome.storage.local.get([
'geminiApiKey', 'geminiModel', 'theme', 'fontSize', 'provider', 'ollamaUrl', 'ollamaModel', 'useSummarizer', 'onDeviceAPI', 'preparseProvider'
], (result) => {
if (result.geminiApiKey) apiKeyInput.value = result.geminiApiKey;
if (result.geminiModel) geminiModelSelect.value = result.geminiModel;
const currentProvider = result.provider || 'ondevice';
providerSelect.value = currentProvider;
if (result.ollamaUrl) ollamaUrlInput.value = result.ollamaUrl;
if (result.onDeviceAPI) onDeviceAPISelect.value = result.onDeviceAPI;
useSummarizerCheckbox.checked = result.useSummarizer !== false; // Default to true
preparseProviderSelect.value = result.preparseProvider || 'ondevice';
preparseProviderSelect.disabled = !useSummarizerCheckbox.checked;
toggleProviderSettings(currentProvider);
if (result.theme === 'light') {
document.body.setAttribute('data-theme', 'light');
sunIcon?.classList.add('hidden');
moonIcon?.classList.remove('hidden');
}
if (result.fontSize) {
fontSize = result.fontSize;
document.documentElement.style.fontSize = fontSize + '%';
}
if (result.provider === 'ollama') {
loadOllamaModels(result.ollamaModel);
}
});
// Save Settings
function saveSettings(silent = false) {
const key = apiKeyInput.value.trim();
const geminiModel = geminiModelSelect.value;
const provider = providerSelect.value;
const ollamaUrl = ollamaUrlInput.value.trim();
const ollamaModel = ollamaModelSelect.value;
const onDeviceAPI = onDeviceAPISelect.value;
const useSummarizer = useSummarizerCheckbox.checked;
const preparseProvider = preparseProviderSelect.value;
chrome.storage.local.set({
geminiApiKey: key,
geminiModel: geminiModel,
provider: provider,
ollamaUrl: ollamaUrl,
ollamaModel: ollamaModel,
onDeviceAPI: onDeviceAPI,
useSummarizer: useSummarizer,
preparseProvider: preparseProvider
}, () => {
if (!silent) {
statusMsg.classList.remove('hidden');
setTimeout(() => {
statusMsg.classList.add('hidden');
}, 2000);
}
});
}
saveSettingsBtn.addEventListener('click', () => {
saveSettings();
});
resetSettingsBtn.addEventListener('click', () => {
if (initialSettings.provider) {
providerSelect.value = initialSettings.provider;
apiKeyInput.value = initialSettings.apiKey;
geminiModelSelect.value = initialSettings.geminiModel;
ollamaUrlInput.value = initialSettings.ollamaUrl;
useSummarizerCheckbox.checked = initialSettings.useSummarizer !== false;
if (initialSettings.preparseProvider) preparseProviderSelect.value = initialSettings.preparseProvider;
preparseProviderSelect.disabled = !useSummarizerCheckbox.checked;
toggleProviderSettings(initialSettings.provider);
if (initialSettings.provider === 'ollama') {
loadOllamaModels(initialSettings.ollamaModel);
}
}
});
// Resize functionality
const resizeHandle = document.querySelector('.resize-handle');
if (resizeHandle) {
let isResizing = false;
resizeHandle.addEventListener('mousedown', (e) => {
isResizing = true;
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (!isResizing) return;
const newWidth = e.clientX;
const newHeight = e.clientY;
if (newWidth > 280 && newWidth < 600) {
document.body.style.width = newWidth + 'px';
}
if (newHeight > 150 && newHeight < 800) {
document.body.style.minHeight = newHeight + 'px';
}
});
document.addEventListener('mouseup', () => {
isResizing = false;
});
}
let lastResponseRaw = '';
let lastSummarizerOutput = '';
// Stage 1 modal handlers
const stage1Modal = document.getElementById('stage1Modal');
document.getElementById('viewStage1Btn').addEventListener('click', () => {
document.getElementById('stage1Output').textContent = lastSummarizerOutput;
stage1Modal.classList.remove('hidden');
});
document.getElementById('closeStage1Modal').addEventListener('click', () => {
stage1Modal.classList.add('hidden');
});
stage1Modal.addEventListener('click', (e) => {
if (e.target === stage1Modal) stage1Modal.classList.add('hidden');
});
let currentAbortController = null;
// Summarize Logic
summarizeBtn.addEventListener('click', async () => {
if (currentAbortController) {
currentAbortController.abort();
currentAbortController = null;
resetLoadingState();
hideStatus();
hideError();
return;
}
setLoadingState(true);
resultsDiv.classList.add('hidden');
document.getElementById('stage1Details')?.classList.add('hidden');
hideError();
hideStatus();
showStatus('Summarizing...', 'status-loading');
currentAbortController = new AbortController();
try {
let analysis;
const startTime = performance.now();
if (false) { // Dummy mode disabled
// ... removed
} else {
const config = await chrome.storage.local.get(['geminiApiKey', 'geminiModel', 'provider', 'ollamaUrl', 'ollamaModel', 'useSummarizer', 'onDeviceAPI', 'preparseProvider']);
await checkProviderConnection(config);
const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
if (!tab) throw new Error("Could not find active tab.");
const [{ result: contentResult }] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => {
const selectors = ['#job-description', '.job-description', '#jobDescriptionText', 'main', 'article'];
for (const s of selectors) {
const el = document.querySelector(s);
if (el && el.innerText.length > 200) return el.innerText;
}
return document.body.innerText;
}
});
if (!contentResult) throw new Error("Could not extract page content.");
const stage1OutputEl = document.getElementById('stage1Output');
const stage1Btn = document.getElementById('viewStage1Btn');
const stage1DetailsDiv = document.getElementById('stage1Details');
const parseStage1Output = (text) => {
const fields = {};
const lines = text.split('\n');
for (const line of lines) {
const match = line.match(/^([A-Z\s]+):\s*(.+)$/);
if (match) {
const [, label, value] = match;
const key = label.trim().toLowerCase().replace(/\s+/g, '');
fields[key] = value.trim();
}
}
return fields;
};
const onStage1Done = (text, duration, skipped, stage1Provider) => {
if (skipped) {
showStatus('Extraction skipped', 'status-warn');
return;
}
lastSummarizerOutput = text;
stage1OutputEl.textContent = text;
stage1Btn.classList.remove('hidden');
displayStage1Details(text, stage1Provider);
showStatus(`Extraction done (${stage1Provider}). ${duration}s`, 'status-info');
};
const displayStage1Details = (text, provider) => {
const fields = parseStage1Output(text);
document.getElementById('stage1Title').textContent = fields.title || '---';
document.getElementById('stage1Salary').textContent = fields.salary || '---';
document.getElementById('stage1Location').textContent = fields.location || '---';
document.getElementById('stage1Experience').textContent = fields.experience || '---';
document.getElementById('stage1RoleFocus').textContent = fields.rolefocus || '---';
document.getElementById('stage1Team').textContent = fields.team || '---';
document.getElementById('stage1RequiredSkills').textContent = fields.requiredskills || '---';
document.getElementById('stage1PreferredSkills').textContent = fields.preferredskills || '---';
document.getElementById('stage1KeyResponsibilities').textContent = fields.keyresponsibilities || '---';
document.getElementById('stage1AboutRole').textContent = fields.aboutrole || '---';
if (provider) {
const header = document.querySelector('.stage1-details-grid')?.parentElement;
if (header && !header.querySelector('.stage1-provider')) {
const providerLabel = document.createElement('div');
providerLabel.className = 'stage1-provider';
providerLabel.textContent = `Provider: ${provider}`;
header.insertBefore(providerLabel, header.firstChild);
}
}
stage1DetailsDiv.classList.remove('hidden');
};
const onStage2Start = () => showStatus('Finding job highlights...', 'status-loading');
analysis = await summarizeJob(config, contentResult, currentAbortController.signal, onStage1Done, onStage2Start);
}
lastResponseRaw = analysis.raw || '';
lastSummarizerOutput = analysis.preParsed || '';
const endTime = performance.now();
const duration = ((endTime - startTime) / 1000).toFixed(2);
updateUI(analysis.parsed, duration, analysis.timings);
} catch (error) {
if (error.name === 'AbortError') {
console.log("Evaluation cancelled by user.");
} else {
console.error("Evaluation error:", error);
showError(error.message || "An unexpected error occurred.");
}
} finally {
currentAbortController = null;
setLoadingState(false);
}
});
function setLoadingState(loading) {
if (loading) {
summarizeBtn.classList.add('loading');
btnText.classList.add('hidden');
btnLoader.classList.remove('hidden');
btnCancel.classList.add('hidden'); // hidden by default, CSS shows on hover
summarizeBtn.disabled = false; // Keep enabled to allow clicking 'Cancel'
} else {
summarizeBtn.classList.remove('loading');
btnText.classList.remove('hidden');
btnLoader.classList.add('hidden');
btnCancel.classList.add('hidden');
summarizeBtn.disabled = false;
}
}
function resetLoadingState() {
summarizeBtn.classList.remove('loading');
btnText.classList.remove('hidden');
btnLoader.classList.add('hidden');
btnCancel.classList.add('hidden');
summarizeBtn.disabled = false;
}
function updateUI(data, duration, timings) {
resultsDiv.classList.remove('hidden');
document.getElementById('stage1Details').classList.add('hidden');
hideStatus();
const timeEl = document.getElementById('timeTaken');
if (timings) {
timeEl.textContent = `S1: ${timings.stage1}s | S2: ${timings.stage2}s | Total: ${timings.total}s`;
timeEl.classList.remove('hidden');
} else if (duration) {
timeEl.textContent = `Response in ${duration}s`;
timeEl.classList.remove('hidden');
}
const stage1Btn = document.getElementById('viewStage1Btn');
if (lastSummarizerOutput) {
stage1Btn.classList.remove('hidden');
} else {
stage1Btn.classList.add('hidden');
}
document.getElementById('jobTitle').textContent = data.title || "---";
document.getElementById('salary').textContent = data.salary || "---";
document.getElementById('team').textContent = data.team || "---";
document.getElementById('expReq').textContent = data.expReq || "---";
const summaryContent = document.getElementById('summaryContent');
summaryContent.innerHTML = '';
if (data.summary && typeof data.summary === 'object' && !Array.isArray(data.summary)) {
const s = data.summary;
// Primary Status
if (s.primaryStatus) {
const statusDiv = document.createElement('div');
const matchClass = (s.primaryStatus.match || '').toLowerCase().replace(/[^a-z]/g, '');
statusDiv.className = `highlight-item primary-status-box ${matchClass}`;
statusDiv.innerHTML = `
<div class="status-badge ${matchClass}">${s.primaryStatus.match}</div>
<div class="status-reason">${formatMarkdown(s.primaryStatus.reason)}</div>
`;
summaryContent.appendChild(statusDiv);
}
// Leveling Note
if (s.levelingNote && s.levelingNote !== 'NULL' && s.levelingNote !== 'N/A') {
summaryContent.appendChild(createHighlightItem('Leveling Note', formatMarkdown(s.levelingNote), 'level-note'));
}
// Full Matches
if (s.fullMatches && s.fullMatches.length > 0) {
const list = `<ul>${s.fullMatches.map(m => `<li>${formatMarkdown(m)}</li>`).join('')}</ul>`;
summaryContent.appendChild(createHighlightItem('Full Matches', list, 'matches'));
}
// Partial & Missing
if (s.partialMissing && s.partialMissing.length > 0) {
const list = `<ul>${s.partialMissing.map(m => `<li>${formatMarkdown(m)}</li>`).join('')}</ul>`;
summaryContent.appendChild(createHighlightItem('Partial & Missing', list, 'gaps'));
}
// Unique Insight
if (s.uniqueInsight) {
summaryContent.appendChild(createHighlightItem('Unique Insight', formatMarkdown(s.uniqueInsight), 'insight'));
}
} else if (Array.isArray(data.summary)) {
// Fallback for old format or simple lists
summaryContent.innerHTML = '<ul>' + data.summary.map(item => `<li>${formatMarkdown(item)}</li>`).join('') + '</ul>';
} else {
summaryContent.textContent = data.summary || "No highlights provided.";
}
// Update Square Scale
const score = data.relevanceScore || 0;
const scale = Math.max(1, Math.floor(score)); // 1-5 scale
const container = document.getElementById('scoreSquares');
const squares = container.querySelectorAll('.square');
const text = document.getElementById('scoreText');
// Determine color based on scale
let color = '#ef4444'; // Red for 1/5
let glow = 'rgba(239, 68, 68, 0.5)';
if (scale === 2) { color = '#f97316'; glow = 'rgba(249, 115, 22, 0.5)'; }
else if (scale === 3) { color = '#eab308'; glow = 'rgba(234, 179, 8, 0.5)'; }
else if (scale === 4) { color = '#84cc16'; glow = 'rgba(132, 204, 22, 0.5)'; }
else if (scale === 5) { color = '#10b981'; glow = 'rgba(16, 185, 129, 0.5)'; }
container.style.setProperty('--scale-color', color);
container.style.setProperty('--scale-glow', glow);
squares.forEach((sq, idx) => {
if (idx < scale) {
sq.classList.add('active');
} else {
sq.classList.remove('active');
}
});
text.textContent = `${score}/5`;
text.style.color = color;
}
function createHighlightItem(label, content, className) {
const div = document.createElement('div');
div.className = `highlight-item ${className}`;
div.innerHTML = `
<div class="highlight-label">${label}</div>
<div class="highlight-content">${content}</div>
`;
return div;
}
function formatMarkdown(text) {
if (!text) return '';
return text
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*?)\*/g, '<em>$1</em>')
.replace(/`(.*?)`/g, '<code>$1</code>');
}
});