Skip to content

Adding format array support #198

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ API
| showHour | Boolean | true | whether show hour | |
| showMinute | Boolean | true | whether show minute |
| showSecond | Boolean | true | whether show second |
| format | String | - | moment format |
| format | String \| String[] | - | moment format. When an array is provided, all values are used for parsing and first value for display |
| disabledHours | Function | - | disabled hour options |
| disabledMinutes | Function | - | disabled minute options |
| disabledSeconds | Function | - | disabled second options |
Expand Down
8 changes: 8 additions & 0 deletions examples/format.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ const App = () => (
<TimePicker defaultValue={moment()} showMinute={false} showSecond={false} />
<TimePicker defaultValue={moment()} showHour={false} showSecond={false} />
<TimePicker defaultValue={moment()} showHour={false} showMinute={false} />

<TimePicker defaultValue={moment()} format={['HH:mm:ss', 'HH.mm.ss', 'HH.mm.ss']} />
<TimePicker
defaultValue={moment()}
format={['HH:mm a', 'HH.mm a', 'HH.mm a']}
showSecond={false}
use12Hours
/>
</>
);

Expand Down
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ declare module "rc-time-picker" {
showHour?: boolean;
showMinute?: boolean;
showSecond?: boolean;
format?: string;
format?: string | string[];
disabledHours?: () => number[];
disabledMinutes?: (hour: number) => number[];
disabledSeconds?: (hour: number, minute: number) => number[];
Expand Down
2 changes: 1 addition & 1 deletion src/Combobox.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ class Combobox extends Component {
}

const AMPMOptions = ['am', 'pm'] // If format has A char, then we should uppercase AM/PM
.map(c => (format.match(/\sA/) ? c.toUpperCase() : c))
.map(c => (format[0].match(/\sA/) ? c.toUpperCase() : c))
.map(c => ({ value: c }));

const selected = isAM ? 0 : 1;
Expand Down
30 changes: 25 additions & 5 deletions src/Header.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class Header extends Component {
super(props);
const { value, format } = props;
this.state = {
str: (value && value.format(format)) || '',
str: (value && value.format(format[0])) || '',
invalid: false,
};
}
Expand All @@ -35,7 +35,7 @@ class Header extends Component {
if (value !== prevProps.value) {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({
str: (value && value.format(format)) || '',
str: (value && value.format(format[0])) || '',
invalid: false,
});
}
Expand All @@ -53,7 +53,6 @@ class Header extends Component {
str,
});
const {
format,
hourOptions,
minuteOptions,
secondOptions,
Expand All @@ -66,13 +65,16 @@ class Header extends Component {
if (str) {
const { value: originalValue } = this.props;
const value = this.getProtoValue().clone();
const parsed = moment(str, format, true);
if (!parsed.isValid()) {

const parsed = this.parseValue(str);

if (parsed === null) {
this.setState({
invalid: true,
});
return;
}

value
.hour(parsed.hour())
.minute(parsed.minute())
Expand Down Expand Up @@ -163,6 +165,24 @@ class Header extends Component {
);
}

parseValue = str => {
const { format } = this.props;

let parsedDate = null;
format.find(singleFormat => {
const date = moment(str, singleFormat, true);

if (date.isValid()) {
parsedDate = date;
return true;
}

return false;
});

return parsedDate;
};

render() {
const { prefixCls } = this.props;
return <div className={`${prefixCls}-input-wrap`}>{this.getInput()}</div>;
Expand Down
22 changes: 16 additions & 6 deletions src/TimePicker.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ function refFn(field, component) {
this[field] = component;
}

function toArray(val) {
if (val === null || val === undefined) {
return [];
}

return Array.isArray(val) ? val : [val];
}

class Picker extends Component {
static defaultProps = {
clearText: 'clear',
Expand Down Expand Up @@ -115,20 +123,22 @@ class Picker extends Component {
getFormat() {
const { format, showHour, showMinute, showSecond, use12Hours } = this.props;
if (format) {
return format;
return toArray(format);
}

if (use12Hours) {
const fmtString = [showHour ? 'h' : '', showMinute ? 'mm' : '', showSecond ? 'ss' : '']
.filter(item => !!item)
.join(':');

return fmtString.concat(' a');
return toArray(fmtString.concat(' a'));
}

return [showHour ? 'HH' : '', showMinute ? 'mm' : '', showSecond ? 'ss' : '']
.filter(item => !!item)
.join(':');
return toArray(
[showHour ? 'HH' : '', showMinute ? 'mm' : '', showSecond ? 'ss' : '']
.filter(item => !!item)
.join(':'),
);
}

getPanelElement() {
Expand Down Expand Up @@ -314,7 +324,7 @@ class Picker extends Component {
name={name}
onKeyDown={this.onKeyDown}
disabled={disabled}
value={(value && value.format(this.getFormat())) || ''}
value={(value && value.format(this.getFormat()[0])) || ''}
autoComplete={autoComplete}
onFocus={onFocus}
onBlur={onBlur}
Expand Down
72 changes: 72 additions & 0 deletions tests/Select.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,32 @@ describe('Select', () => {
expect(picker.state().open).toBeTruthy();
});

it('ampm correctly format value', async () => {
const onAmPmChange = jest.fn();
const picker = renderPicker({
onAmPmChange,
defaultValue: moment()
.hour(0)
.minute(0)
.second(0),
format: 'hh:mm a',
showSecond: false,
use12Hours: true,
});
expect(picker.state().open).toBeFalsy();
clickInput(picker);

expect(picker.state().open).toBeTruthy();

matchValue(picker, '12:00 am');
clickSelectItem(picker, 2, 1);

expect(onAmPmChange).toBeCalled();
expect(onAmPmChange.mock.calls[0][0]).toBe('PM');
matchValue(picker, '12:00 pm');
expect(picker.state().open).toBeTruthy();
});

it('disabled correctly', async () => {
const onChange = jest.fn();
const picker = renderPicker({
Expand Down Expand Up @@ -269,6 +295,52 @@ describe('Select', () => {
});
});

describe('multi format parsing mode', () => {
it('renders correctly', async () => {
const picker = renderPicker({
use12Hours: true,
defaultValue: moment()
.hour(14)
.minute(0)
.second(0),
format: ['h:mm a', 'h-mm a'],
showSecond: false,
});

expect(picker.state().open).toBeFalsy();
clickInput(picker);
expect(picker.state().open).toBeTruthy();

matchValue(picker, '2:00 pm');

expect(picker.find('.rc-time-picker-panel-select').length).toBe(3);
});

it('renders 12am/pm correctly', async () => {
const picker = renderPicker({
use12Hours: true,
defaultValue: moment()
.hour(0)
.minute(0)
.second(0),
showSecond: false,
format: ['hh:mm a', 'hh-mm a'],
});

expect(picker.state().open).toBeFalsy();
clickInput(picker);
expect(picker.state().open).toBeTruthy();

matchValue(picker, '12:00 am');

clickSelectItem(picker, 2, 1);
matchValue(picker, '12:00 pm');

clickSelectItem(picker, 2, 0);
matchValue(picker, '12:00 am');
});
});

describe('select in 12 hours mode', () => {
it('renders correctly', async () => {
const picker = renderPicker({
Expand Down