import { action , observable } from 'mobx' ; import { browser } from 'webextension-polyfill-ts' ; export interface SyncStorage { hide_descriptions : boolean ; max_suggestions : number ; operator_blacklist : string [ ] ; } class Storage { @ observable . ref public isLoading : boolean = true ; @ observable . ref public hideDescriptions ? : boolean | null = null ; @ observable . ref public maxSuggestions ? : number | null = null ; @ observable . ref public operatorBlacklist ? : string [ ] = [ ] ; return @ action . bound public async fetchStorage ( ) { let storage ; storage = await browser . storage . sync . get ( ) ; if ( ! storage . max_suggestions || ! storage . hide_descriptions || ! storage . operator_blacklist ) { storage = await this . initializeStorage ( ) ; } this . isLoading = false ; this . hideDescriptions = storage . hide_descriptions ; this . maxSuggestions = storage . max_suggestions ; this . operatorBlacklist = storage . operator_blacklist ; } return @ action protected async initializeStorage ( ) { const initialStorage = { hide_descriptions : false , max_suggestions : 5 , operator_blacklist : [ ] , } ; await browser . storage . sync . set ( initialStorage ) ; return initialStorage ; } param value return @ action . bound public async toggleDescriptionVisibility ( value ) { await browser . storage . sync . set ( { hide_descriptions : value } ) ; const { hide_descriptions } = await browser . storage . sync . get ( 'hide_descriptions' ) ; this . hideDescriptions = hide_descriptions ; } param value return @ action . bound public async changeMaxSuggestions ( value ) { await browser . storage . sync . set ( { max_suggestions : value } ) ; const { max_suggestions } = await browser . storage . sync . get ( 'max_suggestions' ) ; this . maxSuggestions = max_suggestions ; } param id return @ action . bound public async addOperatorsToBlacklist ( id ) { const mergedBlacklist = [ ... this . operatorBlacklist || [ ] , id ] ; await browser . storage . sync . set ( { operator_blacklist : mergedBlacklist } ) ; const { operator_blacklist : newBlacklist , } = await browser . storage . sync . get ( 'operator_blacklist' ) ; this . operatorBlacklist = newBlacklist ; } param id return @ action . bound public async removeOperatorsFromBlacklist ( id ) { const mergedBlacklist = ( this . operatorBlacklist || [ ] ) . filter ( ( item ) => item !== id ) ; await browser . storage . sync . set ( { operator_blacklist : mergedBlacklist } ) ; const { operator_blacklist : newBlacklist , } = await browser . storage . sync . get ( 'operator_blacklist' ) ; this . operatorBlacklist = newBlacklist ; } } export const storage = new Storage ( ) ;