|
|
|
|
|
|
|
|
import debug from 'debug'; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const queueDebug = debug( 'calypso:analytics:queue' ); |
|
|
|
|
|
|
|
|
|
|
|
const modules = { |
|
|
signup: () => asyncRequire( 'calypso/lib/analytics/signup' ), |
|
|
}; |
|
|
|
|
|
const lsKey = () => 'analyticsQueue'; |
|
|
|
|
|
function clear() { |
|
|
if ( ! window.localStorage ) { |
|
|
return; |
|
|
} |
|
|
|
|
|
try { |
|
|
window.localStorage.removeItem( lsKey() ); |
|
|
} catch { |
|
|
|
|
|
} |
|
|
} |
|
|
|
|
|
function get() { |
|
|
if ( ! window.localStorage ) { |
|
|
return []; |
|
|
} |
|
|
|
|
|
try { |
|
|
let items = window.localStorage.getItem( lsKey() ); |
|
|
|
|
|
items = items ? JSON.parse( items ) : []; |
|
|
items = Array.isArray( items ) ? items : []; |
|
|
|
|
|
return items; |
|
|
} catch { |
|
|
return []; |
|
|
} |
|
|
} |
|
|
|
|
|
function runTrigger( moduleName, trigger, ...args ) { |
|
|
if ( 'string' === typeof trigger && 'function' === typeof modules[ moduleName ] ) { |
|
|
modules[ moduleName ]().then( ( mod ) => { |
|
|
if ( 'function' === typeof mod[ trigger ] ) { |
|
|
mod[ trigger ].apply( null, args || undefined ); |
|
|
} |
|
|
} ); |
|
|
} |
|
|
return; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function addToQueue( moduleName, trigger, ...args ) { |
|
|
if ( ! window.localStorage ) { |
|
|
|
|
|
return runTrigger( moduleName, trigger, ...args ); |
|
|
} |
|
|
|
|
|
try { |
|
|
let items = get(); |
|
|
const newItem = { moduleName, trigger, args }; |
|
|
|
|
|
items.push( newItem ); |
|
|
items = items.slice( -100 ); |
|
|
|
|
|
queueDebug( 'Adding new item to queue.', newItem ); |
|
|
window.localStorage.setItem( lsKey(), JSON.stringify( items ) ); |
|
|
} catch { |
|
|
|
|
|
return runTrigger( moduleName, trigger, ...args ); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function processQueue() { |
|
|
if ( ! window.localStorage ) { |
|
|
return; |
|
|
} |
|
|
|
|
|
const items = get(); |
|
|
clear(); |
|
|
|
|
|
queueDebug( 'Processing items in queue.', items ); |
|
|
|
|
|
items.forEach( ( item ) => { |
|
|
if ( 'object' === typeof item && 'string' === typeof item.trigger ) { |
|
|
queueDebug( 'Processing item in queue.', item ); |
|
|
runTrigger( item.moduleName, item.trigger, ...item.args ); |
|
|
} |
|
|
} ); |
|
|
} |
|
|
|