This repository has been archived by the owner on Aug 30, 2019. It is now read-only.
Calendar component - Issue #36 (WIP) #45
Merged
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
71b681b
Changes the builder to use the util.inspect() to output the error
cb93c82
Adds the examples with a normal calendar with all props set and a ran…
2a0146f
Fixes issue where renderDate was not between the min and max limits, …
01bc264
Fixes issue where in the edge-months (0 and 11) we were doing imprope…
201061b
Updates the snapshots and the tests to cover properly with the new ch…
0d85c3d
Fixes poor configuration on the .eslintrc
c929a9a
Improved readability on the ternary operator of the handling of the r…
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,314 @@ | ||
import React, { Component, PropTypes } from 'react'; | ||
import { getClassNamesWithMods, getDataAttributes, normalizeDate } from '../_helpers'; | ||
import DaysPanel from './panels/days'; | ||
import calendarConstants from './constants/calendar'; | ||
|
||
const { | ||
CALENDAR_MOVE_TO_NEXT, | ||
CALENDAR_MOVE_TO_PREVIOUS, | ||
CALENDAR_SELECTION_TYPE_RANGE, | ||
} = calendarConstants; | ||
|
||
|
||
/** | ||
* Processes the given props and the existing state and returns | ||
* a new state. | ||
* | ||
* @function processProps | ||
* @param {Object} props Props to base the new state on. | ||
* @param {Object} state (Existing) state to be based on for the existing values. | ||
* @return {Object} New state to be set/used. | ||
* @static | ||
*/ | ||
function processProps(props) { | ||
const { initialDates, maxDate, minDate, selectionType } = props; | ||
const maxLimit = maxDate ? normalizeDate(new Date(maxDate), 23, 59, 59, 999) : null; | ||
const renderDate = normalizeDate(((initialDates && initialDates.length && initialDates[0]) | ||
? new Date(initialDates[0]) | ||
: new Date())); | ||
|
||
let minLimit = minDate ? normalizeDate(new Date(minDate)) : null; | ||
let selectedDates = [null, null]; | ||
|
||
if (initialDates) { | ||
selectedDates = selectedDates.map((item, idx) => { | ||
if (!initialDates[idx]) { | ||
return null; | ||
} | ||
|
||
return normalizeDate(new Date(initialDates[idx])); | ||
}); | ||
} | ||
|
||
/** | ||
* If a minDate or a maxDate is set, let's check if any selectedDates are outside of the boundaries. | ||
* If so, resets the selectedDates. | ||
*/ | ||
if (minLimit || maxLimit) { | ||
const isAnyDateOutOfLimit = selectedDates.some(item => ( | ||
item && ( | ||
(minLimit && (minLimit.getTime() > item.getTime())) || | ||
(maxLimit && (maxLimit.getTime() < item.getTime())) | ||
) | ||
)); | ||
|
||
if (isAnyDateOutOfLimit) { | ||
selectedDates = [null, null]; | ||
console.warn(`A calendar instance contains a selectedDate outside of the minDate and maxDate boundaries`); // eslint-disable-line | ||
} | ||
} | ||
|
||
/** If initialDates is defined and we have a start date, we want to set it as the minLimit */ | ||
if (selectedDates[0] && (selectionType === CALENDAR_SELECTION_TYPE_RANGE)) { | ||
minLimit = selectedDates[0]; | ||
} | ||
|
||
/** If the renderDate is not between any of the minLimit and/or maxDate, we need to redefine it. */ | ||
if ( | ||
(minLimit && (renderDate.getMonth() < minLimit.getMonth())) || | ||
(maxLimit && (renderDate.getMonth() > maxLimit.getMonth())) | ||
) { | ||
renderDate.setMonth(minLimit.getMonth()); | ||
} | ||
|
||
return { | ||
maxLimit, | ||
minLimit, | ||
renderDate, | ||
selectedDates, | ||
}; | ||
} | ||
|
||
export default class Calendar extends Component { | ||
constructor(props) { | ||
super(); | ||
|
||
this.moveToMonth = this.moveToMonth.bind(this); | ||
this.state = processProps(props); | ||
} | ||
|
||
componentWillReceiveProps(newProps) { | ||
const { initialDates, maxDate, minDate, selectionType } = newProps; | ||
|
||
let propsChanged = ( | ||
(maxDate !== this.props.maxDate) || | ||
(minDate !== this.props.minDate) || | ||
(selectionType !== this.props.selectionType) | ||
); | ||
|
||
if (initialDates) { | ||
if (this.props.initialDates) { | ||
propsChanged = propsChanged || initialDates.some((item, idx) => item !== this.props.initialDates[idx]); | ||
} else { | ||
propsChanged = true; | ||
} | ||
} | ||
|
||
if (propsChanged) { | ||
this.setState(() => processProps(newProps)); | ||
} | ||
} | ||
|
||
/** | ||
* Changes the renderDate of the calendar to the previous or next month. | ||
* Also triggers the onNavPreviousMonth/onNavNextMonth when the state gets changed | ||
* and passes the new date to it. | ||
* | ||
* @method moveToMonth | ||
* @param {String} direction Defines to which month is the calendar moving (previous or next). | ||
*/ | ||
moveToMonth(direction) { | ||
const { onNavNextMonth, onNavPreviousMonth } = this.props; | ||
|
||
this.setState(({ renderDate }) => { | ||
renderDate.setMonth(renderDate.getMonth() + (direction === CALENDAR_MOVE_TO_PREVIOUS ? -1 : 1)); | ||
return { renderDate }; | ||
}, () => { | ||
if ((direction === CALENDAR_MOVE_TO_PREVIOUS) && onNavPreviousMonth) { | ||
onNavPreviousMonth(this.state.renderDate); | ||
} else if ((direction === CALENDAR_MOVE_TO_NEXT) && onNavNextMonth) { | ||
onNavNextMonth(this.state.renderDate); | ||
} | ||
}); | ||
} | ||
|
||
/** | ||
* Handler for the day's selection. Passed to the DaysPanel -> DaysView. | ||
* Also triggers the onSelectDay function (when passed) after the state is updated, | ||
* passing the selectedDates array to it. | ||
* | ||
* @method onSelectDay | ||
* @param {Date} dateSelected Date selected by the user. | ||
*/ | ||
onSelectDay(dateSelected) { | ||
const { onSelectDay, selectionType, minDate } = this.props; | ||
|
||
this.setState((prevState) => { | ||
let { minLimit, renderDate, selectedDates } = prevState; | ||
|
||
/** | ||
* If the calendar's selectionType is 'normal', we always set the date selected | ||
* to the first position of the selectedDates array. | ||
* If the selectionType is 'range', we need to verify the following requirements: | ||
* | ||
* - If there's no start date selected, then the selected date becomes the start | ||
* date and the minLimit becomes that same date. Prevents the range selection to the past. | ||
* | ||
* - If there's a start date already selected: | ||
* | ||
* - If there's no end date selected, then the selected date becomes the end date. Also | ||
* if the start and end dates are the same, it will remove the minLimit as the layout renders | ||
* them as a 'normal' selection. | ||
* | ||
* - If there's an end date selected and the user is clicking on the start date again, it | ||
* clears the selections and the limits, resetting the range. | ||
*/ | ||
if (selectionType === CALENDAR_SELECTION_TYPE_RANGE) { | ||
if (selectedDates[0]) { | ||
if (!selectedDates[1]) { | ||
selectedDates[1] = dateSelected; | ||
if (selectedDates[0].toDateString() === selectedDates[1].toDateString()) { | ||
minLimit = minDate ? normalizeDate(new Date(minDate)) : null; | ||
} | ||
} else { | ||
selectedDates = [null, null]; | ||
minLimit = minDate ? normalizeDate(new Date(minDate)) : null; | ||
} | ||
} else { | ||
selectedDates[0] = dateSelected; | ||
minLimit = dateSelected; | ||
selectedDates[1] = null; | ||
} | ||
} else { | ||
selectedDates[0] = dateSelected; | ||
} | ||
|
||
/** | ||
* If the user selects a day of the previous or next month, the rendered month switches to | ||
* the one of the selected date. | ||
*/ | ||
if (dateSelected.getMonth() !== renderDate.getMonth()) { | ||
renderDate = new Date(dateSelected.toDateString()); | ||
} | ||
|
||
return { | ||
minLimit, | ||
renderDate, | ||
selectedDates, | ||
}; | ||
}, () => { | ||
if (onSelectDay) { | ||
onSelectDay(this.state.selectedDates); | ||
} | ||
}); | ||
} | ||
|
||
render() { | ||
const { dataAttrs = {}, isDaySelectableFn, locale, mods = [], navButtons, selectionType } = this.props; | ||
const { maxLimit, minLimit, renderDate, selectedDates } = this.state; | ||
|
||
const restProps = getDataAttributes(dataAttrs); | ||
const className = getClassNamesWithMods('ui-calendar', mods); | ||
|
||
return ( | ||
<div className={className} {...restProps}> | ||
<DaysPanel | ||
isDaySelectableFn={isDaySelectableFn} | ||
locale={locale} | ||
maxDate={maxLimit} | ||
minDate={minLimit} | ||
navButtons={navButtons} | ||
onNavNextMonth={() => this.moveToMonth(CALENDAR_MOVE_TO_NEXT)} | ||
onNavPreviousMonth={() => this.moveToMonth(CALENDAR_MOVE_TO_PREVIOUS)} | ||
onSelectDay={dt => this.onSelectDay(dt)} | ||
renderDate={renderDate} | ||
selectedDates={selectedDates} | ||
selectionType={selectionType} | ||
/> | ||
</div> | ||
); | ||
} | ||
} | ||
|
||
Calendar.defaultProps = { | ||
selectionType: 'normal', | ||
}; | ||
|
||
Calendar.propTypes = { | ||
/** | ||
* Data attribute. You can use it to set up GTM key or any custom data-* attribute | ||
*/ | ||
dataAttrs: PropTypes.oneOfType([ | ||
PropTypes.bool, | ||
PropTypes.object, | ||
]), | ||
|
||
/** | ||
* Optional. Initial value of the calendar. Defaults to the current date as per the locale. | ||
*/ | ||
initialDates: PropTypes.array, | ||
|
||
/** | ||
* Optional. Function to be triggered to evaluate if the date (passed as an argument) | ||
* is selectable. Must return a boolean. | ||
*/ | ||
isDaySelectableFn: PropTypes.func, | ||
|
||
/** | ||
* Locale definitions, with the calendar's months and weekdays in the right language. | ||
* Also contains the startWeekDay which defines in which week day starts the week. | ||
*/ | ||
locale: PropTypes.shape({ | ||
months: PropTypes.array, | ||
weekDays: PropTypes.array, | ||
startWeekDay: PropTypes.number, | ||
}), | ||
|
||
/** | ||
* Sets the max date boundary. Defaults to `null`. | ||
*/ | ||
maxDate: PropTypes.string, | ||
|
||
/** | ||
* Sets the min date boundary. Defaults to `null`. | ||
*/ | ||
minDate: PropTypes.string, | ||
|
||
/** | ||
* You can provide set of custom modifications. | ||
*/ | ||
mods: PropTypes.arrayOf(PropTypes.string), | ||
|
||
navButtons: PropTypes.shape({ | ||
days: PropTypes.shape({ | ||
next: PropTypes.shape({ | ||
ariaLabel: PropTypes.string, | ||
displayValue: PropTypes.string, | ||
}), | ||
previous: PropTypes.shape({ | ||
ariaLabel: PropTypes.string, | ||
displayValue: PropTypes.string, | ||
}), | ||
}), | ||
}), | ||
|
||
/** | ||
* Function to be triggered when pressing the nav's "next" button. | ||
*/ | ||
onNavNextMonth: PropTypes.func, | ||
|
||
/** | ||
* Function to be triggered when pressing the nav's "previous" button. | ||
*/ | ||
onNavPreviousMonth: PropTypes.func, | ||
|
||
/** | ||
* Function to be triggered when selecting a day. | ||
*/ | ||
onSelectDay: PropTypes.func, | ||
|
||
/** | ||
* Optional. Type of date selection. | ||
*/ | ||
selectionType: PropTypes.oneOf(['normal', 'range']), | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
does it have any side-effect?
what happens to the original Date object, that is passed to this Calendar component from parent component?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@fahad19 it is mutated. But that's what happens when you call
.setHours()
or any of it's sister functions :)But that's why it's called normalizeDate and not returnNewNormalizedDate or something 😄
However, side effects imply that the function is changing things that are not passed to it - implying knowledge of variables outside it's scope, etc - which is not the case.
Regarding your last question, if you check this exact code, it's doing a new Date() of the string coming from the
initialDates[0]
(when applicable)...I will improve a little bit the readability.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is there any specific reason for choosing the approach of
normalizeDate()
overreturnNewNormalizedDate()
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@fahad19 check if it's better :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I agree with you about what you mentioned about side-effects. The only problem we have here is that it is still referencing the parent Component's props.
I would always avoid props mutation of any kind in React. If I really need to transform the value in some way, and expect the Component to re-render on further changes, I would use
.setState()
, and scope it under the current Component only. Without affecting parent(s).Similar issue was found in another PR few weeks ago. I think @asci wanted to created a Story out of it so all affected components are updated to avoid this issue.