-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptions.js
More file actions
604 lines (522 loc) · 17.5 KB
/
Copy pathoptions.js
File metadata and controls
604 lines (522 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
// BonusVarsler - Options Page
const browser = globalThis.browser || globalThis.chrome;
// Fallback service definitions - canonical source is loaded from feed cache
// These are used when feed is not yet cached.
const SERVICES_FALLBACK = {
trumf: {
id: "trumf",
name: "Trumf",
color: "#4D4DFF",
defaultEnabled: true,
},
sas: {
id: "sas",
name: "SAS EuroBonus",
color: "#0F1E82",
defaultEnabled: false,
},
remember: {
id: "remember",
name: "re:member",
color: "#f28d00",
defaultEnabled: false,
},
dnb: {
id: "dnb",
name: "DNB",
color: "#007272",
defaultEnabled: false,
},
obos: {
id: "obos",
name: "OBOS",
color: "#0047ba",
type: "info",
},
naf: {
id: "naf",
name: "NAF",
color: "#c9a000",
type: "info",
},
lofavor: {
id: "lofavor",
name: "LOfavør",
color: "#66083c",
type: "info",
},
logbuy: {
id: "logbuy",
name: "Visma LogBuy",
color: "#ee2e24",
},
};
// Mutate this registry in place so Object.keys(SERVICES) keeps fallback order.
let SERVICES = { ...SERVICES_FALLBACK };
// Storage keys
const KEYS = {
hiddenSites: "BonusVarsler_HiddenSites",
blacklistedSites: "BonusVarsler_BlacklistedSites",
theme: "BonusVarsler_Theme",
startMinimized: "BonusVarsler_StartMinimized",
position: "BonusVarsler_Position",
sitePositions: "BonusVarsler_SitePositions",
feedData: "BonusVarsler_FeedData_v1",
feedTime: "BonusVarsler_FeedTime_v1",
hostIndex: "BonusVarsler_HostIndex_v1",
language: "BonusVarsler_Language",
enabledServices: "BonusVarsler_EnabledServices",
};
// Messages cache
let messages = {};
let currentLang = "no";
// Load messages for a specific language
async function loadMessages(lang) {
try {
const url = browser.runtime.getURL(`_locales/${lang}/messages.json`);
const response = await fetch(url);
return await response.json();
} catch {
return {};
}
}
// i18n helper with placeholder support
function i18n(messageName, substitutions) {
const entry = messages[messageName];
if (!entry || !entry.message) {
return messageName;
}
let msg = entry.message;
// Handle substitutions
if (substitutions !== undefined) {
const subs = Array.isArray(substitutions) ? substitutions : [substitutions];
subs.forEach((sub, index) => {
const placeholder = `$${index + 1}`;
msg = msg.replace(placeholder, sub);
// Also handle named placeholders
if (entry.placeholders) {
for (const [name, config] of Object.entries(entry.placeholders)) {
if (config.content === placeholder) {
msg = msg.replace(new RegExp(`\\$${name.toUpperCase()}\\$`, "g"), sub);
}
}
}
});
}
return msg;
}
// Translate all elements with data-i18n attributes
function translatePage() {
// Translate text content
document.querySelectorAll("[data-i18n]").forEach((el) => {
const key = el.getAttribute("data-i18n");
const message = i18n(key);
if (message && message !== key) {
el.textContent = message;
}
});
// Translate titles
document.querySelectorAll("[data-i18n-title]").forEach((el) => {
const key = el.getAttribute("data-i18n-title");
const message = i18n(key);
if (message && message !== key) {
el.title = message;
}
});
// Translate aria-labels
document.querySelectorAll("[data-i18n-aria]").forEach((el) => {
const key = el.getAttribute("data-i18n-aria");
const message = i18n(key);
if (message && message !== key) {
el.setAttribute("aria-label", message);
}
});
// Translate placeholders
document.querySelectorAll("[data-i18n-placeholder]").forEach((el) => {
const key = el.getAttribute("data-i18n-placeholder");
const message = i18n(key);
if (message && message !== key) {
el.placeholder = message;
}
});
// Update page title
document.title = i18n("optionsTitle");
}
// Get value from storage
async function getValue(key, defaultValue) {
try {
const result = await browser.storage.local.get(key);
return result[key] !== undefined ? result[key] : defaultValue;
} catch {
return defaultValue;
}
}
// Set value in storage
async function setValue(key, value) {
try {
await browser.storage.local.set({ [key]: value });
} catch {
console.error("Failed to save setting:", key);
}
}
// Show status message
function showStatus(message) {
let statusEl = document.querySelector(".status-message");
if (!statusEl) {
statusEl = document.createElement("div");
statusEl.className = "status-message";
document.body.appendChild(statusEl);
}
statusEl.textContent = message;
statusEl.classList.add("visible");
setTimeout(() => {
statusEl.classList.remove("visible");
}, 2000);
}
/**
* Wire up language selection buttons and apply the selected language to the UI.
*
* Attaches click handlers to buttons under `#language-buttons .theme-btn`. When a different
* language is chosen, the selection is persisted to storage, `currentLang` and `messages`
* are updated, the page is retranslated, the services UI is reinitialized, and a save status
* message is shown. Clicks that select the already-active language are ignored.
*/
async function initLanguage() {
const buttons = document.querySelectorAll("#language-buttons .theme-btn");
buttons.forEach((btn) => {
if (btn.dataset.lang === currentLang) {
btn.classList.add("active");
}
btn.addEventListener("click", async () => {
const newLang = btn.dataset.lang;
if (newLang === currentLang) return;
buttons.forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
await setValue(KEYS.language, newLang);
currentLang = newLang;
messages = await loadMessages(newLang);
translatePage();
await initServices();
showStatus(i18n("languageSaved"));
});
});
}
// Initialize theme buttons
async function initTheme() {
const currentTheme = await getValue(KEYS.theme, "light");
const buttons = document.querySelectorAll("#theme-buttons .theme-btn");
buttons.forEach((btn) => {
if (btn.dataset.theme === currentTheme) {
btn.classList.add("active");
}
btn.addEventListener("click", async () => {
buttons.forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
await setValue(KEYS.theme, btn.dataset.theme);
showStatus(i18n("themeSaved"));
});
});
}
// Initialize start minimized toggle
async function initStartMinimized() {
const startMinimized = await getValue(KEYS.startMinimized, true);
const toggle = document.getElementById("start-minimized");
if (startMinimized) {
toggle.classList.add("active");
}
toggle.addEventListener("click", async () => {
const isActive = toggle.classList.toggle("active");
await setValue(KEYS.startMinimized, isActive);
showStatus(isActive ? i18n("startMinimizedEnabled") : i18n("startMinimizedDisabled"));
});
}
// Initialize position buttons
async function initPosition() {
const currentPosition = await getValue(KEYS.position, "bottom-right");
const buttons = document.querySelectorAll("#position-buttons .position-btn");
buttons.forEach((btn) => {
if (btn.dataset.position === currentPosition) {
btn.classList.add("active");
}
btn.addEventListener("click", async () => {
buttons.forEach((b) => b.classList.remove("active"));
btn.classList.add("active");
await setValue(KEYS.position, btn.dataset.position);
showStatus(i18n("positionSaved"));
});
});
}
// Initialize hidden sites
async function initHiddenSites() {
const hiddenSites = await getValue(KEYS.hiddenSites, []);
const container = document.getElementById("hidden-sites-container");
const list = document.getElementById("hidden-sites-list");
const actions = document.getElementById("hidden-sites-actions");
function render() {
list.innerHTML = "";
if (hiddenSites.length === 0) {
container.style.display = "block";
actions.style.display = "none";
return;
}
container.style.display = "none";
actions.style.display = "block";
hiddenSites.forEach((site, index) => {
const item = document.createElement("div");
item.className = "hidden-site-item";
const name = document.createElement("span");
name.className = "hidden-site-name";
name.textContent = site;
const removeBtn = document.createElement("button");
removeBtn.className = "remove-site-btn";
removeBtn.textContent = "×";
removeBtn.title = i18n("remove");
removeBtn.addEventListener("click", async () => {
hiddenSites.splice(index, 1);
await setValue(KEYS.hiddenSites, hiddenSites);
render();
showStatus(i18n("siteRemoved", site));
});
item.appendChild(name);
item.appendChild(removeBtn);
list.appendChild(item);
});
}
render();
// Reset all hidden sites
document.getElementById("reset-hidden-sites").addEventListener("click", async () => {
if (confirm(i18n("confirmResetHiddenSites"))) {
hiddenSites.length = 0;
await setValue(KEYS.hiddenSites, []);
render();
showStatus(i18n("allHiddenSitesRemoved"));
}
});
}
// Initialize blacklisted sites
async function initBlacklistedSites() {
const storedBlacklist = await getValue(KEYS.blacklistedSites, []);
const blacklistedSites = Array.isArray(storedBlacklist) ? storedBlacklist : [];
const container = document.getElementById("blacklist-container");
const list = document.getElementById("blacklist-list");
const actions = document.getElementById("blacklist-actions");
const input = document.getElementById("blacklist-input");
const addBtn = document.getElementById("blacklist-add-btn");
function normalizeHost(host) {
let normalized = String(host).trim().toLowerCase();
normalized = normalized.replace(/^https?:\/\//, "");
normalized = normalized.split("/")[0].split("?")[0].split("#")[0];
normalized = normalized.split(":")[0];
if (normalized.startsWith("www.")) {
normalized = normalized.slice(4);
}
normalized = normalized.replace(/^\.+|\.+$/g, "");
return normalized;
}
// Normalize and deduplicate stored values to keep matching consistent
const normalizedStored = Array.from(
new Set(
blacklistedSites
.map((site) => normalizeHost(site))
.filter(Boolean)
)
);
if (
normalizedStored.length !== blacklistedSites.length ||
normalizedStored.some((site, index) => site !== blacklistedSites[index])
) {
blacklistedSites.length = 0;
blacklistedSites.push(...normalizedStored);
await setValue(KEYS.blacklistedSites, blacklistedSites);
}
function render() {
list.innerHTML = "";
if (blacklistedSites.length === 0) {
container.style.display = "block";
actions.style.display = "none";
return;
}
container.style.display = "none";
actions.style.display = "block";
blacklistedSites.forEach((site, index) => {
const item = document.createElement("div");
item.className = "blacklist-item";
const name = document.createElement("span");
name.className = "blacklist-name";
name.textContent = site;
const removeBtn = document.createElement("button");
removeBtn.className = "remove-site-btn";
removeBtn.textContent = "×";
removeBtn.title = i18n("remove");
removeBtn.addEventListener("click", async () => {
blacklistedSites.splice(index, 1);
await setValue(KEYS.blacklistedSites, blacklistedSites);
render();
showStatus(i18n("siteUnblacklisted", site));
});
item.appendChild(name);
item.appendChild(removeBtn);
list.appendChild(item);
});
}
render();
// Add site to blacklist
async function addSite() {
const normalized = normalizeHost(input.value);
// Basic validation - must look like a domain
if (!normalized || normalized.includes(" ")) {
showStatus(i18n("invalidDomain"));
return;
}
if (blacklistedSites.includes(normalized)) {
showStatus(i18n("siteAlreadyBlacklisted"));
return;
}
blacklistedSites.push(normalized);
await setValue(KEYS.blacklistedSites, blacklistedSites);
input.value = "";
render();
showStatus(i18n("siteBlacklisted", normalized));
}
addBtn.addEventListener("click", addSite);
input.addEventListener("keypress", (e) => {
if (e.key === "Enter") {
addSite();
}
});
// Reset all blacklisted sites
document.getElementById("reset-blacklist").addEventListener("click", async () => {
if (confirm(i18n("confirmResetBlacklist"))) {
blacklistedSites.length = 0;
await setValue(KEYS.blacklistedSites, []);
render();
showStatus(i18n("allBlacklistedSitesRemoved"));
}
});
}
/**
* Render and manage service enable checkboxes in the options UI.
*
* Renders services in the merged SERVICES insertion order, preferring a per-service i18n name with a fallback to the service's `name`. Persists the list of enabled services to storage when changed and prevents disabling all non-"coming soon" services by reverting the last uncheck and showing a status message.
*/
async function initServices() {
const container = document.getElementById("services-list");
if (!container) return;
container.textContent = "";
// Get default enabled services
const defaultEnabled = Object.values(SERVICES)
.filter((s) => s.defaultEnabled)
.map((s) => s.id);
// Load enabled services from storage
let enabledServices = await getValue(KEYS.enabledServices, null);
if (!enabledServices) {
enabledServices = defaultEnabled;
}
// Service order follows the merged service registry insertion order.
const serviceOrder = Object.keys(SERVICES);
// Create checkbox for each service
serviceOrder.forEach((serviceId) => {
const service = SERVICES[serviceId];
if (!service) return;
const row = document.createElement("div");
row.className = "service-row";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = `service-${service.id}`;
checkbox.checked = enabledServices.includes(service.id);
const label = document.createElement("label");
label.htmlFor = `service-${service.id}`;
label.className = "service-label";
const colorDot = document.createElement("span");
colorDot.className = "service-color";
colorDot.style.backgroundColor = service.color;
const nameSpan = document.createElement("span");
nameSpan.className = "service-name";
const i18nKey = `${service.id}Name`;
const localizedServiceName = i18n(i18nKey);
nameSpan.textContent = localizedServiceName && localizedServiceName !== i18nKey
? localizedServiceName
: service.name;
label.appendChild(colorDot);
label.appendChild(nameSpan);
// Add "coming soon" text for placeholder services
if (service.comingSoon) {
const comingSoon = document.createElement("span");
comingSoon.className = "coming-soon";
comingSoon.textContent = i18n("comingSoon");
label.appendChild(comingSoon);
}
row.appendChild(checkbox);
row.appendChild(label);
container.appendChild(row);
// Handle checkbox change
checkbox.addEventListener("change", async () => {
const checkboxes = container.querySelectorAll('input[type="checkbox"]');
// Count only active (non-coming-soon) services
const checkedActiveCount = Array.from(checkboxes).filter((cb) => {
const serviceId = cb.id.replace("service-", "");
const service = SERVICES[serviceId];
return cb.checked && service && !service.comingSoon;
}).length;
// Prevent disabling all active services
if (checkedActiveCount === 0) {
checkbox.checked = true;
showStatus(i18n("cannotDisableAllServices"));
return;
}
// Update enabled services
const newEnabled = Array.from(checkboxes)
.filter((cb) => cb.checked)
.map((cb) => cb.id.replace("service-", ""));
await setValue(KEYS.enabledServices, newEnabled);
showStatus(i18n("servicesSaved"));
});
});
}
// Initialize clear cache
function initClearCache() {
document.getElementById("clear-cache").addEventListener("click", async () => {
await setValue(KEYS.feedData, null);
await setValue(KEYS.feedTime, null);
await setValue(KEYS.hostIndex, null);
showStatus(i18n("cacheCleared"));
});
}
// Initialize version display
function initVersion() {
const manifest = browser.runtime.getManifest();
document.querySelector(".version").textContent = `v${manifest.version}`;
}
// Load services from feed cache (canonical source)
async function loadServicesFromFeed() {
try {
const feedData = await getValue(KEYS.feedData, null);
if (feedData?.services && typeof feedData.services === "object") {
// Merge feed services with fallback (feed overrides, but missing fields preserved)
for (const [id, service] of Object.entries(feedData.services)) {
const fallback = SERVICES[id] || {};
SERVICES[id] = { ...fallback, ...service, id };
}
}
} catch {
// Use fallback services
}
}
// Initialize everything
document.addEventListener("DOMContentLoaded", async () => {
// Load language preference and messages first
currentLang = await getValue(KEYS.language, "no");
messages = await loadMessages(currentLang);
// Load services from feed cache (canonical source)
await loadServicesFromFeed();
translatePage();
initVersion();
initLanguage();
initTheme();
initStartMinimized();
initPosition();
initServices();
initHiddenSites();
initBlacklistedSites();
initClearCache();
});