|
| 1 | +import {uiFactory} from '../uiFactory/uiFactory'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Interface for a counter that provides methods for tracking metrics. |
| 5 | + * |
| 6 | + * @method hit - Tracks a hit event with optional arguments. https://yandex.ru/support/metrica/ru/objects/hit |
| 7 | + * @method params - Sets parameters for the counter with optional arguments. https://yandex.ru/support/metrica/ru/objects/params-method |
| 8 | + * @method userParams - Sets user-specific parameters for the counter with optional arguments. https://yandex.ru/support/metrica/ru/objects/user-params |
| 9 | + * @method reachGoal - Tracks a goal achievement event with optional arguments. https://yandex.ru/support/metrica/ru/objects/reachgoal |
| 10 | + */ |
| 11 | +export interface Counter { |
| 12 | + hit: (...args: unknown[]) => void; |
| 13 | + params: (...args: unknown[]) => void; |
| 14 | + userParams: (...args: unknown[]) => void; |
| 15 | + reachGoal: (...args: unknown[]) => void; |
| 16 | +} |
| 17 | + |
| 18 | +const yaMetricaMap = uiFactory.yaMetricaMap; |
| 19 | + |
| 20 | +/** |
| 21 | + * A fake implementation of a counter metric for Yandex.Metrica. |
| 22 | + * This class is used when the actual Yandex.Metrica counter is not defined, |
| 23 | + * and it provides a warning message the first time any of its methods are called. |
| 24 | + * |
| 25 | + * @property name - The name of the counter. |
| 26 | + * @property warnShown - Flag to indicate if the warning has been shown. |
| 27 | + */ |
| 28 | +class FakeMetrica implements Counter { |
| 29 | + name: string; |
| 30 | + |
| 31 | + private warnShown = false; |
| 32 | + |
| 33 | + constructor(name: string) { |
| 34 | + this.name = name; |
| 35 | + } |
| 36 | + |
| 37 | + hit() { |
| 38 | + this.warnOnce(); |
| 39 | + } |
| 40 | + |
| 41 | + params() { |
| 42 | + this.warnOnce(); |
| 43 | + } |
| 44 | + |
| 45 | + userParams() { |
| 46 | + this.warnOnce(); |
| 47 | + } |
| 48 | + |
| 49 | + reachGoal() { |
| 50 | + this.warnOnce(); |
| 51 | + } |
| 52 | + |
| 53 | + private warnOnce() { |
| 54 | + if (!this.warnShown) { |
| 55 | + console.warn(`Yandex.Metrica counter "${this.name}" is not defined\n`); |
| 56 | + this.warnShown = true; |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + * Retrieves a Yandex Metrica instance by name from the global window object. |
| 63 | + * If no instance is found for the given name, returns a FakeMetrica instance instead. |
| 64 | + * |
| 65 | + * @param name The name of the metrica to retrieve |
| 66 | + * @returns The Yandex Metrica instance if found, otherwise a FakeMetrica instance |
| 67 | + */ |
| 68 | +export function getMetrica(name: string) { |
| 69 | + const yaMetricaId = yaMetricaMap?.[name]; |
| 70 | + const metricaInstance = yaMetricaId |
| 71 | + ? (window[`yaCounter${yaMetricaId}`] as Counter) |
| 72 | + : undefined; |
| 73 | + |
| 74 | + return metricaInstance ?? new FakeMetrica(name); |
| 75 | +} |
0 commit comments