-
Notifications
You must be signed in to change notification settings - Fork 5
/
popup.js
409 lines (357 loc) · 13.9 KB
/
popup.js
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
const saveButton = document.getElementById('save');
const apiKeyInput = document.getElementById('apiKey');
const hideLowRankTweetsSelect = document.getElementById('hideLowRankTweets');
const colorfulRanksCheckbox = document.getElementById('colorfulRanks');
const pauseResumeButton = document.getElementById('pauseResume');
const toggleApiVisibility = document.querySelector('.toggle-api-visibility');
const MODEL_CONFIGS = {
'gemini-1.5-flash-latest': {
name: 'gemini-1.5-flash (free)',
placeholder: 'Paste your Google AI Studio API key',
apiKeyLink: 'https://aistudio.google.com/app/apikey',
linkText: 'Get your Google AI Studio key',
description: 'Please ensure you are using a Google AI Studio API key for the Gemini model.'
},
'gpt-4o-mini': {
name: 'gpt-4o-mini',
placeholder: 'Paste your OpenAI API key',
apiKeyLink: 'https://platform.openai.com/api-keys',
linkText: 'Get your OpenAI API key',
description: 'Please ensure you are using an OpenAI API key for GPT models.'
},
'gpt-4o': {
name: 'gpt-4o',
placeholder: 'Paste your OpenAI API key',
apiKeyLink: 'https://platform.openai.com/api-keys',
linkText: 'Get your OpenAI API key',
description: 'Please ensure you are using an OpenAI API key for GPT models.'
}
};
const modelSelect = document.getElementById('modelSelect');
const apiKeyLink = document.getElementById('apiKeyLink');
const apiKeyLinkText = document.getElementById('apiKeyLinkText');
class CriteriaManager {
constructor() {
this.criteriaList = document.getElementById('criteria-list');
this.addButton = document.getElementById('add-criteria');
this.originalState = null;
this.setupEventListeners();
// Load initial state and criteria
this.initializeState();
}
// New method to handle initial state loading
initializeState() {
chrome.storage.sync.get(
['geminiApiKey', 'openaiApiKey', 'selectedModel', 'hideLowRankTweets', 'colorfulRanks', 'isPaused', 'rankingCriteria'],
(data) => {
if (data.selectedModel) {
modelSelect.value = data.selectedModel;
} else {
modelSelect.value = 'gemini-1.5-flash-latest';
}
const config = MODEL_CONFIGS[modelSelect.value];
apiKeyInput.placeholder = config.placeholder;
apiKeyLink.href = config.apiKeyLink;
apiKeyLinkText.textContent = config.linkText;
document.getElementById('apiKeyDescription').textContent = config.description;
// Load the appropriate API key based on the selected model
if (modelSelect.value.includes('gemini')) {
if (data.geminiApiKey) {
apiKeyInput.dataset.fullKey = data.geminiApiKey;
apiKeyInput.value = maskApiKey(data.geminiApiKey);
toggleApiVisibility.innerHTML = '<i class="fas fa-eye"></i>';
}
} else {
if (data.openaiApiKey) {
apiKeyInput.dataset.fullKey = data.openaiApiKey;
apiKeyInput.value = maskApiKey(data.openaiApiKey);
toggleApiVisibility.innerHTML = '<i class="fas fa-eye"></i>';
}
}
hideLowRankTweetsSelect.value = data.hideLowRankTweets || '0';
colorfulRanksCheckbox.checked = data.colorfulRanks !== undefined ? data.colorfulRanks : true;
// Load criteria
const defaultCriteria = [{ text: 'Thoughtfulness', weight: 1 }];
const criteria = Array.isArray(data.rankingCriteria) && data.rankingCriteria.length > 0
? data.rankingCriteria
: defaultCriteria;
this.criteriaList.innerHTML = '';
criteria.forEach((criterion, index) => {
const validCriterion = {
text: criterion.text || (index === 0 ? 'Thoughtfulness' : ''),
weight: criterion.weight !== undefined ? criterion.weight : 1
};
this.criteriaList.appendChild(this.createCriteriaItem(validCriterion, index === 0));
});
// Set the original state AFTER everything is initialized
this.originalState = this.getCurrentState();
// Ensure save button is disabled initially
const saveButton = document.getElementById('save');
saveButton.disabled = true;
saveButton.textContent = 'Saved';
}
);
}
getCurrentState() {
return {
apiKey: apiKeyInput.value,
selectedModel: modelSelect.value,
hideLowRankTweets: hideLowRankTweetsSelect.value,
colorfulRanks: colorfulRanksCheckbox.checked,
criteria: this.getCriteria()
};
}
hasStateChanged() {
if (!this.originalState) return false;
const currentState = this.getCurrentState();
if (currentState.apiKey !== this.originalState.apiKey ||
currentState.selectedModel !== this.originalState.selectedModel ||
currentState.hideLowRankTweets !== this.originalState.hideLowRankTweets ||
currentState.colorfulRanks !== this.originalState.colorfulRanks) {
return true;
}
if (currentState.criteria.length !== this.originalState.criteria.length) {
return true;
}
return currentState.criteria.some((criterion, index) => {
const original = this.originalState.criteria[index];
return criterion.text !== original.text || criterion.weight !== original.weight;
});
}
createCriteriaItem(criterion = { text: 'Thoughtfulness', weight: 0 }, isFirst = false) {
const item = document.createElement('div');
item.className = 'criteria-item';
item.setAttribute('data-weight', criterion.weight);
item.innerHTML = `
<div class="criteria-input-container">
<input type="text"
class="criteria-input"
placeholder="${isFirst ? 'Enter main criterion' : 'Enter criterion'}"
value="${criterion.text}"
required>
</div>
<div class="weight-control">
<div class="slider-container">
<label class="weight-label">Weight</label>
<span class="weight-value">${criterion.weight}</span>
<input type="range"
class="weight-slider"
min="0"
max="5"
value="${criterion.weight}"
step="1">
</div>
</div>
<div class="criteria-button-container">
${!isFirst ? `
<button class="criteria-button delete" title="Remove">
<i class="fas fa-times"></i>
</button>
` : `
<div class="criteria-button-placeholder"></div>
`}
</div>
`;
const input = item.querySelector('.criteria-input');
if (!isFirst) {
input.addEventListener('blur', (e) => {
if (e.target.value.trim() === '') {
item.remove();
this.checkForChanges();
}
});
}
input.addEventListener('input', (e) => {
if (e.target.value.trim() === '') {
e.target.classList.add('invalid');
} else {
e.target.classList.remove('invalid');
}
this.checkForChanges();
});
const slider = item.querySelector('.weight-slider');
const weightValue = item.querySelector('.weight-value');
slider.addEventListener('input', (e) => {
const weight = e.target.value;
weightValue.textContent = weight;
item.setAttribute('data-weight', weight);
this.checkForChanges();
});
return item;
}
setupEventListeners() {
this.addButton.addEventListener('click', () => {
const item = this.createCriteriaItem({ text: '', weight: 1 }, false);
this.criteriaList.appendChild(item);
const input = item.querySelector('.criteria-input');
input.focus();
this.checkForChanges();
});
this.criteriaList.addEventListener('click', (e) => {
const item = e.target.closest('.criteria-item');
if (!item) return;
if (e.target.closest('.delete')) {
if (this.criteriaList.children.length > 1) {
item.remove();
this.checkForChanges();
} else {
const input = item.querySelector('.criteria-input');
input.value = 'Thoughtfulness';
const slider = item.querySelector('.weight-slider');
slider.value = 0;
const weightValue = item.querySelector('.weight-value');
weightValue.textContent = '0';
this.checkForChanges();
}
}
});
}
addCriterion() {
const item = this.createCriteriaItem();
this.criteriaList.appendChild(item);
item.querySelector('.criteria-input').focus();
this.checkForChanges();
}
getCriteria() {
return Array.from(this.criteriaList.children)
.map(item => {
const text = item.querySelector('.criteria-input').value.trim();
const weight = parseInt(item.querySelector('.weight-slider').value);
return { text, weight };
})
.filter(c => c.text !== '');
}
checkForChanges() {
const saveButton = document.getElementById('save');
const hasChanges = this.hasStateChanged();
const hasEmptyCriteria = Array.from(this.criteriaList.querySelectorAll('.criteria-input'))
.some(input => input.value.trim() === '');
// Check if at least one criterion has weight > 0
const hasActiveCriterion = Array.from(this.criteriaList.querySelectorAll('.weight-slider'))
.some(slider => parseInt(slider.value) > 0);
const isValid = !hasEmptyCriteria && hasActiveCriterion;
saveButton.disabled = !hasChanges || !isValid;
if (hasEmptyCriteria) {
saveButton.textContent = 'Fill all criteria';
} else if (!hasActiveCriterion) {
saveButton.textContent = 'At least one active criterion needed';
} else {
saveButton.textContent = hasChanges ? 'Save' : 'Saved';
}
}
}
const criteriaManager = new CriteriaManager();
function maskApiKey(key) {
if (!key) return '';
if (key.length <= 8) return key;
const firstPart = key.slice(0, 4);
const lastPart = key.slice(-4);
const middleLength = key.length - 8;
const middlePart = '*'.repeat(middleLength);
return `${firstPart}${middlePart}${lastPart}`;
}
// Handle API key input
apiKeyInput.addEventListener('input', (e) => {
const value = e.target.value;
e.target.dataset.fullKey = value;
criteriaManager.checkForChanges();
});
// Handle visibility toggle
toggleApiVisibility.addEventListener('click', () => {
const fullKey = apiKeyInput.dataset.fullKey || apiKeyInput.value;
const isShowingMasked = apiKeyInput.value.includes('*');
if (isShowingMasked) {
apiKeyInput.value = fullKey;
toggleApiVisibility.innerHTML = '<i class="fas fa-eye-slash"></i>';
} else {
apiKeyInput.value = maskApiKey(fullKey);
toggleApiVisibility.innerHTML = '<i class="fas fa-eye"></i>';
}
});
// Update save button handler
saveButton.addEventListener('click', () => {
const fullKey = apiKeyInput.dataset.fullKey || apiKeyInput.value;
const selectedModel = modelSelect.value;
const hideLowRankTweets = hideLowRankTweetsSelect.value;
const colorfulRanks = colorfulRanksCheckbox.checked;
const criteria = criteriaManager.getCriteria();
// Store API keys separately based on the model
const storageData = {
selectedModel,
hideLowRankTweets,
colorfulRanks,
rankingCriteria: criteria
};
if (selectedModel.includes('gemini')) {
storageData.geminiApiKey = fullKey;
} else {
storageData.openaiApiKey = fullKey;
}
chrome.storage.sync.set(storageData, () => {
chrome.runtime.sendMessage({
action: 'updateApiKey',
apiKey: fullKey,
selectedModel,
criteria: criteria
}, () => {
// Clear rankings when model changes
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.sendMessage(tabs[0].id, { action: 'clearRankings' });
});
criteriaManager.originalState = criteriaManager.getCurrentState();
criteriaManager.checkForChanges();
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.tabs.reload(tabs[0].id);
window.close();
});
});
});
});
hideLowRankTweetsSelect.addEventListener('change', () => criteriaManager.checkForChanges());
colorfulRanksCheckbox.addEventListener('change', () => criteriaManager.checkForChanges());
pauseResumeButton.addEventListener('click', () => {
chrome.storage.sync.get(['isPaused'], (data) => {
const newPausedState = !data.isPaused;
chrome.storage.sync.set({ isPaused: newPausedState }, () => {
if (newPausedState) {
pauseResumeButton.textContent = 'Resume Ranking';
pauseResumeButton.style.backgroundColor = '#4CAF50';
} else {
pauseResumeButton.textContent = 'Pause Ranking';
pauseResumeButton.style.backgroundColor = '#FF9900';
}
chrome.runtime.sendMessage({ action: 'togglePause', isPaused: newPausedState });
});
});
});
// Update model select handler
modelSelect.addEventListener('change', () => {
const selectedModel = modelSelect.value;
const config = MODEL_CONFIGS[selectedModel];
apiKeyInput.placeholder = config.placeholder;
apiKeyLink.href = config.apiKeyLink;
apiKeyLinkText.textContent = config.linkText;
document.getElementById('apiKeyDescription').textContent = config.description;
// Load the appropriate stored API key when switching models
chrome.storage.sync.get(['geminiApiKey', 'openaiApiKey'], (data) => {
if (selectedModel.includes('gemini') && data.geminiApiKey) {
apiKeyInput.dataset.fullKey = data.geminiApiKey;
apiKeyInput.value = maskApiKey(data.geminiApiKey);
} else if (!selectedModel.includes('gemini') && data.openaiApiKey) {
apiKeyInput.dataset.fullKey = data.openaiApiKey;
apiKeyInput.value = maskApiKey(data.openaiApiKey);
} else {
apiKeyInput.dataset.fullKey = '';
apiKeyInput.value = '';
}
toggleApiVisibility.innerHTML = '<i class="fas fa-eye"></i>';
});
criteriaManager.checkForChanges();
});
document.getElementById('openFullSettings').addEventListener('click', (e) => {
e.preventDefault();
chrome.tabs.create({
url: chrome.runtime.getURL('popup.html')
});
window.close();
});