Skip to content

feat(datepicker): Rename props and update onChange signature #84

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

Merged
merged 14 commits into from
Oct 25, 2019
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
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ import React from 'react';
import SemanticDatepicker from 'react-semantic-ui-datepickers';
import 'react-semantic-ui-datepickers/dist/react-semantic-ui-datepickers.css';

const AppWithBasic = ({ onDateChange }) => (
<SemanticDatepicker onDateChange={onDateChange} />
const AppWithBasic = ({ onChange }) => (
<SemanticDatepicker onChange={onChange} />
);

const AppWithRangeAndInPortuguese = ({ onDateChange }) => (
<SemanticDatepicker locale="pt-BR" onDateChange={onDateChange} type="range" />
const AppWithRangeAndInPortuguese = ({ onChange }) => (
<SemanticDatepicker locale="pt-BR" onChange={onChange} type="range" />
);
```

Expand All @@ -75,7 +75,7 @@ More examples [here](https://react-semantic-ui-datepickers.now.sh).
| keepOpenOnSelect | boolean | no | false | Keeps the datepicker open when a date is selected |
| locale | string | no | 'en-US' | Filename of the locale to be used. PS: Feel free to submit PR's with more locales! |
| onBlur | function | no | () => {} | Callback fired when the input loses focus |
| onDateChange | function | yes | | Callback fired when the value changes |
| onChange | function | no | () => {} | Callback fired when the value changes |
| pointing | string | no | 'left' | Location to render the component around input. Available options: 'left', 'right', 'top left', 'top right' |
| type | string | no | basic | Type of input to render. Available options: 'basic' and 'range' |

Expand Down
65 changes: 62 additions & 3 deletions src/__tests__/datepicker.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { fireEvent, render } from '@testing-library/react';
import { SemanticDatepickerProps } from '../types';
import localeEn from '../locales/en-US.json';
import localePt from '../locales/pt-BR.json';
import { getShortDate } from '../utils';
import DatePicker from '../';

const setup = (props?: Partial<SemanticDatepickerProps>) => {
const options = render(<DatePicker onDateChange={jest.fn()} {...props} />);
const options = render(<DatePicker onChange={jest.fn()} {...props} />);

return {
...options,
Expand All @@ -17,7 +18,7 @@ const setup = (props?: Partial<SemanticDatepickerProps>) => {
},
rerender: (newProps?: Partial<SemanticDatepickerProps>) =>
options.rerender(
<DatePicker onDateChange={jest.fn()} {...props} {...newProps} />
<DatePicker onChange={jest.fn()} {...props} {...newProps} />
),
};
};
Expand Down Expand Up @@ -55,6 +56,26 @@ describe('Basic datepicker', () => {

expect(todayButton.textContent).toBe(localeEn.todayButton);
});

it('fires onChange with event and selected date as arguments', async () => {
const onChange = jest.fn();
const today = getShortDate(new Date()) as string;
const { getByTestId, openDatePicker } = setup({ onChange });

openDatePicker();

const todayCell = getByTestId(RegExp(today));

fireEvent.click(todayCell);

expect(onChange).toHaveBeenNthCalledWith(
1,
expect.any(Object),
expect.objectContaining({
value: expect.any(Date),
})
);
});
});

describe('Range datepicker', () => {
Expand Down Expand Up @@ -86,8 +107,46 @@ describe('Range datepicker', () => {
expect(todayButton.textContent).toBe(localeEn.todayButton);

// @ts-ignore
rerender({ locale: 'invalid language' });
rerender({ locale: 'invalid' });

expect(todayButton.textContent).toBe(localeEn.todayButton);
});

it('fires onChange with event and selected dates as arguments', async () => {
const onChange = jest.fn();
const now = new Date();
const today = getShortDate(now) as string;
const tomorrow = getShortDate(
new Date(now.setDate(now.getDate() + 1))
) as string;
const { getByTestId, openDatePicker } = setup({
onChange,
type: 'range',
});

openDatePicker();

const todayCell = getByTestId(RegExp(today));
const tomorrowCell = getByTestId(RegExp(tomorrow));

fireEvent.click(todayCell);

expect(onChange).toHaveBeenNthCalledWith(
1,
expect.any(Object),
expect.objectContaining({
value: [expect.any(Date)],
})
);

fireEvent.click(tomorrowCell);

expect(onChange).toHaveBeenNthCalledWith(
2,
expect.any(Object),
expect.objectContaining({
value: [expect.any(Date), expect.any(Date)],
})
);
});
});
14 changes: 13 additions & 1 deletion src/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import localeEn from '../locales/en-US.json';
import {
formatDate,
formatSelectedDate,
getShortDate,
getToday,
isSelectable,
moveElementsByN,
Expand All @@ -14,7 +15,8 @@ import {
} from '../utils';

const objectTest = { a: 'a', b: 'b', c: 'c' };
const dateTest = parse('2018-06-21');
const dateTestString = '2018-06-21';
const dateTest = parse(dateTestString);
const june14 = parse('2018-06-14');
const june20 = parse('2018-06-20');
const june25 = parse('2018-06-25');
Expand Down Expand Up @@ -159,3 +161,13 @@ describe('onlyNumbers', () => {
expect(onlyNumbers('ABC-1025.4.8')).toBe('102548');
});
});

describe('getShortDate', () => {
it('should return undefined if date is not provided', () => {
expect(getShortDate(undefined)).toBe(undefined);
});

it('should return the date provided in the right format', () => {
expect(getShortDate(new Date(dateTestString))).toBe(dateTestString);
});
});
4 changes: 3 additions & 1 deletion src/components/calendar/calendar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import cn from 'classnames';
import React, { Fragment } from 'react';
import { Segment } from 'semantic-ui-react';
import { DateFns, Locale, SemanticDatepickerProps } from 'types';
import { getToday } from '../../utils';
import { getShortDate, getToday } from '../../utils';
import Button from '../button';
import CalendarCell from '../cell';
import TodayButton from '../today-button';
Expand Down Expand Up @@ -124,12 +124,14 @@ const Calendar: React.FC<CalendarProps> = ({

const selectable =
dateObj.selectable && filterDate(dateObj.date);
const shortDate = getShortDate(dateObj.date);

return (
<CalendarCell
key={key}
{...dateObj}
{...getDateProps({ dateObj: { ...dateObj, selectable } })}
data-testid={`datepicker-cell-${shortDate}`}
selectable={selectable}
>
{dateObj.date.getDate()}
Expand Down
62 changes: 33 additions & 29 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import {
parseOnBlur,
pick,
} from './utils';
import BasicDatePicker from './pickers/basic';
import RangeDatePicker from './pickers/range';
import { BasicDatePicker, RangeDatePicker } from './pickers';
import { Locale, SemanticDatepickerProps } from './types';
import Calendar from './components/calendar';
import Input from './components/input';
Expand Down Expand Up @@ -80,22 +79,23 @@ class SemanticDatepicker extends React.Component<
locale: 'en-US',
name: undefined,
onBlur: () => {},
onChange: () => {},
placeholder: null,
pointing: 'left',
readOnly: false,
required: false,
selected: null,
showOutsideDays: false,
type: 'basic',
readOnly: false,
value: null,
};

el = React.createRef<HTMLDivElement>();

componentDidUpdate(prevProps: SemanticDatepickerProps) {
const { locale, selected } = this.props;
const { locale, value } = this.props;

if (!isEqual(selected, prevProps.selected)) {
this.onDateSelected(selected);
if (!isEqual(value, prevProps.value)) {
this.onDateSelected(undefined, value);
}

if (locale !== prevProps.locale) {
Expand All @@ -108,14 +108,14 @@ class SemanticDatepicker extends React.Component<
}

get initialState() {
const { format, selected } = this.props;
const { format, value } = this.props;
const initialSelectedDate = this.isRangeInput ? [] : null;

return {
isVisible: false,
locale: this.locale,
selectedDate: selected || initialSelectedDate,
selectedDateFormatted: formatSelectedDate(selected, format),
selectedDate: value || initialSelectedDate,
selectedDateFormatted: formatSelectedDate(value, format),
typedValue: null,
};
}
Expand All @@ -138,6 +138,10 @@ class SemanticDatepicker extends React.Component<
const { selectedDate } = this.state;
const { date } = this.props;

if (!selectedDate) {
return date;
}

return this.isRangeInput ? selectedDate[0] : selectedDate || date;
}

Expand Down Expand Up @@ -169,16 +173,16 @@ class SemanticDatepicker extends React.Component<
? RangeDatePicker
: BasicDatePicker;

resetState = () => {
const { keepOpenOnClear, onDateChange } = this.props;
resetState = event => {
const { keepOpenOnClear, onChange } = this.props;
const newState = {
isVisible: keepOpenOnClear,
selectedDate: this.isRangeInput ? [] : null,
selectedDateFormatted: '',
};

this.setState(newState, () => {
onDateChange(null);
onChange(event, { ...this.props, value: null });
});
};

Expand Down Expand Up @@ -219,11 +223,11 @@ class SemanticDatepicker extends React.Component<
});
};

handleRangeInput = newDates => {
const { format, keepOpenOnSelect, onDateChange } = this.props;
handleRangeInput = (newDates, event) => {
const { format, keepOpenOnSelect, onChange } = this.props;

if (!newDates || !newDates.length) {
this.resetState();
this.resetState(event);

return;
}
Expand All @@ -235,19 +239,19 @@ class SemanticDatepicker extends React.Component<
};

this.setState(newState, () => {
onDateChange(newDates);
onChange(event, { ...this.props, value: newDates });

if (newDates.length === 2) {
this.setState({ isVisible: keepOpenOnSelect });
}
});
};

handleBasicInput = newDate => {
handleBasicInput = (newDate, event) => {
const {
format,
keepOpenOnSelect,
onDateChange,
onChange,
clearOnSameDateClick,
} = this.props;

Expand All @@ -256,7 +260,7 @@ class SemanticDatepicker extends React.Component<
// then reset the state. This is what was previously the default
// behavior, without a specific prop.
if (clearOnSameDateClick) {
this.resetState();
this.resetState(event);
} else {
// Don't reset the state. Instead, close or keep open the
// datepicker according to the value of keepOpenOnSelect.
Expand All @@ -277,7 +281,7 @@ class SemanticDatepicker extends React.Component<
};

this.setState(newState, () => {
onDateChange(newDate);
onChange(event, { ...this.props, value: newDate });
});
};

Expand All @@ -301,23 +305,23 @@ class SemanticDatepicker extends React.Component<
const areDatesValid = parsedValue.every(isValid);

if (areDatesValid) {
this.handleRangeInput(parsedValue);
this.handleRangeInput(parsedValue, event);
return;
}
} else {
const isDateValid = isValid(parsedValue);

if (isDateValid) {
this.handleBasicInput(parsedValue);
this.handleBasicInput(parsedValue, event);
return;
}
}

this.setState({ typedValue: null });
};

handleChange = (_evt, { value }) => {
const { allowOnlyNumbers, format, onDateChange } = this.props;
handleChange = (event: React.SyntheticEvent, { value }) => {
const { allowOnlyNumbers, format, onChange } = this.props;
const formatString = this.isRangeInput ? `${format} - ${format}` : format;
const typedValue = allowOnlyNumbers ? onlyNumbers(value) : value;

Expand All @@ -329,7 +333,7 @@ class SemanticDatepicker extends React.Component<
};

this.setState(newState, () => {
onDateChange(null);
onChange(event, { ...this.props, value: null });
});

return;
Expand All @@ -349,11 +353,11 @@ class SemanticDatepicker extends React.Component<
}
};

onDateSelected = dateOrDates => {
onDateSelected = (event: React.SyntheticEvent | undefined, dateOrDates) => {
if (this.isRangeInput) {
this.handleRangeInput(dateOrDates);
this.handleRangeInput(dateOrDates, event);
} else {
this.handleBasicInput(dateOrDates);
this.handleBasicInput(dateOrDates, event);
}
};

Expand Down
Loading