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(Calendar,DatePicker): multiple features #3287

Merged
merged 12 commits into from
Jun 5, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion packages/react-ui/.styleguide/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const excludedComponents = [
'SidePageContext',
];

const sectionComponents = ['Modal', 'MiniModal', 'SidePage', 'Tabs'];
const sectionComponents = ['Modal', 'MiniModal', 'SidePage', 'Tabs', 'Calendar'];

const findComponentsInSection = (dirPath, name) => {
// Looks for entries like `ParentCompChildComp.tsx`
Expand Down
43 changes: 42 additions & 1 deletion packages/react-ui/components/Calendar/Calendar.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,11 @@ const isHoliday = (day, isWeekend) => {
<Calendar isHoliday={isHoliday} value={date} onValueChange={setDate} />;
```


Календарю можно задать кастомную высоту с помощью переменной темы `calendarWrapperHeight`

- Базовая высота календаря - `330px`
- Максимальная высота календаря - `450px`

```jsx harmony
import { ThemeContext } from '@skbkontur/react-ui/lib/theming/ThemeContext';
import { ThemeFactory } from '@skbkontur/react-ui/lib/theming/ThemeFactory';
Expand All @@ -103,6 +104,46 @@ const theme = React.useContext(ThemeContext);
</ThemeContext.Provider>
```

### Кастомный рендер дня

```jsx harmony
import { Tooltip, Hint, CalendarDay } from '@skbkontur/react-ui';

const initialValue = "02.09.2023";

const [value, setValue] = React.useState(initialValue);

const renderDay = (props) => {
const [date, month, year] = props.date.split('.').map(Number);

if (month == 9 && date > 12 && date < 16) {
return (
<Tooltip render={() => "Кастомный день"}>
<CalendarDay {...props} style={{ background: 'darkgray' }} />
</Tooltip>
);
}

if (month == 8 && date == 20) {
return (
<Hint text={date} pos="right middle">
<CalendarDay {...props}>
<b style={{color: 'orange'}}>#</b>
</CalendarDay>
</Hint>
);
}

return <CalendarDay {...props} />
};

<Calendar
value={value}
onValueChange={setValue}
renderDay={renderDay}
/>;
```

#### Локали по умолчанию

```typescript static
Expand Down
2 changes: 1 addition & 1 deletion packages/react-ui/components/Calendar/Calendar.styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Theme } from '../../lib/theming/Theme';

export const styles = memoizeStyle({
root(t: Theme) {
const width = parseInt(t.calendarCellSize) * 7;
const width = parseInt(t.calendarCellWidth) * 7;
return css`
background: ${t.calendarBg};
box-sizing: content-box;
Expand Down
140 changes: 98 additions & 42 deletions packages/react-ui/components/Calendar/Calendar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { globalObject, SafeTimer } from '@skbkontur/global-object';

import { isInstanceOf } from '../../lib/isInstanceOf';
import { InternalDate } from '../../lib/date/InternalDate';
import { InternalDateTransformer } from '../../lib/date/InternalDateTransformer';
import { rootNode, TSetRootNode } from '../../lib/rootNode';
import { cx } from '../../lib/theming/Emotion';
import { CommonProps, CommonWrapper } from '../../internal/CommonWrapper';
Expand All @@ -17,6 +16,7 @@ import { ThemeContext } from '../../lib/theming/ThemeContext';
import { animation } from '../../lib/animation';
import { isMobile } from '../../lib/client';
import { createPropsGetter } from '../../lib/createPropsGetter';
import { InternalDateTransformer } from '../../lib/date/InternalDateTransformer';

import { themeConfig } from './config';
import { MonthViewModel } from './MonthViewModel';
Expand All @@ -25,6 +25,8 @@ import { Month } from './Month';
import { styles } from './Calendar.styles';
import { CalendarDateShape, create, isGreater, isLess } from './CalendarDateShape';
import * as CalendarUtils from './CalendarUtils';
import { CalendarContext, CalendarContextProps } from './CalendarContext';
import { CalendarDay, CalendarDayProps } from './CalendarDay';

export interface CalendarProps extends CommonProps {
/**
Expand All @@ -51,6 +53,18 @@ export interface CalendarProps extends CommonProps {
* Дата задаётся в формате `dd.mm.yyyy`
*/
minDate?: string;
/**
* Задаёт начальную дату периода
*
* Дата задаётся в формате `dd.mm.yyyy`
*/
periodStartDate?: string;
/**
* Задаёт конечную дату периода
*
* Дата задаётся в формате `dd.mm.yyyy`
*/
periodEndDate?: string;
/**
* Функция для определения праздничных дней
* @default (_day, isWeekend) => isWeekend
Expand All @@ -68,22 +82,44 @@ export interface CalendarProps extends CommonProps {
* Позволяет задать начальный год
*/
initialYear?: number;
/**
* Метод отрисовки дат в календаре
* @default (props: CalendarDayProps) => <CalendarDay {...props} />
* @param {CalendarDayProps} props
*
* @returns {ReactElement} Элемент, который отрисовывает контент числа месяца.
*/
renderDay?: (props: CalendarDayProps) => React.ReactElement;

/**
* Вызывается при каждом изменении месяца
* @param {CalendarMonthChangeInfo} changeInfo - информация о изменении отображаемого месяца, где
* `month: number` - номер текущего отображаемого месяца от 1 до 12,
* `year: number` - отображаемый год,
*/
onMonthChange?: (changeInfo: CalendarMonthChangeInfo) => void;
}

export interface CalendarState {
scrollPosition: number;
months: MonthViewModel[];
today: CalendarDateShape;
scrollDirection: number;
scrollTarget: number;
}

export interface CalendarMonthChangeInfo {
month: number;
year: number;
}

export const CalendarDataTids = {
root: 'Calendar__root',
month: 'MonthView__month',
dayCell: 'DayCellView__root',
headerMonth: 'MonthView__headerMonth',
monthSelectMobile: 'MonthView__monthSelectMobile',
headerYear: 'MonthView__headerYear',
yearSelectMobile: 'MonthView__yearSelectMobile',
} as const;

type DefaultProps = Required<Pick<CalendarProps, 'minDate' | 'maxDate' | 'isHoliday'>>;
Expand All @@ -96,6 +132,8 @@ export class Calendar extends React.Component<CalendarProps, CalendarState> {
public static __KONTUR_REACT_UI__ = 'Calendar';
public static displayName = 'Calendar';

public static Day = CalendarDay;

private static formatDate(date: number, month: number, year: number) {
return new InternalDate().setComponents({ date, month, year }).toString({ withPad: true });
}
Expand Down Expand Up @@ -132,24 +170,36 @@ export class Calendar extends React.Component<CalendarProps, CalendarState> {
maxDate: maxDateShape,
});

const initialMonth = CalendarUtils.getMonthInNativeFormat(this.props.initialMonth) ?? initialDate.month;
const initialMonth = this.props.initialMonth
? CalendarUtils.getMonthInNativeFormat(this.props.initialMonth)
: initialDate.month;
const initialYear = this.props.initialYear ?? initialDate.year;

this.state = {
scrollPosition: 0,
months: CalendarUtils.getMonths(initialMonth, initialYear),
today,
scrollDirection: 1,
scrollTarget: 0,
};
}

public componentDidUpdate(prevProps: Readonly<CalendarProps>): void {
const { value } = this.props;
public componentDidUpdate(prevProps: Readonly<CalendarProps>, prevState: Readonly<CalendarState>): void {
const { value, onMonthChange } = this.props;
if (value && !shallowEqual(value, prevProps.value)) {
const date = new InternalDate().parseValue(value).getComponentsLikeNumber();
this.scrollToMonth(date.month - 1, date.year);
}

if (onMonthChange) {
const visibleMonthsModels = this.getVisibleMonths(this.state).map(this.getViewModel);
const prevFirstVisibleMonthModels = this.getVisibleMonths(prevState).map(this.getViewModel);
const currentMonth = visibleMonthsModels[0].month;
const prevCurrentMonth = prevFirstVisibleMonthModels[0].month;

if (currentMonth !== prevCurrentMonth) {
this.handleMonthChange(visibleMonthsModels);
}
}
}

public componentWillUnmount() {
Expand Down Expand Up @@ -279,20 +329,41 @@ export class Calendar extends React.Component<CalendarProps, CalendarState> {
}
};

private handleMonthChange = (visibleMonths: MonthViewModel[]): void => {
const currentMonth = visibleMonths[0];
const changeInfo = {
month: CalendarUtils.getMonthInHumanFormat(currentMonth.month),
year: currentMonth.year,
};

this.props.onMonthChange?.(changeInfo);
};

private getViewModel = (item: [number, MonthViewModel]): MonthViewModel => item[1];

private renderMain = () => {
const positions = this.getMonthPositions();
const monthsForRender = this.getVisibleMonths(this.state);
const wrapperStyle = { height: themeConfig(this.theme).WRAPPER_HEIGHT };

const props = this.getProps();

const context: CalendarContextProps = {
value: this.getDateInNativeFormat(props.value),
minDate: this.getDateInNativeFormat(props.minDate),
maxDate: this.getDateInNativeFormat(props.maxDate),
isHoliday: props.isHoliday,
renderDay: props.renderDay,
today: CalendarUtils.getTodayDate(),
onDateClick: this.handleDateClick,
};

return (
<CommonWrapper rootNodeRef={this.setRootNode} {...props}>
<div ref={this.refRoot} data-tid={CalendarDataTids.root} className={cx(styles.root(this.theme))}>
<div style={wrapperStyle} className={styles.wrapper()}>
{this.state.months
.map<[number, MonthViewModel]>((x, i) => [positions[i], x])
.filter(([top, month]) => CalendarUtils.isMonthVisible(top, month, this.theme))
.map(this.renderMonth, this)}
<CalendarContext.Provider value={context}>
{monthsForRender.map(this.renderMonth, this)}
</CalendarContext.Provider>
</div>
<div className={styles.separator(this.theme)} />
</div>
Expand Down Expand Up @@ -321,51 +392,27 @@ export class Calendar extends React.Component<CalendarProps, CalendarState> {
};

private renderMonth([top, month]: [number, MonthViewModel]) {
const date = this.getDateInNativeFormat(this.props.value);
const minDate = this.getDateInNativeFormat(this.props.minDate);
const maxDate = this.getDateInNativeFormat(this.props.maxDate);

return (
<Month
key={month.month + '-' + month.year}
top={top}
month={month}
maxDate={maxDate}
minDate={minDate}
today={this.state.today}
value={date}
onDateClick={this.handleDateChange}
onMonthYearChange={this.handleMonthYearChange}
isHoliday={this.isHoliday}
/>
);
}

private isHoliday = ({ date, month, year, isWeekend }: CalendarDateShape & { isWeekend: boolean }) => {
const dateString = InternalDateTransformer.dateToInternalString({ date, month: month + 1, year });

return this.getProps().isHoliday(dateString, isWeekend);
};

private handleDateChange = (dateShape: CalendarDateShape) => {
const value = InternalDateTransformer.dateToInternalString({
date: dateShape.date,
month: dateShape.month + 1,
year: dateShape.year,
});
private handleDateClick = (dateShape: CalendarDateShape) => {
const value = InternalDateTransformer.dateToHumanString(dateShape);

if (this.props.onValueChange) {
this.props.onValueChange(value);
}
this.props.onValueChange?.(value);
};

private getDateInNativeFormat(date: Nullable<string>) {
return new InternalDate().parseValue(date).toNativeFormat();
}

private getMonthPositions() {
const { scrollPosition, months } = this.state;

private getMonthPositions(months: MonthViewModel[], scrollPosition: number) {
const positions = [scrollPosition - months[0].getHeight(this.theme)];
for (let i = 1; i < months.length; i++) {
const position = positions[i - 1] + months[i - 1].getHeight(this.theme);
Expand All @@ -374,6 +421,15 @@ export class Calendar extends React.Component<CalendarProps, CalendarState> {
return positions;
}

private getVisibleMonths(state: Readonly<CalendarState>): Array<[number, MonthViewModel]> {
const { months, scrollPosition } = state;
const positions = this.getMonthPositions(months, scrollPosition);

return months
.map<[number, MonthViewModel]>((x, i) => [positions[i], x])
.filter(([top, month]) => CalendarUtils.isMonthVisible(top, month, this.theme));
}

private handleMonthYearChange = (month: number, year: number) => {
this.scrollToMonth(month, year);
};
Expand Down Expand Up @@ -440,12 +496,12 @@ export class Calendar extends React.Component<CalendarProps, CalendarState> {
private scrollToNearestWeek = () => {
const { scrollTarget, scrollDirection } = this.state;

const trasholdHeight = themeConfig(this.theme).MONTH_TITLE_OFFSET_HEIGHT + themeConfig(this.theme).DAY_SIZE;
const thresholdHeight = themeConfig(this.theme).MONTH_TITLE_OFFSET_HEIGHT + themeConfig(this.theme).DAY_HEIGHT;

if (scrollTarget < trasholdHeight) {
if (scrollTarget < thresholdHeight) {
let targetPosition = 0;
if (scrollDirection < 0) {
targetPosition = trasholdHeight;
targetPosition = thresholdHeight;
}

this.setState({ scrollTarget: targetPosition }, () => {
Expand Down
16 changes: 16 additions & 0 deletions packages/react-ui/components/Calendar/CalendarContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { createContext } from 'react';

import { CalendarDateShape } from './CalendarDateShape';
import { CalendarProps } from './Calendar';

export interface CalendarContextProps {
renderDay?: CalendarProps['renderDay'];
value?: CalendarDateShape;
minDate?: CalendarDateShape;
maxDate?: CalendarDateShape;
isHoliday?: CalendarProps['isHoliday'];
today?: CalendarDateShape;
onDateClick?: (date: CalendarDateShape) => void;
}

export const CalendarContext = createContext<CalendarContextProps>({});