diff --git a/src/plugin/calendar/index.js b/src/plugin/calendar/index.js index e62e1fa38..2971f972d 100644 --- a/src/plugin/calendar/index.js +++ b/src/plugin/calendar/index.js @@ -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' @@ -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 } } diff --git a/test/plugin/calendar.test.js b/test/plugin/calendar.test.js index 31391ad06..5bf6fdae2 100644 --- a/test/plugin/calendar.test.js +++ b/test/plugin/calendar.test.js @@ -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 = {