Skip to content

Commit b25be90

Browse files
fix: Add option callback to Calendar plugin (#839)
1 parent 669968e commit b25be90

File tree

2 files changed

+46
-3
lines changed

2 files changed

+46
-3
lines changed

src/plugin/calendar/index.js

+8-3
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ export default (o, c, d) => {
1010
sameElse: L
1111
}
1212
const proto = c.prototype
13-
proto.calendar = function (referenceTime, formats) {
14-
const format = formats || this.$locale().calendar || calendarFormat
13+
proto.calendar = function (referenceTime, callbacks) {
14+
const format = callbacks || this.$locale().calendar || calendarFormat
1515
const referenceStartOfDay = d(referenceTime || undefined).startOf('d')
1616
const diff = this.diff(referenceStartOfDay, 'd', true)
1717
const sameElse = 'sameElse'
@@ -23,7 +23,12 @@ export default (o, c, d) => {
2323
diff < 2 ? 'nextDay' :
2424
diff < 7 ? 'nextWeek' : sameElse
2525
/* eslint-enable no-nested-ternary */
26-
return this.format(format[retVal] || calendarFormat[retVal])
26+
const currentFormat = format[retVal] || calendarFormat[retVal]
27+
if (typeof currentFormat === 'function') {
28+
return currentFormat(referenceStartOfDay)
29+
}
30+
const formattedDate = this.format(currentFormat)
31+
return formattedDate
2732
}
2833
}
2934

test/plugin/calendar.test.js

+38
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,44 @@ it('Custom format', () => {
8181
.toEqual(moment(now).calendar(nextDayWithoutFormat, format))
8282
})
8383

84+
it('Custom callback', () => {
85+
const callbacks = {
86+
sameDay: jest.fn(),
87+
sameElse: jest.fn()
88+
}
89+
const now = '2015-01-15T14:21:22.000Z'
90+
const nextDayWithoutFormat = '2015-01-14T11:23:55.000Z'
91+
expect(dayjs(now).calendar(nextDayWithoutFormat, callbacks))
92+
.toEqual(moment(now).calendar(nextDayWithoutFormat, callbacks))
93+
})
94+
95+
it('Calls callback', () => {
96+
const callbacks = {
97+
sameDay: jest.fn(),
98+
sameElse: jest.fn()
99+
}
100+
dayjs().calendar(null, callbacks)
101+
expect(callbacks.sameElse).not.toBeCalled()
102+
expect(callbacks.sameDay).toBeCalled()
103+
})
104+
105+
it('callback is a function with the scope of the current moment', () => {
106+
const callbacks = {
107+
sameDay: jest.fn(),
108+
sameElse: jest.fn()
109+
}
110+
expect(dayjs().calendar(null, callbacks)).toEqual(callbacks.sameDay())
111+
})
112+
113+
it('callback is a function and first argument a moment that depicts now', () => {
114+
const callbacks = {
115+
sameDay: jest.fn()
116+
}
117+
const now = dayjs()
118+
dayjs(now).calendar(now, callbacks)
119+
expect(callbacks.sameDay).toBeCalledWith(now.startOf('d'))
120+
})
121+
84122
it('set global calendar in locale file', () => {
85123
const now = '2019-04-03T14:21:22.000Z'
86124
zhCn.calendar = {

0 commit comments

Comments
 (0)