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

Use moment locales for customization #277

Merged
merged 6 commits into from
Feb 14, 2016
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
28 changes: 12 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,28 +51,24 @@ var Example = React.createClass({

## Configuration

The default Datepicker can be initialised by:
The most basic use of the DatePicker can be described with:

```js
<DatePicker
selected={this.state.startDate}
onChange={this.handleChange} />
<DatePicker selected={this.state.date} onChange={this.handleChange} />
```

This included the Datepicker with its default functionality. To use more functionality you can pass extra props to the Datepicker to enable them.
See [here](https://github.com/Hacker0x01/react-datepicker/blob/master/docs/datepicker.md) for a full list of props that may be passed to the component. Examples are given on the [main website](https://hacker0x01.github.io/react-datepicker).

### Localization

The date picker relies on [moment.js internationalization](http://momentjs.com/docs/#/i18n/) to localize its display components. By default, the date picker will use the locale globally set in moment, which is English. Locales can be changed in the following ways:

- **Globally** by calling `moment.locale(lang)`
- **Picker-specific** by providing the `locale` prop

- Change date format by passing a different date format in the props: `dateFormat: “YYYY/MM/DD”`
- Add placeholder text: `placeholderText: 'Click to select a date'` (Defaults to the selected date when no placeholder text is added)
- Give users a predefined date range: `minDate: moment()` & `maxDate: moment().add(5, 'days')` (this gives users the ability to select a date between today and 5 days in the future)
- Exclude a set of dates from those that are selectable: `excludeDates: [ moment(), moment('2015-01-01') ]` (prevent users from selecting today or Jan 1st, 2015)
- Include a set of dates from those that are selectable: `includeDates: [ moment(), moment(‘2015-01-01’) ]` (allow users selecting only today or Jan 1st, 2015)
- Set custom moment.js instance (could have defined custom locale settings): `moment: require('./foo/moment')`
- Set custom locale settings for locale: `locale: 'cs'`
- Set date format for calendar: `dateFormatCalendar: 'YYYY/MM/DD'`
- Set custom weekdays (for locale days): `weekdays: ['Ne', 'Po', 'Út', 'St', 'Čt', 'Pá', 'So']`
- Set custom calendar week start day: `weekStart: '0'` would start the week on Sunday
Locales can be further configured in moment with various [customization options](http://momentjs.com/docs/#/customization/).

More information about the different ways to customise available at https://hacker0x01.github.io/react-datepicker.
_As of version 0.23, the `weekdays` and `weekStart` DatePicker props have been removed. Instead, they can be configured with the `weekdaysMin` and `week.dow` moment locale customization options._

## Compatibility

Expand Down
11 changes: 3 additions & 8 deletions docs-site/src/example_components.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@ import CustomDateFormat from "./examples/custom_date_format";
import CustomClassName from "./examples/custom_class_name";
import PlaceholderText from "./examples/placeholder_text";
import SpecificDateRange from "./examples/specific_date_range";
import CustomStartDate from "./examples/custom_start_date";
import Locale from "./examples/locale";
import ExcludeDates from "./examples/exclude_dates";
import IncludeDates from "./examples/include_dates";
import FilterDates from "./examples/filter_dates";
import Disabled from "./examples/disabled";
import ClearInput from "./examples/clear_input";
import OnBlurCallbacks from "./examples/on_blur_callbacks";
import Weekdays from "./examples/weekdays";
import Placement from "./examples/placement";
import DateRange from "./examples/date_range";
import TabIndex from "./examples/tab_index";
Expand Down Expand Up @@ -65,8 +64,8 @@ export default React.createClass({
component: <SpecificDateRange />
},
{
title: "Custom week start day",
component: <CustomStartDate />
title: "Locale",
component: <Locale />
},
{
title: "Exclude dates",
Expand Down Expand Up @@ -96,10 +95,6 @@ export default React.createClass({
title: "onBlur callbacks in console",
component: <OnBlurCallbacks />
},
{
title: "Custom weekdays",
component: <Weekdays />
},
{
title: "Configure Popover Placement",
component: <Placement />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,16 @@ export default React.createClass({
{"<DatePicker"}<br />
    {"selected={this.state.startDate}"}<br />
    {"onChange={this.handleChange}"}<br />
<strong>    {"weekStart='0'"}</strong><br />
    {"placeholderText='I start on Sunday!' />"}
<strong>    {"locale='en-gb'"}</strong><br />
    {"placeholderText='Weeks start on Monday' />"}
</code>
</pre>
<div className="column">
<DatePicker
selected={this.state.startDate}
onChange={this.handleChange}
weekStart="0"
placeholderText="I start on Sunday!" />
locale="en-gb"
placeholderText="Weeks start on Monday" />
</div>
</div>;
}
Expand Down
38 changes: 0 additions & 38 deletions docs-site/src/examples/weekdays.jsx

This file was deleted.

40 changes: 13 additions & 27 deletions src/calendar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ var Calendar = React.createClass({
mixins: [require("react-onclickoutside")],

propTypes: {
weekdays: React.PropTypes.array.isRequired,
locale: React.PropTypes.string.isRequired,
locale: React.PropTypes.string,
moment: React.PropTypes.func.isRequired,
dateFormat: React.PropTypes.string.isRequired,
onSelect: React.PropTypes.func.isRequired,
Expand All @@ -33,7 +32,6 @@ var Calendar = React.createClass({
excludeDates: React.PropTypes.array,
includeDates: React.PropTypes.array,
filterDate: React.PropTypes.func,
weekStart: React.PropTypes.string.isRequired,
showYearDropdown: React.PropTypes.bool
},

Expand All @@ -43,38 +41,20 @@ var Calendar = React.createClass({

getInitialState() {
return {
date: getDateInView(this.props)
date: this.localizeMoment(getDateInView(this.props))
};
},

getDefaultProps() {
return {
weekStart: "1"
};
},

componentWillMount() {
this.initializeMomentLocale();
},

componentWillReceiveProps(nextProps) {
if (nextProps.selected && !isSameDay(nextProps.selected, this.props.selected)) {
this.setState({
date: nextProps.selected
date: this.localizeMoment(nextProps.selected)
});
}
},

initializeMomentLocale() {
var weekdays = this.props.weekdays.slice(0);
weekdays = weekdays.concat(weekdays.splice(0, this.props.weekStart));

this.props.moment.locale(this.props.locale, {
week: {
dow: this.props.weekStart
},
weekdaysMin: weekdays
});
localizeMoment(date) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Localizing the moment as soon as it's passed in allows the localization to be passed to weekdays and week start automatically.

return date.clone().locale(this.props.locale || this.props.moment.locale());
},

increaseMonth() {
Expand All @@ -100,8 +80,14 @@ var Calendar = React.createClass({
},

header() {
return this.props.moment.weekdaysMin().map(function(day, key) {
return <div className="datepicker__day" key={key}>{day}</div>;
const startOfWeek = this.state.date.clone().startOf("week");
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the best I could come up with without digging into moment internal fields =(

return [0, 1, 2, 3, 4, 5, 6].map(offset => {
const day = startOfWeek.clone().add(offset, "days");
return (
<div key={offset} className="datepicker__day">
{day.localeData().weekdaysMin(day)}
</div>
);
});
},

Expand Down
5 changes: 4 additions & 1 deletion src/date_input.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ var DateInput = React.createClass({

propTypes: {
date: React.PropTypes.object,
locale: React.PropTypes.string,
minDate: React.PropTypes.object,
maxDate: React.PropTypes.object,
excludeDates: React.PropTypes.array,
Expand Down Expand Up @@ -50,7 +51,9 @@ var DateInput = React.createClass({
},

safeDateFormat(date) {
return !!date ? date.format(this.props.dateFormat) : null;
return date && date.clone()
.locale(this.props.locale || moment.locale())
.format(this.props.dateFormat);
},

handleKeyDown(event) {
Expand Down
7 changes: 1 addition & 6 deletions src/datepicker.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ var DatePicker = React.createClass({

propTypes: {
selected: React.PropTypes.object,
weekdays: React.PropTypes.arrayOf(React.PropTypes.string),
locale: React.PropTypes.string,
dateFormatCalendar: React.PropTypes.string,
disabled: React.PropTypes.bool,
Expand All @@ -22,7 +21,6 @@ var DatePicker = React.createClass({
popoverTargetAttachment: React.PropTypes.string,
popoverTargetOffset: React.PropTypes.string,
tetherConstraints: React.PropTypes.array,
weekStart: React.PropTypes.string,
showYearDropdown: React.PropTypes.bool,
onChange: React.PropTypes.func.isRequired,
onBlur: React.PropTypes.func,
Expand All @@ -34,8 +32,6 @@ var DatePicker = React.createClass({

getDefaultProps() {
return {
weekdays: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
locale: "en",
dateFormatCalendar: "MMMM YYYY",
onChange() {},
disabled: false,
Expand Down Expand Up @@ -110,7 +106,6 @@ var DatePicker = React.createClass({
}
return <Calendar
ref="calendar"
weekdays={this.props.weekdays}
locale={this.props.locale}
moment={moment}
dateFormat={this.props.dateFormatCalendar}
Expand All @@ -124,7 +119,6 @@ var DatePicker = React.createClass({
filterDate={this.props.filterDate}
onClickOutside={this.handleCalendarClickOutside}
includeDates={this.props.includeDates}
weekStart={this.props.weekStart}
showYearDropdown={this.props.showYearDropdown}
todayButton={this.props.todayButton} />;
},
Expand All @@ -151,6 +145,7 @@ var DatePicker = React.createClass({
id={this.props.id}
name={this.props.name}
date={this.props.selected}
locale={this.props.locale}
minDate={this.props.minDate}
maxDate={this.props.maxDate}
excludeDates={this.props.excludeDates}
Expand Down
4 changes: 2 additions & 2 deletions src/day.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ var Day = React.createClass({
},

isWeekend() {
const weekday = this.props.day.weekday();
return weekday === 5 || weekday === 6;
const weekday = this.props.day.day();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hooray for tests!

return weekday === 0 || weekday === 6;
},

isOutsideMonth() {
Expand Down
46 changes: 43 additions & 3 deletions test/calendar_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import Calendar from "../src/calendar";
import YearDropdown from "../src/year_dropdown";

describe("Calendar", function() {
var dateFormat = "MMMM YYYY";

function getCalendar(extraProps) {
return <Calendar
weekdays={["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]}
locale="en"
moment={moment}
dateFormat="MMMM"
dateFormat={dateFormat}
onSelect={() => {}}
onClickOutside={() => {}}
hideCalendar={() => {}}
Expand Down Expand Up @@ -73,4 +73,44 @@ describe("Calendar", function() {
expect(todayButton).to.exist;
expect(todayButton.textContent).to.equal("Vandaag");
});

describe("localization", function() {
function testLocale(calendar, selected, locale) {
var localized = selected.clone().locale(locale);

var calendarText = TestUtils.findRenderedDOMComponentWithClass(calendar, "datepicker__current-month");
expect(calendarText.textContent).to.equal(localized.format(dateFormat));

var firstDateOfWeek = localized.clone().startOf("week");
var firstWeekDayMin = firstDateOfWeek.localeData().weekdaysMin(firstDateOfWeek);
var firstHeader = TestUtils.scryRenderedDOMComponentsWithClass(calendar, "datepicker__day")[0];
expect(firstHeader.textContent).to.equal(firstWeekDayMin);
}

it("should use the globally-defined locale by default", function() {
var selected = moment();
var calendar = TestUtils.renderIntoDocument(getCalendar({ selected }));
testLocale(calendar, selected, moment.locale());
});

it("should use the locale specified as a prop", function() {
var locale = "fr";
var selected = moment().locale(locale);
var calendar = TestUtils.renderIntoDocument(getCalendar({ selected, locale }));
testLocale(calendar, selected, locale);
});

it("should override the locale of the date with the globally-defined locale", function() {
var selected = moment().locale("fr");
var calendar = TestUtils.renderIntoDocument(getCalendar({ selected }));
testLocale(calendar, selected, moment.locale());
});

it("should override the locale of the date with the locale prop", function() {
var locale = "fr";
var selected = moment();
var calendar = TestUtils.renderIntoDocument(getCalendar({ selected, locale }));
testLocale(calendar, selected, locale);
});
});
});
Loading