|
| 1 | +import { setDateLocalizer } from './dateLocalizer' |
| 2 | + |
| 3 | +export default function(moment) { |
| 4 | + if (!moment) throw Error('\'moment\' should be truthy'); |
| 5 | + |
| 6 | + if (typeof moment !== 'function') |
| 7 | + throw new TypeError('You must provide a valid moment object'); |
| 8 | + |
| 9 | + let localField = typeof moment().locale === 'function' ? 'locale' : 'lang'; |
| 10 | + |
| 11 | + if (!moment.localeData) |
| 12 | + throw new TypeError('The Moment localizer depends on the `localeData` api, please provide a moment object v2.2.0 or higher'); |
| 13 | + |
| 14 | + let getMoment = (culture, value, format) => culture ? moment(value, format)[localField](culture) : moment(value, format); |
| 15 | + |
| 16 | + let endOfDecade = (date) => moment(date).add(10, 'year').add(-1, 'millisecond').toDate(); |
| 17 | + |
| 18 | + let endOfCentury = (date) => moment(date).add(100, 'year').add(-1, 'millisecond').toDate(); |
| 19 | + |
| 20 | + let localizer = { |
| 21 | + formats: { |
| 22 | + date: 'L', |
| 23 | + time: 'LT', |
| 24 | + default: 'lll', |
| 25 | + header: 'MMMM YYYY', |
| 26 | + footer: 'LL', |
| 27 | + weekday: 'dd', |
| 28 | + dayOfMonth: 'DD', |
| 29 | + month: 'MMM', |
| 30 | + year: 'YYYY', |
| 31 | + |
| 32 | + decade(date, culture, localizer) { |
| 33 | + return localizer.format(date, 'YYYY', culture) |
| 34 | + + ' - ' + localizer.format(endOfDecade(date), 'YYYY', culture) |
| 35 | + }, |
| 36 | + |
| 37 | + century(date, culture, localizer) { |
| 38 | + return localizer.format(date, 'YYYY', culture) |
| 39 | + + ' - ' + localizer.format(endOfCentury(date), 'YYYY', culture) |
| 40 | + } |
| 41 | + }, |
| 42 | + |
| 43 | + firstOfWeek(culture) { |
| 44 | + return moment.localeData(culture).firstDayOfWeek() |
| 45 | + }, |
| 46 | + |
| 47 | + parse(value, format, culture) { |
| 48 | + if (!value) return undefined; // localizers should return undefined for empty inputs |
| 49 | + const m = getMoment(culture, value, format); |
| 50 | + if (m.isValid()) return m.toDate(); |
| 51 | + return null; // localizers should return nul for invalid inputs |
| 52 | + }, |
| 53 | + |
| 54 | + format(value, format, culture) { |
| 55 | + return getMoment(culture, value).format(format) |
| 56 | + } |
| 57 | + }; |
| 58 | + |
| 59 | + setDateLocalizer(localizer); |
| 60 | + |
| 61 | + return localizer; |
| 62 | +} |
0 commit comments