Skip to content

Commit

Permalink
feat: Move from dayjs to date-fns (#7320)
Browse files Browse the repository at this point in the history
Переходим от dayjs к date-fns
  • Loading branch information
SevereCloud authored Aug 7, 2024
1 parent bb58c54 commit 785b7f6
Show file tree
Hide file tree
Showing 28 changed files with 84 additions and 589 deletions.
2 changes: 1 addition & 1 deletion packages/vkui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
"@vkontakte/icons": "^2.115.0",
"@vkontakte/vkjs": "^1.3.0",
"@vkontakte/vkui-floating-ui": "^0.2.1",
"dayjs": "^1.11.12"
"date-fns": "^3.6.0"
},
"devDependencies": {
"storybook": "8.2.7"
Expand Down
2 changes: 1 addition & 1 deletion packages/vkui/src/components/Calendar/Calendar.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as React from 'react';
import { classNames } from '@vkontakte/vkjs';
import { isSameDay, isSameMonth } from 'date-fns';
import { useCalendar } from '../../hooks/useCalendar';
import { clamp, isFirstDay, isLastDay, navigateDate, setTimeEqual } from '../../lib/calendar';
import { isSameDay, isSameMonth } from '../../lib/date';
import { useIsomorphicLayoutEffect } from '../../lib/useIsomorphicLayoutEffect';
import { warnOnce } from '../../lib/warnOnce';
import { HTMLAttributesWithRootRef } from '../../types';
Expand Down
4 changes: 2 additions & 2 deletions packages/vkui/src/components/Calendar/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
- Если нужен выбор диапазона дат, используйте [CalendarRange](#!/CalendarRange).

```jsx { "props": { "layout": false, "iframe": false } }
import { format } from '../../lib/date';
import { lightFormat } from 'date-fns';

const Example = () => {
const [value, setValue] = useState(() => new Date());
Expand All @@ -19,7 +19,7 @@ const Example = () => {

return (
<FormLayoutGroup mode="vertical">
<FormItem top="Выбранная дата">{format(value, 'YYYY-MM-DD HH:mm:ss')}</FormItem>
<FormItem top="Выбранная дата">{lightFormat(value, 'yyyy-MM-dd HH:mm:ss')}</FormItem>
<FormItem top="Выбор времени">
<Checkbox checked={enableTime} onChange={(e) => setEnableTime(e.target.checked)}>
Включено
Expand Down
2 changes: 1 addition & 1 deletion packages/vkui/src/components/CalendarDays/CalendarDays.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as React from 'react';
import { classNames } from '@vkontakte/vkjs';
import { isSameDay, isSameMonth } from 'date-fns';
import { useExternRef } from '../../hooks/useExternRef';
import { useTodayDate } from '../../hooks/useTodayDate';
import { getDaysNames, getWeeks } from '../../lib/calendar';
import { isSameDay, isSameMonth } from '../../lib/date';
import { HTMLAttributesWithRootRef } from '../../types';
import { CalendarDay, CalendarDayElementProps } from '../CalendarDay/CalendarDay';
import { useConfigProvider } from '../ConfigProvider/ConfigProviderContext';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import {
Icon20ChevronRightOutline,
} from '@vkontakte/icons';
import { classNames } from '@vkontakte/vkjs';
import { addMonths, setMonth, setYear, subMonths } from 'date-fns';
import { DEFAULT_MAX_YEAR, DEFAULT_MIN_YEAR, getMonths, getYears } from '../../lib/calendar';
import { addMonths, setMonth, setYear, subMonths } from '../../lib/date';
import { HTMLAttributesWithRootRef } from '../../types';
import { AdaptivityProvider } from '../AdaptivityProvider/AdaptivityProvider';
import { useConfigProvider } from '../ConfigProvider/ConfigProviderContext';
Expand Down
8 changes: 4 additions & 4 deletions packages/vkui/src/components/CalendarRange/CalendarRange.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import * as React from 'react';
import { useCalendar } from '../../hooks/useCalendar';
import { isFirstDay, isLastDay, navigateDate, setTimeEqual } from '../../lib/calendar';
import {
addMonths,
endOfDay,
Expand All @@ -11,7 +9,9 @@ import {
isWithinInterval,
startOfDay,
subMonths,
} from '../../lib/date';
} from 'date-fns';
import { useCalendar } from '../../hooks/useCalendar';
import { isFirstDay, isLastDay, navigateDate, setTimeEqual } from '../../lib/calendar';
import { HTMLAttributesWithRootRef } from '../../types';
import { CalendarDays, CalendarDaysProps } from '../CalendarDays/CalendarDays';
import { CalendarHeader, CalendarHeaderProps } from '../CalendarHeader/CalendarHeader';
Expand Down Expand Up @@ -48,7 +48,7 @@ const getIsDaySelected = (day: Date, value?: DateRangeType) => {
return false;
}

return Boolean(isWithinInterval(day, startOfDay(value[0]), endOfDay(value[1])));
return isWithinInterval(day, { start: startOfDay(value[0]), end: endOfDay(value[1]) });
};

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/vkui/src/components/CalendarRange/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
- Если нужен выбор одной даты, используйте [Calendar](#!/Calendar).

```jsx { "props": { "layout": false, "iframe": false } }
import { addDays, format } from '../../lib/date';
import { addDays, format } from 'date-fns';

const Example = () => {
const [value, setValue] = useState([new Date(), addDays(new Date(), 10)]);
Expand All @@ -16,7 +16,7 @@ const Example = () => {
return (
<FormLayoutGroup mode="vertical">
<FormItem top="Выбранная дата">
{format(value[0], 'YYYY-MM-DD')} - {format(value[1], 'YYYY-MM-DD')}
{format(value[0], 'yyyy-MM-dd')} - {format(value[1], 'yyyy-MM-dd')}
</FormItem>
<FormItem top="Запрет выбора прошлых дат">
<Checkbox checked={disablePast} onChange={(e) => setDisablePast(e.target.checked)}>
Expand Down
2 changes: 1 addition & 1 deletion packages/vkui/src/components/CalendarTime/CalendarTime.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { setHours, setMinutes } from '../../lib/date';
import { setHours, setMinutes } from 'date-fns';
import { AdaptivityProvider } from '../AdaptivityProvider/AdaptivityProvider';
import { Button } from '../Button/Button';
import { CustomSelect } from '../CustomSelect/CustomSelect';
Expand Down
4 changes: 2 additions & 2 deletions packages/vkui/src/components/DateInput/DateInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ export const DateInput = ({
}

let formattedValue = `${internalValue[0]}.${internalValue[1]}.${internalValue[2]}`;
let mask = 'DD.MM.YYYY';
let mask = 'dd.MM.yyyy';
if (enableTime) {
formattedValue += ` ${internalValue[3]}:${internalValue[4]}`;
mask += ' HH:mm';
Expand Down Expand Up @@ -243,7 +243,7 @@ export const DateInput = ({
<input
type="hidden"
name={name}
value={value ? format(value, enableTime ? 'DD.MM.YYYYTHH:mm' : 'DD.MM.YYYY') : ''}
value={value ? format(value, enableTime ? "dd.MM.yyyy'T'HH:mm" : 'dd.MM.yyyy') : ''}
/>
<Text
className={styles['DateInput__input']}
Expand Down
2 changes: 0 additions & 2 deletions packages/vkui/src/components/DateInput/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
> ⚠️ Данный компонент предназначен для использования на desktop. При использовании на ios/android работа компонента не гарантируется
```jsx { "props": { "layout": false, "iframe": false } }
import { format } from '../../lib/date';

const Example = () => {
const [value, setValue] = useState(() => new Date());
const [enableTime, setEnableTime] = useState(false);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as React from 'react';
import { Icon16Clear, Icon20CalendarOutline } from '@vkontakte/icons';
import { classNames } from '@vkontakte/vkjs';
import { isAfter } from 'date-fns';
import { useAdaptivity } from '../../hooks/useAdaptivity';
import { useDateInput } from '../../hooks/useDateInput';
import { useExternRef } from '../../hooks/useExternRef';
import { callMultiple } from '../../lib/callMultiple';
import { format, isAfter, isMatch, parse } from '../../lib/date';
import { format, isMatch, parse } from '../../lib/date';
import type { PlacementWithAuto } from '../../lib/floating';
import { HasRootRef } from '../../types';
import { CalendarRange, CalendarRangeProps, DateRangeType } from '../CalendarRange/CalendarRange';
Expand Down Expand Up @@ -159,7 +160,7 @@ export const DateRangeInput = ({
}
const formattedStartValue = `${internalValue[0]}.${internalValue[1]}.${internalValue[2]}`;
const formattedEndValue = `${internalValue[3]}.${internalValue[4]}.${internalValue[5]}`;
const mask = 'DD.MM.YYYY';
const mask = 'dd.MM.yyyy';

if (!isMatch(formattedStartValue, mask)) {
isStartValid = false;
Expand Down Expand Up @@ -258,8 +259,8 @@ export const DateRangeInput = ({
name={name}
value={
value
? `${value[0] ? format(value[0], 'DD.MM.YYYY') : ''} - ${
value[1] ? format(value[1], 'DD.MM.YYYY') : ''
? `${value[0] ? format(value[0], 'dd.MM.yyyy') : ''} - ${
value[1] ? format(value[1], 'dd.MM.yyyy') : ''
}`
: ''
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vkui/src/components/DateRangeInput/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
> ⚠️ Данный компонент предназначен для использования на desktop. При использовании на ios/android работа компонента не гарантируется
```jsx { "props": { "layout": false, "iframe": false } }
import { format, addDays } from '../../lib/date';
import { addDays } from 'date-fns';

const Example = () => {
const [value, setValue] = useState([new Date(), addDays(new Date(), 10)]);
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 1 addition & 9 deletions packages/vkui/src/hooks/useCalendar.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
import * as React from 'react';
import { addMonths, endOfDay, isAfter, isBefore, isSameDay, startOfDay, subMonths } from 'date-fns';
import { CalendarProps } from '../components/Calendar/Calendar';
import { DEFAULT_MAX_YEAR, DEFAULT_MIN_YEAR, isDayMinMaxRestricted } from '../lib/calendar';
import {
addMonths,
endOfDay,
isAfter,
isBefore,
isSameDay,
startOfDay,
subMonths,
} from '../lib/date';

export interface UseCalendarDependencies
extends Pick<
Expand Down
4 changes: 2 additions & 2 deletions packages/vkui/src/hooks/useTodayDate.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { getMillisecondsToTomorrow, isSameDay } from '../lib/date';
import { differenceInMilliseconds, endOfToday, isSameDay } from 'date-fns';
import { useDOM } from '../lib/dom';

/**
Expand All @@ -26,7 +26,7 @@ export function useTodayDate(listenDayChangesForUpdate = false): Date {
if (document.visibilityState === 'visible') {
const now = new Date();

const timeToDayChange = getMillisecondsToTomorrow(now);
const timeToDayChange = differenceInMilliseconds(endOfToday(), now);

// Удаляем старый таймаут
window.clearTimeout(timeout);
Expand Down
15 changes: 8 additions & 7 deletions packages/vkui/src/lib/calendar.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { clamp as clampNumber } from '../helpers/math';
import {
addDays,
addWeeks,
Expand All @@ -14,7 +13,8 @@ import {
startOfWeek,
subDays,
subWeeks,
} from './date';
} from 'date-fns';
import { clamp as clampNumber } from '../helpers/math';

export const DEFAULT_MAX_YEAR = 9999;
// 100 - из-за ограничений dayjs https://github.com/iamkun/dayjs/issues/2591
Expand Down Expand Up @@ -74,9 +74,10 @@ export const getDaysNames = (
const formatter = new Intl.DateTimeFormat(locale, {
weekday: 'short',
});
return eachDayOfInterval(startOfWeek(now, weekStartsOn), endOfWeek(now, weekStartsOn)).map(
(day) => formatter.format(day),
);
return eachDayOfInterval({
start: startOfWeek(now, { weekStartsOn }),
end: endOfWeek(now, { weekStartsOn }),
}).map((day) => formatter.format(day));
};

export const navigateDate = (date?: Date | null, key?: string): Date => {
Expand All @@ -101,8 +102,8 @@ export const navigateDate = (date?: Date | null, key?: string): Date => {
};

export const getWeeks = (viewDate: Date, weekStartsOn: 0 | 1 | 2 | 3 | 4 | 5 | 6): Date[][] => {
const start = startOfWeek(startOfMonth(viewDate), weekStartsOn);
const end = endOfWeek(endOfMonth(viewDate), weekStartsOn);
const start = startOfWeek(startOfMonth(viewDate), { weekStartsOn });
const end = endOfWeek(endOfMonth(viewDate), { weekStartsOn });

let count = 0;
let current = start;
Expand Down
Loading

0 comments on commit 785b7f6

Please sign in to comment.