Skip to content

Commit

Permalink
- initialDates & initialTimes
Browse files Browse the repository at this point in the history
  • Loading branch information
edwardxiao committed Jul 7, 2020
1 parent c662894 commit 45e085a
Show file tree
Hide file tree
Showing 5 changed files with 134 additions and 58 deletions.
25 changes: 21 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,34 @@ import 'react-minimal-datetime-range/lib/react-minimal-datetime-range.min.css';
/>

<RangePicker
locale={`en-us`} // default is en-us
locale="en-us" // default is en-us
show={false} // default is false
disabled={false} // default is false
allowPageClickToClose={true} // default is true
placeholder={['Start Time', 'End Time']}
defaultDates={[`${yearS}-${monthS}-${dateS}`, `${yearE}-${monthE}-${dateE}`]} // ['YYYY-MM-DD', 'YYYY-MM-DD']
defaultTimes={[`${hourS}:${minuteS}`, `${hourE}:${minuteE}`]} // ['hh:mm', 'hh:mm']
onConfirm={res => console.log(res)}
onClose={() => console.log('onClose')}
onClear={() => console.log('onClear')}
style={{ width: '300px', margin: '0 auto' }}
placeholder={['Start Time', 'End Time']}
////////////////////
// IMPORTANT DESC //
////////////////////
defaultDates={[year+'-'+month+'-'+date,year+'-'+month+'-'+date]}
// ['YYYY-MM-DD', 'YYYY-MM-DD']
// This is the value you choosed every time.
defaultTimes={[hour+':'+minute,hour+':'+minute]}
// ['hh:mm', 'hh:mm']
// This is the value you choosed every time.
initialDates={[year+'-'+month+'-'+date,year+'-'+month+'-'+date]}
// ['YYYY-MM-DD', 'YYYY-MM-DD']
// This is the initial dates.
// If provied, input will be reset to this value when the clear icon hits,
// otherwise input will be display placeholder
initialTimes={[hour+':'+minute,hour+':'+minute]}
// ['hh:mm', 'hh:mm']
// This is the initial times.
// If provied, input will be reset to this value when the clear icon hits,
// otherwise input will be display placeholder
/>
```

Expand Down
79 changes: 58 additions & 21 deletions example/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import prefixAll from 'inline-style-prefix-all';
import Prism from 'prismjs';
import 'prismjs/themes/prism-tomorrow.css';
import '../src/css/example.css';
// import { CalendarPicker, RangePicker } from '../src/js/component/index.js';
import { CalendarPicker, RangePicker } from '../lib/components/index.js';
import { CalendarPicker, RangePicker } from '../src/js/component/index.js';
// import { CalendarPicker, RangePicker } from '../lib/components/index.js';
import '../src/js/component/react-minimal-datetime-range.css';
// import '../lib/react-minimal-datetime-range.min.css';
const CodeBlock = ({ literal, language }) => {
Expand All @@ -29,16 +29,32 @@ CodeBlock.propTypes = {
language: PropTypes.string,
};

const now = new Date();
if (!String.prototype.padStart) {
String.prototype.padStart = function padStart(targetLength, padString) {
targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0;
padString = String(typeof padString !== 'undefined' ? padString : ' ');
if (this.length >= targetLength) {
return String(this);
} else {
targetLength = targetLength - this.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
}
return padString.slice(0, targetLength) + String(this);
}
};
}
const Component = () => {
const $passwordWrapperRef = useRef(null);
const $pinWrapperRef = useRef(null);
const $activationWrapperRef = useRef(null);
const [showCalendarPicker, setShowCalendarPicker] = useState(true);
const [hour, setHour] = useState('03');
const [minute, setMinute] = useState('10');
const [month, setMonth] = useState('01');
const [date, setDate] = useState('30');
const [year, setYear] = useState('2000');
const [hour, setHour] = useState('01');
const [minute, setMinute] = useState('01');
const [month, setMonth] = useState(String(now.getMonth() + 1).padStart(2, '0'));
const [date, setDate] = useState(String(now.getDate()).padStart(2, '0'));
const [year, setYear] = useState(String(now.getFullYear()));
return (
<div className={'wrapper'}>
<div>
Expand Down Expand Up @@ -71,16 +87,17 @@ const Component = () => {
</div>
</div>
<div style={prefixAll({ flex: '0 0 40%' })}>
<Markdown
source={`\`\`\`javascript
<div style={{ maxWidth: '800px' }}>
<Markdown
source={`\`\`\`javascript
import { CalendarPicker } from 'react-minimal-datetime-range';
import 'react-minimal-datetime-range/lib/react-minimal-datetime-range.min.css';
<CalendarPicker
locale="en-us" // default is en-us
show={showCalendarPicker} //default is false
allowPageClickToClose={true} // default is true
onClose={() => setShowCalendarPicker(false)}
defaultDate={year + '-' + month + '-' + date} // OPTIONAL. format: "YYYY-MM-DD"
defaultDate={year+'-'+month+'-'+date} // OPTIONAL. format: "YYYY-MM-DD"
onYearPicked={res => console.log(res)}
onMonthPicked={res => console.log(res)}
onDatePicked={res => console.log(res)}
Expand All @@ -89,8 +106,9 @@ import 'react-minimal-datetime-range/lib/react-minimal-datetime-range.min.css';
style={{ width: '300px', margin: '10px auto 0' }}
/>
\`\`\``}
renderers={{ CodeBlock }}
/>
renderers={{ CodeBlock }}
/>
</div>
</div>
</div>
<div>
Expand All @@ -107,33 +125,52 @@ import 'react-minimal-datetime-range/lib/react-minimal-datetime-range.min.css';
placeholder={['Start Time', 'End Time']}
defaultDates={[year + '-' + month + '-' + date, year + '-' + month + '-' + date]} // ['YYYY-MM-DD', 'YYYY-MM-DD']
defaultTimes={[hour + ':' + minute, hour + ':' + minute]} // ['hh:mm', 'hh:mm']
initialDates={[year + '-' + month + '-' + date, year + '-' + month + '-' + date]} // ['YYYY-MM-DD', 'YYYY-MM-DD']
initialTimes={[hour + ':' + minute, hour + ':' + minute]} // ['hh:mm', 'hh:mm']
onConfirm={res => console.log(res)}
onClose={() => console.log('closed')}
style={{ width: '300px', margin: '0 auto' }}
/>
</div>
</div>
<div style={prefixAll({ flex: '0 0 40%' })}>
<Markdown
source={`\`\`\`javascript
<div style={{ maxWidth: '800px' }}>
<Markdown
source={`\`\`\`javascript
import { RangePicker } from 'react-minimal-datetime-range';
import 'react-minimal-datetime-range/lib/react-minimal-datetime-range.min.css';
<RangePicker
locale="en-us" // default is en-us
show={false} // default is false
allowPageClickToClose={true} // default is true
placeholder={['Start Time', 'End Time']}
defaultDates={[year + '-' + month + '-' + date, year + '-' + month + '-' + date]}
// ['YYYY-MM-DD', 'YYYY-MM-DD']
defaultTimes={[hour + ':' + minute, hour + ':' + minute]}
// ['hh:mm', 'hh:mm']
onConfirm={res => console.log(res)}
onClose={() => console.log('closed')}
style={{ width: '300px', margin: '0 auto' }}
placeholder={['Start Time', 'End Time']}
////////////////////
// IMPORTANT DESC //
////////////////////
defaultDates={[year+'-'+month+'-'+date,year+'-'+month+'-'+date]}
// ['YYYY-MM-DD', 'YYYY-MM-DD']
// This is the value you choosed every time.
defaultTimes={[hour+':'+minute,hour+':'+minute]}
// ['hh:mm', 'hh:mm']
// This is the value you choosed every time.
initialDates={[year+'-'+month+'-'+date,year+'-'+month+'-'+date]}
// ['YYYY-MM-DD', 'YYYY-MM-DD']
// This is the initial dates.
// If provied, input will be reset to this value when the clear icon hits,
// otherwise input will be display placeholder
initialTimes={[hour+':'+minute,hour+':'+minute]}
// ['hh:mm', 'hh:mm']
// This is the initial times.
// If provied, input will be reset to this value when the clear icon hits,
// otherwise input will be display placeholder
/>
\`\`\``}
renderers={{ CodeBlock }}
/>
renderers={{ CodeBlock }}
/>
</div>
</div>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-minimal-datetime-range",
"version": "1.4.0",
"version": "1.4.1",
"description": "A react component for date time range picker.",
"main": "index.js",
"repository": {
Expand Down
73 changes: 42 additions & 31 deletions src/js/component/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef, useMemo, useCallback, memo } from 'react';
import { cx, isValidDate } from './utils.js';
import { cx, isValidDates } from './utils.js';
import LOCALE from './locale.js';
import Calendar from './Calendar.js';
import RangeDate from './RangeDate.js';
Expand Down Expand Up @@ -133,24 +133,16 @@ export const RangePicker = memo(
placeholder = ['', ''],
defaultDates = ['', ''],
defaultTimes = ['', ''],
initialDates = ['', ''],
initialTimes = ['', ''],
onConfirm = () => {},
onClear = () => {},
onClose = () => {},
style = {},
}) => {
// ['YYYY-MM-DD', 'YYYY-MM-DD'] // ['hh:mm', 'hh:mm']
const isDefaultDatesValid = useMemo(() => {
let isValid = false;
if (defaultDates.length === 2) {
isValid = true;
defaultDates.forEach(defaultDate => {
if (!isValidDate(defaultDate)) {
isValid = false;
}
});
}
return isValid;
}, [defaultDates]);
const isDefaultDatesValid = isValidDates(defaultDates);
const isInitialDatesValid = isValidDates(initialDates);
const [selected, setSelected] = useState(isDefaultDatesValid ? true : false);
const [start, setStart] = useState(defaultDates[0] ? `${defaultDates[0]} ${defaultTimes[0] ? defaultTimes[0] : ''}` : '');
const [end, setEnd] = useState(defaultDates[1] ? `${defaultDates[1]} ${defaultTimes[1] ? defaultTimes[1] : ''}` : '');
Expand Down Expand Up @@ -209,27 +201,46 @@ export const RangePicker = memo(
setType(TYPES[0]);
}
}, [type]);
const handleOnConfirm = useCallback(() => {
const a = new Date(startDatePickedArray.join('-'));
const b = new Date(endDatePickedArray.join('-'));
const starts = a < b ? startDatePickedArray : endDatePickedArray;
const ends = a > b ? startDatePickedArray : endDatePickedArray;
const startStr = `${starts.join('-')} ${startTimePickedArray.join(':')}`;
const endStr = `${ends.join('-')} ${endTimePickedArray.join(':')}`;
setStart(startStr);
setEnd(endStr);
setStartDatePickedArray(starts);
setEndDatePickedArray(ends);
setDates([starts.join('-'), ends.join('-')]);
setInternalShow(false);
onConfirm && onConfirm([startStr, endStr]);
}, [startDatePickedArray, endDatePickedArray, startTimePickedArray, endTimePickedArray]);
const handleOnConfirm = useCallback(
(e, sd, ed, st, et) => {
if (!sd) {
sd = startDatePickedArray;
}
if (!ed) {
ed = endDatePickedArray;
}
if (!st) {
st = startTimePickedArray;
}
if (!et) {
et = endTimePickedArray;
}
const a = new Date(sd.join('-'));
const b = new Date(ed.join('-'));
const starts = a < b ? sd : ed;
const ends = a > b ? sd : ed;
const startStr = `${starts.join('-')} ${st.join(':')}`;
const endStr = `${ends.join('-')} ${et.join(':')}`;
setStart(startStr);
setEnd(endStr);
setStartDatePickedArray(starts);
setEndDatePickedArray(ends);
setDates([starts.join('-'), ends.join('-')]);
setInternalShow(false);
onConfirm && onConfirm([startStr, endStr]);
},
[startDatePickedArray, endDatePickedArray, startTimePickedArray, endTimePickedArray],
);
const handleOnClear = useCallback(
e => {
if (disabled) {
return;
}
e.stopPropagation();
if (isInitialDatesValid) {
handleOnConfirm({}, initialDates[0].split('-'), initialDates[1].split('-'), initialTimes[0].split(':'), initialTimes[1].split(':'));
return;
}
setSelected(false);
setInternalShow(false);
setStart('');
Expand All @@ -242,7 +253,7 @@ export const RangePicker = memo(
setEndTimePickedArray(['00', '00']);
onClear && onClear();
},
[disabled],
[disabled, initialDates, initialTimes],
);
useEffect(() => {
setType(TYPES[0]);
Expand Down Expand Up @@ -279,15 +290,15 @@ export const RangePicker = memo(
},
[allowPageClickToClose],
);
const isDefault = useMemo(() => start === `${defaultDates[0]} ${defaultTimes[0]}` && end === `${defaultDates[1]} ${defaultTimes[1]}`, [start, end]);
const isInitial = useMemo(() => start === `${initialDates[0]} ${initialTimes[0]}` && end === `${initialDates[1]} ${initialTimes[1]}`, [start, end]);
const isEmpty = useMemo(() => !start && !end, [start, end]);
return (
<div className="react-minimal-datetime-range__range" style={style}>
<span className={`react-minimal-datetime-range__range-input-wrapper ${disabled && 'disabled'}`} onClick={() => !disabled && setInternalShow(!internalShow)}>
<input readOnly={true} placeholder={placeholder[0]} className={`react-minimal-datetime-range__range-input ${disabled && 'disabled'}`} value={start} />
<span className="react-minimal-datetime-range__range-input-separator"> ~ </span>
<input readOnly={true} placeholder={placeholder[1]} className={`react-minimal-datetime-range__range-input ${disabled && 'disabled'}`} value={end} />
{!isDefault && !isEmpty ? (
{!isInitial && !isEmpty ? (
<svg className={`react-minimal-datetime-range__clear ${disabled && 'disabled'}`} width="15" height="15" viewBox="0 0 24 24" onClick={handleOnClear}>
<path
className="react-minimal-datetime-range__icon-fill"
Expand Down
13 changes: 12 additions & 1 deletion src/js/component/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export const cx = (...params) => {
}
return classes.join(' ');
};

export const isValidDate = str => {
try {
const d = new Date(str);
Expand All @@ -33,3 +32,15 @@ export const isValidDate = str => {
return false;
}
};
export const isValidDates = arr => {
let isValid = false;
if (arr.length === 2) {
isValid = true;
arr.forEach(v => {
if (!isValidDate(v)) {
isValid = false;
}
});
}
return isValid;
};

0 comments on commit 45e085a

Please sign in to comment.