UNPKG

@ima/plugin-analytic

Version:

Seznam IMA.js abstract analytic plugin

91 lines (90 loc) 2.77 kB
import { ScriptLoaderPlugin } from '@ima/plugin-script-loader'; import { Events as AnalyticEvents } from './Events'; /** * Abstract analytic class */ export class AbstractAnalytic { #scriptLoader; #dispatcher; // If flag has value true then analytic script was loaded. #loaded = false; _window; _analyticScriptName = null; // Analytic script url. _analyticScriptUrl = null; // If flag has value true then analytic is enabled to hit events. _enable = false; static get $dependencies() { return [ ScriptLoaderPlugin, '$Window', '$Dispatcher' ]; } constructor(scriptLoader, window, dispatcher){ this.#scriptLoader = scriptLoader; this._window = window; this.#dispatcher = dispatcher; } /** * Initialization analytic. * * @function init * @param initConfig * @param initConfig.purposeConsents Purpose Consents of TCModel, see: https://www.npmjs.com/package/@iabtcf/core#tcmodel */ init(initConfig) { if (!this.isEnabled() && this._window.isClient()) { // we are on client, therefore window is defined const window = this._window.getWindow(); if (initConfig?.purposeConsents) { this._applyPurposeConsents(initConfig.purposeConsents); } this._createGlobalDefinition(window); this._fireLifecycleEvent(AnalyticEvents.INITIALIZED); } } /** * Load analytic script, configure analytic and execute deferred hits. */ load() { if (this._window.isClient()) { if (this.isLoaded()) { return Promise.resolve(true); } if (!this._analyticScriptUrl) { this.#afterLoadCallback(); return Promise.resolve(true); } return this.#scriptLoader.load(this._analyticScriptUrl).then(()=>{ this.#afterLoadCallback(); return true; }).catch((error)=>{ console.error(error); }); } return Promise.resolve(false); } /** * Returns true if analytic is enabled. */ isEnabled() { return this._enable; } /** * Returns true if analytic is loaded. * @protected */ isLoaded() { return this.#loaded; } #afterLoadCallback() { this.#loaded = true; this._configuration(); this._fireLifecycleEvent(AnalyticEvents.LOADED); } /** * @protected * @param eventType */ _fireLifecycleEvent(eventType) { this.#dispatcher.fire(eventType, { type: this._analyticScriptName }); } } //# sourceMappingURL=AbstractAnalytic.js.map