useCalendar.js
8.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import listPlugin from '@fullcalendar/list'
import timeGridPlugin from '@fullcalendar/timegrid'
import { useConfigStore } from '@core/stores/config'
import { useCalendarStore } from '@/views/apps/calendar/useCalendarStore'
export const blankEvent = {
title: '',
start: '',
end: '',
allDay: false,
url: '',
extendedProps: {
/*
ℹ️ We have to use undefined here because if we have blank string as value then select placeholder will be active (moved to top).
Hence, we need to set it to undefined or null
*/
calendar: undefined,
guests: [],
location: '',
description: '',
},
}
export const useCalendar = (event, isEventHandlerSidebarActive, isLeftSidebarOpen) => {
const configStore = useConfigStore()
// 👉 Store
const store = useCalendarStore()
// 👉 Calendar template ref
const refCalendar = ref()
// 👉 Calendar colors
const calendarsColor = {
Business: 'primary',
Holiday: 'success',
Personal: 'error',
Family: 'warning',
ETC: 'info',
}
// ℹ️ Extract event data from event API
const extractEventDataFromEventApi = eventApi => {
const { id, title, start, end, url, extendedProps: { calendar, guests, location, description }, allDay } = eventApi
return {
id,
title,
start,
end,
url,
extendedProps: {
calendar,
guests,
location,
description,
},
allDay,
}
}
if (typeof process !== 'undefined' && process.server)
store.fetchEvents()
// 👉 Fetch events
const fetchEvents = (info, successCallback) => {
// If there's no info => Don't make useless API call
if (!info)
return
store.fetchEvents()
.then(r => {
successCallback(r.map(e => ({
...e,
// Convert string representation of date to Date object
start: new Date(e.start),
end: new Date(e.end),
})))
})
.catch(e => {
console.error('Error occurred while fetching calendar events', e)
})
}
// 👉 Calendar API
const calendarApi = ref(null)
// 👉 Update event in calendar [UI]
const updateEventInCalendar = (updatedEventData, propsToUpdate, extendedPropsToUpdate) => {
calendarApi.value = refCalendar.value.getApi()
const existingEvent = calendarApi.value?.getEventById(String(updatedEventData.id))
if (!existingEvent) {
console.warn('Can\'t found event in calendar to update')
return
}
// ---Set event properties except date related
// Docs: https://fullcalendar.io/docs/Event-setProp
// dateRelatedProps => ['start', 'end', 'allDay']
for (let index = 0; index < propsToUpdate.length; index++) {
const propName = propsToUpdate[index]
existingEvent.setProp(propName, updatedEventData[propName])
}
// --- Set date related props
// ? Docs: https://fullcalendar.io/docs/Event-setDates
existingEvent.setDates(updatedEventData.start, updatedEventData.end, { allDay: updatedEventData.allDay })
// --- Set event's extendedProps
// ? Docs: https://fullcalendar.io/docs/Event-setExtendedProp
for (let index = 0; index < extendedPropsToUpdate.length; index++) {
const propName = extendedPropsToUpdate[index]
existingEvent.setExtendedProp(propName, updatedEventData.extendedProps[propName])
}
}
// 👉 Remove event in calendar [UI]
const removeEventInCalendar = eventId => {
const _event = calendarApi.value?.getEventById(eventId)
if (_event)
_event.remove()
}
// 👉 refetch events
const refetchEvents = () => {
calendarApi.value?.refetchEvents()
}
watch(() => store.selectedCalendars, refetchEvents)
// 👉 Add event
const addEvent = _event => {
store.addEvent(_event)
.then(() => {
refetchEvents()
})
}
// 👉 Update event
const updateEvent = _event => {
// ℹ️ Making API call using $api('', { method: ... })
store.updateEvent(_event)
.then(r => {
const propsToUpdate = ['id', 'title', 'url']
const extendedPropsToUpdate = ['calendar', 'guests', 'location', 'description']
updateEventInCalendar(r, propsToUpdate, extendedPropsToUpdate)
})
refetchEvents()
}
// 👉 Remove event
const removeEvent = eventId => {
store.removeEvent(eventId).then(() => {
removeEventInCalendar(eventId)
})
}
// 👉 Calendar options
const calendarOptions = {
plugins: [dayGridPlugin, interactionPlugin, timeGridPlugin, listPlugin],
initialView: 'dayGridMonth',
headerToolbar: {
start: 'drawerToggler,prev,next title',
end: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth',
},
events: fetchEvents,
// ❗ We need this to be true because when its false and event is allDay event and end date is same as start data then Full calendar will set end to null
forceEventDuration: true,
/*
Enable dragging and resizing event
Docs: https://fullcalendar.io/docs/editable
*/
editable: true,
/*
Enable resizing event from start
Docs: https://fullcalendar.io/docs/eventResizableFromStart
*/
eventResizableFromStart: true,
/*
Automatically scroll the scroll-containers during event drag-and-drop and date selecting
Docs: https://fullcalendar.io/docs/dragScroll
*/
dragScroll: true,
/*
Max number of events within a given day
Docs: https://fullcalendar.io/docs/dayMaxEvents
*/
dayMaxEvents: 2,
/*
Determines if day names and week names are clickable
Docs: https://fullcalendar.io/docs/navLinks
*/
navLinks: true,
eventClassNames({ event: calendarEvent }) {
const colorName = calendarsColor[calendarEvent._def.extendedProps.calendar]
return [
// Background Color
`bg-light-${colorName} text-${colorName}`,
]
},
eventClick({ event: clickedEvent, jsEvent }) {
// Prevent the default action
jsEvent.preventDefault()
if (clickedEvent.url) {
// Open the URL in a new tab
window.open(clickedEvent.url, '_blank')
}
// * Only grab required field otherwise it goes in infinity loop
// ! Always grab all fields rendered by form (even if it get `undefined`) otherwise due to Vue3/Composition API you might get: "object is not extensible"
event.value = extractEventDataFromEventApi(clickedEvent)
isEventHandlerSidebarActive.value = true
},
// customButtons
dateClick(info) {
event.value = { ...event.value, start: info.date }
isEventHandlerSidebarActive.value = true
},
/*
Handle event drop (Also include dragged event)
Docs: https://fullcalendar.io/docs/eventDrop
We can use `eventDragStop` but it doesn't return updated event so we have to use `eventDrop` which returns updated event
*/
eventDrop({ event: droppedEvent }) {
updateEvent(extractEventDataFromEventApi(droppedEvent))
},
/*
Handle event resize
Docs: https://fullcalendar.io/docs/eventResize
*/
eventResize({ event: resizedEvent }) {
if (resizedEvent.start && resizedEvent.end)
updateEvent(extractEventDataFromEventApi(resizedEvent))
},
customButtons: {
drawerToggler: {
text: 'calendarDrawerToggler',
click() {
isLeftSidebarOpen.value = true
},
},
},
}
// 👉 onMounted
onMounted(() => {
calendarApi.value = refCalendar.value.getApi()
})
// 👉 Jump to date on sidebar(inline) calendar change
const jumpToDate = currentDate => {
calendarApi.value?.gotoDate(new Date(currentDate))
}
watch(() => configStore.isAppRTL, val => {
calendarApi.value?.setOption('direction', val ? 'rtl' : 'ltr')
}, { immediate: true })
return {
refCalendar,
calendarOptions,
refetchEvents,
fetchEvents,
addEvent,
updateEvent,
removeEvent,
jumpToDate,
}
}