Skip to content

Commit

Permalink
fix: Add option callback to Calendar plugin (#839)
Browse files Browse the repository at this point in the history
  • Loading branch information
edumoreira1506 authored Mar 24, 2020
1 parent 669968e commit b25be90
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/plugin/calendar/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ export default (o, c, d) => {
sameElse: L
}
const proto = c.prototype
proto.calendar = function (referenceTime, formats) {
const format = formats || this.$locale().calendar || calendarFormat
proto.calendar = function (referenceTime, callbacks) {
const format = callbacks || this.$locale().calendar || calendarFormat
const referenceStartOfDay = d(referenceTime || undefined).startOf('d')
const diff = this.diff(referenceStartOfDay, 'd', true)
const sameElse = 'sameElse'
Expand All @@ -23,7 +23,12 @@ export default (o, c, d) => {
diff < 2 ? 'nextDay' :
diff < 7 ? 'nextWeek' : sameElse
/* eslint-enable no-nested-ternary */
return this.format(format[retVal] || calendarFormat[retVal])
const currentFormat = format[retVal] || calendarFormat[retVal]
if (typeof currentFormat === 'function') {
return currentFormat(referenceStartOfDay)
}
const formattedDate = this.format(currentFormat)
return formattedDate
}
}

38 changes: 38 additions & 0 deletions test/plugin/calendar.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,44 @@ it('Custom format', () => {
.toEqual(moment(now).calendar(nextDayWithoutFormat, format))
})

it('Custom callback', () => {
const callbacks = {
sameDay: jest.fn(),
sameElse: jest.fn()
}
const now = '2015-01-15T14:21:22.000Z'
const nextDayWithoutFormat = '2015-01-14T11:23:55.000Z'
expect(dayjs(now).calendar(nextDayWithoutFormat, callbacks))
.toEqual(moment(now).calendar(nextDayWithoutFormat, callbacks))
})

it('Calls callback', () => {
const callbacks = {
sameDay: jest.fn(),
sameElse: jest.fn()
}
dayjs().calendar(null, callbacks)
expect(callbacks.sameElse).not.toBeCalled()
expect(callbacks.sameDay).toBeCalled()
})

it('callback is a function with the scope of the current moment', () => {
const callbacks = {
sameDay: jest.fn(),
sameElse: jest.fn()
}
expect(dayjs().calendar(null, callbacks)).toEqual(callbacks.sameDay())
})

it('callback is a function and first argument a moment that depicts now', () => {
const callbacks = {
sameDay: jest.fn()
}
const now = dayjs()
dayjs(now).calendar(now, callbacks)
expect(callbacks.sameDay).toBeCalledWith(now.startOf('d'))
})

it('set global calendar in locale file', () => {
const now = '2019-04-03T14:21:22.000Z'
zhCn.calendar = {
Expand Down

0 comments on commit b25be90

Please sign in to comment.