blob: 7b2d93cd63a735478280a8c7d67cf1285d726876 [file] [log] [blame]
Adrià Vilanova Martínezb523be92024-05-25 19:14:19 +02001import {getForceDisabledFeatures} from '../common/options/optionsUtils.js';
Adrià Vilanova Martínez994d1e22023-07-23 01:52:15 +02002
3/**
4 * Watches for changes to an internal kill switch and calls a callback when a
5 * change is detected.
6 */
7export default class InternalKillSwitchWatcher {
8 /**
9 * @param {string} killSwitch - The internal kill switch codename.
10 * @param {changeCallback} callback - The callback which is called when a
11 * change is detected.
12 * @param {boolean} callbackOnFirstLoad - Whether the callback should be
13 * called after first loading which is the current state of the kill
14 * switch.
15 */
16 constructor(killSwitch, callback, callbackOnFirstLoad = true) {
17 this.watchedKillSwitch = killSwitch;
18 this.isActive = null;
19 this.callback = callback;
20 this.#setChangeListener();
21 this.#firstLoadGetValue(callbackOnFirstLoad);
22 }
23
24 #setChangeListener() {
25 chrome.storage.onChanged.addListener((changes, areaName) => {
26 const change = changes?.['_forceDisabledFeatures'];
27 if (areaName !== 'sync' || change === undefined) return;
28 const newValue = change.newValue.includes(this.watchedKillSwitch);
29 const hasChanged = newValue !== this.isActive;
30 this.isActive = newValue;
31 if (hasChanged) this.callback(this.isActive);
32 });
33 }
34
35 async #firstLoadGetValue(callbackOnFirstLoad) {
36 const activeKillSwitches = await getForceDisabledFeatures();
37 this.isActive = activeKillSwitches.includes(this.watchedKillSwitch);
38 if (callbackOnFirstLoad) this.callback(this.isActive);
39 }
40}
41
42/**
43 * Callback which receives changes to the kill switch active state.
44 * @callback changeCallback
45 * @param {boolean} Whether the kill switch is currently active.
46 */