Adrià Vilanova MartÃnez | 994d1e2 | 2023-07-23 01:52:15 +0200 | [diff] [blame] | 1 | import {getForceDisabledFeatures} from '../common/optionsUtils.js'; |
| 2 | |
| 3 | /** |
| 4 | * Watches for changes to an internal kill switch and calls a callback when a |
| 5 | * change is detected. |
| 6 | */ |
| 7 | export 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 | */ |