/**
 * Storing global state in local module variables has issues when more than one copy
 * if the module gets loaded on the page (due to a bundling error or simply by consuming
 * a prebundled script.)
 *
 * This file contains helpers to deal with the getting and setting local state, and allows
 * callers to get called back when it mutates.
 */ const GLOBAL_SETTINGS_PROP_NAME = '__globalSettings__' ; const CALLBACK_STATE_PROP_NAME = '__callbacks__' ; let _global ; let _counter = 0 ; if ( typeof window !== 'undefined' ) { _global = window ; } else if ( typeof global !== 'undefined' ) { _global = global ; } else { _global = { } ; } let _globalSettings = ( _global [ GLOBAL_SETTINGS_PROP_NAME ] = _global [ GLOBAL_SETTINGS_PROP_NAME ] || { [ CALLBACK_STATE_PROP_NAME ] : { } } ) ; const _callbacks = _globalSettings [ CALLBACK_STATE_PROP_NAME ] ; public export interface IChangeDescription { key : string ; oldValue : any ; value : any ; } public export interface IChangeEventCallback { __id__ ? : string ; ( changeDescription ? ) : void ; } public export class GlobalSettings { public static getValue < T > ( key , defaultValue ? ) { if ( _globalSettings [ key ] === undefined ) { _globalSettings [ key ] = typeof defaultValue === 'function' ? defaultValue ( ) : defaultValue ; } return _globalSettings [ key ] ; } public static setValue < T > ( key , value ) { let oldValue = _globalSettings [ key ] ; if ( value !== oldValue ) { _globalSettings [ key ] = value ; let changeDescription = { oldValue , value , key } ; for ( let id in _callbacks ) { if ( _callbacks . hasOwnProperty ( id ) ) { _callbacks [ id ] ( changeDescription ) ; } } } return value ; } public static addChangeListener ( cb ) { let id = cb . __id__ ; if ( ! id ) { id = cb . __id__ = String ( _counter ++ ) ; } _callbacks [ id ] = cb ; } public static removeChangeListener ( cb ) { delete _callbacks [ cb . __id__ as string ] ; } }