All files / src/libs/settings settings.ts

100% Statements 19/19
66.66% Branches 4/6
100% Functions 6/6
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                              5x   5x 11x 11x 11x     11x       5x 13x 13x       5x           5x       15x       11x   11x   11x 8x 8x 8x         5x  
import {configure} from '@gravity-ui/uikit';
import get from 'lodash/get';
import mergeWith from 'lodash/mergeWith';
 
import {i18nFactory} from '../../i18n';
import type {ChartKitHolidays, ChartKitLang, ChartKitPlugin} from '../../types';
 
import {EventEmitter} from './eventEmitter';
import {mergeSettingStrategy} from './mergeSettingStrategy';
 
interface Settings {
    plugins: ChartKitPlugin[];
    lang: ChartKitLang;
    extra?: {
        holidays?: ChartKitHolidays;
    };
}
 
type SettingKey = keyof Settings;
type SettingsEventsMap = {
    'change-lang': ChartKitLang;
};
 
export const settingsEventEmitter = new EventEmitter<SettingsEventsMap>();
 
const removeUndefinedValues = <T extends Record<string, any>>(data: T) => {
    return Object.entries(data).reduce((acc, [key, value]) => {
        Eif (typeof value !== 'undefined') {
            acc[key as keyof T] = value;
        }
 
        return acc;
    }, {} as T);
};
 
const updateLang = (lang: ChartKitLang) => {
    configure({lang});
    i18nFactory.setLang(lang);
};
 
class ChartKitSettings {
    private settings: Settings = {
        plugins: [],
        lang: 'en',
    };
 
    constructor() {
        updateLang(this.get('lang'));
    }
 
    get<T extends SettingKey>(key: T) {
        return get(this.settings, key);
    }
 
    set(updates: Partial<Settings>) {
        const filteredUpdates = removeUndefinedValues(updates);
 
        this.settings = mergeWith(this.settings, filteredUpdates, mergeSettingStrategy);
 
        if (filteredUpdates.lang) {
            const lang = filteredUpdates.lang || this.get('lang');
            updateLang(lang);
            settingsEventEmitter.dispatch('change-lang', lang);
        }
    }
}
 
export const settings = new ChartKitSettings();