Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat!: change moment to date-utils #198

Merged
merged 3 commits into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
{
"extends": ["@gravity-ui/eslint-config", "@gravity-ui/eslint-config/client"],
"extends": [
"@gravity-ui/eslint-config",
"@gravity-ui/eslint-config/client",
"@gravity-ui/eslint-config/prettier"
],
"root": true
}
18 changes: 12 additions & 6 deletions .storybook/decorators/withLang.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import React from 'react';
import type {DecoratorFn} from '@storybook/react';
import type {Decorator} from '@storybook/react';
import {Lang, configure} from '@gravity-ui/uikit';
import {settings as dateUtilsSettings} from '@gravity-ui/date-utils';
import {settings as chartkitSettings} from '../../src/libs';

export const withLang: DecoratorFn = (Story, context) => {
const lang = context.globals.lang;
const setDateUtilsLocale = async (lang: string) => {
await dateUtilsSettings.loadLocale(lang);
dateUtilsSettings.setLocale(lang);
};

configure({
lang: lang as Lang,
});
export const withLang: Decorator = (Story, context) => {
const lang = context.globals.lang;
chartkitSettings.set({lang});
setDateUtilsLocale(lang);
configure({lang: lang as Lang});

return <Story key={lang} {...context} />;
};
26 changes: 15 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"access": "public"
},
"dependencies": {
"@gravity-ui/date-utils": "^1.4.1",
"@gravity-ui/yagr": "^3.3.4",
"bem-cn-lite": "^4.1.0",
"highcharts": "^8.2.2",
Expand Down Expand Up @@ -54,7 +55,6 @@
"jest": "^28.1.3",
"jest-environment-jsdom": "^28.1.2",
"lint-staged": "^10.2.7",
"moment": "^2.29.4",
"npm-run-all": "^4.1.5",
"prettier": "^2.6.0",
"react": "^17.0.2",
Expand All @@ -72,7 +72,6 @@
},
"peerDependencies": {
"@gravity-ui/uikit": "^4.0.0",
"moment": "^2.19.3",
"react": "^16.0.0 || ^17.0.0 || ^18.0.0"
},
"scripts": {
Expand Down
13 changes: 2 additions & 11 deletions src/libs/settings/__tests__/settings.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
import {DEFAULT_LOCALE_SPECIFICATION, settings} from '../settings';
import {settings} from '../settings';

const resetSettings = () =>
settings.set({
lang: 'en',
locale: DEFAULT_LOCALE_SPECIFICATION,
});
const resetSettings = () => settings.set({lang: 'en'});

describe('libs/settings', () => {
it('Default locale should be equal DEFAULT_LOCALE_SPECIFICATION', () => {
const result = settings.get('locale');
expect(result).toStrictEqual(DEFAULT_LOCALE_SPECIFICATION);
});

it('Default lang should be equal to en', () => {
const result = settings.get('lang');

Expand Down
30 changes: 30 additions & 0 deletions src/libs/settings/eventEmitter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
type EventObject<T = unknown> = {
id: string;
action: (args: T) => void;
};

export class EventEmitter<EventsMap = unknown> {
private events = {} as Record<keyof EventsMap, EventObject<any>[]>;

on<MapKey extends keyof EventsMap>(type: MapKey, event: EventObject<EventsMap[MapKey]>) {
if (this.events[type]) {
this.events[type].push(event);
} else {
this.events[type] = [event];
}
}

off<MapKey extends keyof EventsMap>(type: MapKey, eventId: string) {
if (this.events[type]) {
this.events[type] = this.events[type].filter(({id}) => id !== eventId);
}
}

dispatch<MapKey extends keyof EventsMap>(type: MapKey, args: EventsMap[MapKey]) {
if (this.events[type]) {
this.events[type].forEach(({action}) => {
action(args);
});
}
}
}
33 changes: 15 additions & 18 deletions src/libs/settings/settings.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import moment from 'moment';
import get from 'lodash/get';
import merge from 'lodash/merge';
import {configure} from '@gravity-ui/uikit';
import {i18nFactory} from '../../i18n';
import type {ChartKitPlugin, ChartKitLang, ChartKitHolidays} from '../../types';
import {EventEmitter} from './eventEmitter';

interface Settings {
plugins: ChartKitPlugin[];
lang: ChartKitLang;
locale?: moment.LocaleSpecification;
extra?: {
holidays?: ChartKitHolidays;
};
}

type SettingKey = keyof Settings;
type SettingsEventsMap = {
'change-lang': ChartKitLang;
};

export const DEFAULT_LOCALE_SPECIFICATION: moment.LocaleSpecification = {week: {dow: 1, doy: 7}};
export const settingsEventEmitter = new EventEmitter<SettingsEventsMap>();

const removeUndefinedValues = <T extends Record<string, any>>(data: T) => {
return Object.entries(data).reduce((acc, [key, value]) => {
Expand All @@ -28,14 +30,7 @@ const removeUndefinedValues = <T extends Record<string, any>>(data: T) => {
}, {} as T);
};

const updateLocale = (args: {lang: ChartKitLang; locale?: moment.LocaleSpecification}) => {
const {lang, locale} = args;

if (locale) {
moment.updateLocale(lang, locale);
}

moment.locale(lang);
const updateLang = (lang: ChartKitLang) => {
configure({lang});
i18nFactory.setLang(lang);
};
Expand All @@ -46,23 +41,25 @@ class ChartKitSettings {
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);

if (filteredUpdates.lang || filteredUpdates.locale) {
this.settings = merge(this.settings, filteredUpdates);

if (filteredUpdates.lang) {
const lang = filteredUpdates.lang || this.get('lang');
const locale = filteredUpdates.locale || this.get('locale');
updateLocale({lang, locale});
updateLang(lang);
settingsEventEmitter.dispatch('change-lang', lang);
}

this.settings = merge(this.settings, filteredUpdates);
}
}

export const settings = new ChartKitSettings();

settings.set({locale: DEFAULT_LOCALE_SPECIFICATION});
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import HighchartsReact from 'highcharts-react-official';
import get from 'lodash/get';
import type {ChartKitProps} from '../../../../types';
import {settings} from '../../../../libs';
import {settingsEventEmitter} from '../../../../libs/settings/settings';
import {markChartPerformance, getChartPerformanceDuration, getRandomCKId} from '../../../../utils';
import type {HighchartsWidgetData, StringParams} from '../../types';
import {getGraph} from '../helpers/graph';
import {initHighchartsModules} from '../helpers/init-highcharts-modules';
import {initHighchartsLangOptions} from '../helpers/highcharts/highcharts';
import {withSplitPane} from './withSplitPane/withSplitPane';

import './HighchartsComponent.scss';
Expand All @@ -23,6 +25,11 @@ type State = {
isError: boolean;
};

settingsEventEmitter.on('change-lang', {
id: 'hc-lang-handler',
action: initHighchartsLangOptions,
});

initHighchartsModules();

export class HighchartsComponent extends React.PureComponent<Props, State> {
Expand Down
6 changes: 4 additions & 2 deletions src/plugins/highcharts/renderer/helpers/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import isNumber from 'lodash/isNumber';
import throttle from 'lodash/throttle';
import pick from 'lodash/pick';
import debounce from 'lodash/debounce';
import moment from 'moment';
import {dateTime} from '@gravity-ui/date-utils';
import {i18n} from '../../../../../i18n';
import {formatNumber} from '../../../../shared';
import {
Expand Down Expand Up @@ -1412,7 +1412,9 @@ function drillOnClick(event, {options, chartType}) {
chartType === 'scatter' ? drillDownFilter - 180 * 60 * 1000 : drillDownFilter;
}

return isDateTime ? moment(drillDownFilter).format('YYYY-MM-DD') : drillDownFilter;
return isDateTime
? dateTime({input: drillDownFilter}).format('YYYY-MM-DD')
: drillDownFilter;
}

return filter;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import moment from 'moment';
import {dateTime} from '@gravity-ui/date-utils';
import type {Highcharts} from '../../../../types';
import type {NavigatorPeriod} from '../types';
import {getXAxisThresholdValue} from './getXAxisThresholdValue';
Expand Down Expand Up @@ -39,7 +39,7 @@ export const getDefaultPeriodInMS = (
return null;
}

const minXValue = moment(maxXValue).subtract(value, period);
const minXValue = dateTime({input: maxXValue}).subtract(value, period);
const range = maxXValue - minXValue.valueOf();

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ Highcharts.setOptions({
},
});

function initHighcharts({isMobile}) {
function initHighchartsLangOptions() {
Highcharts.setOptions({
lang: {
resetZoom: '⟲',
Expand Down Expand Up @@ -178,6 +178,10 @@ function initHighcharts({isMobile}) {
thousandsSep: i18n('highcharts', 'thousands-sep'),
},
});
}

function initHighcharts({isMobile}) {
initHighchartsLangOptions();

// https://github.com/highcharts/highcharts/issues/11494
(function (H) {
Expand Down Expand Up @@ -428,4 +432,4 @@ function initHighchartsMap() {
});
}

export {initHighcharts, initHighchartsMap};
export {initHighcharts, initHighchartsMap, initHighchartsLangOptions};
6 changes: 3 additions & 3 deletions src/plugins/highcharts/renderer/helpers/prepare-data.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import moment from 'moment';
import lodashMin from 'lodash/min';
import {dateTime} from '@gravity-ui/date-utils';
import {i18n} from '../../../../i18n';
import {ChartKitError, CHARTKIT_ERROR_CODE} from '../../../../libs';
import {DEFAULT_LINES_LIMIT} from './constants';
Expand Down Expand Up @@ -80,9 +80,9 @@ function removeHolidays(data, options, holidays) {
});

data.categories_ms.forEach((ts, i) => {
const datetime = moment(ts).format('YYYYMMDD');
const key = dateTime({input: ts}).format('YYYYMMDD');
const region = (options.region && options.region.toLowerCase()) || 'tot';
const holiday = holidays.holiday[region][datetime] || holidays.weekend[region][datetime];
const holiday = holidays.holiday[region][key] || holidays.weekend[region][key];

if (!holiday) {
timeline.push(ts);
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/yagr/renderer/tooltip/renderTooltip.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import moment from 'moment';
import {dateTime} from '@gravity-ui/date-utils';
import type {TooltipRow, TooltipRenderOptions, ValueFormatter} from '../../types';
import type {TooltipData, TooltipLine} from './types';
import {formatTooltip} from './tooltip';
Expand Down Expand Up @@ -50,7 +50,7 @@ export const renderTooltip = (data: TooltipRenderOptions) => {

const tooltipFormatOptions: TooltipData = {
activeRowAlwaysFirstInTooltip: rows.length > 1,
tooltipHeader: moment(x / timeMultiplier).format('DD MMMM YYYY HH:mm:ss'),
tooltipHeader: dateTime({input: x / timeMultiplier}).format('DD MMMM YYYY HH:mm:ss'),
shared: true,
lines: rows.map(
(row, i) =>
Expand Down
6 changes: 3 additions & 3 deletions src/plugins/yagr/renderer/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import moment from 'moment';
import merge from 'lodash/merge';
import {dateTime} from '@gravity-ui/date-utils';
import {defaults} from '@gravity-ui/yagr';
import {settings} from '../../../libs';
import type {Yagr, YagrWidgetData, YagrTheme, YagrChartOptions, MinimalValidConfig} from '../types';
Expand Down Expand Up @@ -120,9 +120,9 @@ const getXAxisFormatter =
(_: unknown, ticks: number[]) => {
const range = (ticks[ticks.length - 1] - ticks[0]) / msm;
return ticks.map((rawValue) => {
const d = moment(rawValue / msm);
const d = dateTime({input: rawValue / msm});

if (d.hour() === 0 && d.minutes() === 0 && d.seconds() === 0) {
if (d.hour() === 0 && d.minute() === 0 && d.second() === 0) {
return d.format('DD.MM.YY');
}

Expand Down