import { PubSub } from "./libs/pubsub" ; import { autoinject } from "./libs/container" ; import { EVENT_SETTINGS_CHANGED } from "./constants" ; declare const chrome , browser ; export interface ISettings { 'single-change' : boolean ; 'file-sort' : number ; 'panel-width' : number ; } @ autoinject export class SettingsStore { public onceReady ; private storage = ( chrome || browser ) . storage . local ; private defaultValues : ISettings = { 'single-change' : true , 'file-sort' : 2 , 'panel-width' : 250 , } ; private state : ISettings = this . defaultValues ; constructor ( private pubsub ) { this . onceReady = this . pullSettings ( ) ; } private setState ( newState ) { this . state = Object . assign ( { } , this . state , newState ) ; } pullSettings ( ) { return new Promise ( ( resolve , reject ) => { const callback = values => { const newState = Object . assign ( { } , this . state ) ; Object . keys ( values ) . forEach ( key => { if ( values . hasOwnProperty ( key ) ) { const value = values [ key ] ; if ( value !== undefined || value !== null ) { newState [ key ] = value ; } } } ) ; this . setState ( newState ) ; resolve ( newState ) ; } ; const keys = Object . keys ( this . defaultValues ) ; const storage = this . storage . get ( keys , callback ) ; if ( storage && storage . then ) { storage . then ( callback ) ; } } ) ; } pushSettings ( settings ) { this . setState ( settings ) ; this . storage . set ( this . state ) ; this . pubsub . publish ( EVENT_SETTINGS_CHANGED , Object . assign ( { } , this . state ) ) ; } get ( name ) { return this . state [ name ] ; } getAll ( ) { return Object . assign ( { } , this . state ) ; } }