-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalendarContainer.tsx
More file actions
388 lines (348 loc) · 13.2 KB
/
Copy pathCalendarContainer.tsx
File metadata and controls
388 lines (348 loc) · 13.2 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import { FC, useCallback, useMemo, useState, useEffect } from "react";
import moment from "moment-with-locales-es6";
import { useHistory, useParams } from "react-router-dom";
import { useWidgetHeight } from "src/api/hooks";
import { useSelectedDate } from "src/api/hooks/useSelectedDate";
import {
EWidgetData,
useGetEventQuery,
useGetEventsQuery,
TGetEventResponse,
} from "src/api/services";
import {
selectSelectedCalendarType,
setEventFilters,
setSelectedCalendarType,
selectedViewSelector,
} from "src/api/store";
import { useAppDispatch, useAppSelector } from "src/api/store/hooks";
import { TEvent } from "src/api/types";
import { getClosestEvent } from "src/api/utils/calendarUtils";
import { filteringListToStr } from "src/api/utils/filterUtils";
import { customDataAsItems } from "src/api/utils/itemUtils";
import { Logger } from "src/api/utils/logging";
import { buildViewPath } from "src/api/utils/viewUtils";
import CalendarModule from "src/components/calendar/CalendarModule";
import { ECalendarType } from "src/components/calendar/types";
import {
defaultEventCategory,
viewableCategories,
} from "src/components/calendarCategories";
import { TEventCategory } from "src/components/types";
import { EWidgetSettingsRegistry } from "src/constants";
import { IModuleContainer, TCategoryData } from "src/types";
import CONFIG from "../../config/config";
const { POLLING_INTERVAL, QUERY_EVENTS_HARD_LIMIT } = CONFIG.WIDGETS.CALENDAR;
/**
* @param eventIdFromPath The event id from the current URL path
* @param selectedEventDetailsResponse The event details as returned by the backend
* @param selectedDate The selected date in the calendar
* @returns true if the selected date is not within the range of the current event id
*/
const shouldChangeSelectedDate = (
eventIdFromPath: string | undefined,
selectedEventDetailsResponse: TGetEventResponse | undefined,
selectedDate: Date
): boolean => {
if (
eventIdFromPath !== undefined &&
eventIdFromPath === selectedEventDetailsResponse?.result.id
) {
// trigger query to get other events in the same month as the event with id eventId
const { start, end } = selectedEventDetailsResponse.result;
if (moment(selectedDate).isSame(moment(start))) return false;
// Do not change the selectedDate if it is within the range of the selected Event.
if (moment(selectedDate).isBetween(moment(start), moment(end))) {
return false;
}
return true;
}
return false;
};
const fetchCalendarEvents = (_date: Date): void => undefined;
const CalendarContainer: FC<IModuleContainer<TCategoryData[][]>> = ({
moduleData,
showFullSize,
toggleAdjustable,
}) => {
const navigate = useHistory();
const params = useParams<{ eventId: string }>();
const dispatch = useAppDispatch();
const selectedView = useAppSelector(selectedViewSelector);
const viewPath = buildViewPath(selectedView?.data);
const widgetCats = customDataAsItems(moduleData.widget.custom_data ?? []);
// TODO(v-almonacid): remove this block when format_structure is removed from db model
const legacyWidgetCats = moduleData.widget.format_structure?.data?.[0];
if (Array.isArray(legacyWidgetCats) && legacyWidgetCats.length > 0) {
Logger.warn(
`CalendarContainer: widget ${moduleData.widget.name} is using format_structure which has been deprecated`
);
}
const allowedCategories: TEventCategory[] =
widgetCats?.map((wCat) => {
const vCat =
viewableCategories.find((cat) => cat.value === wCat.name) ||
defaultEventCategory;
return {
...wCat,
value: vCat?.value,
label: wCat?.description,
category: wCat?.description,
color: vCat?.color,
};
}) || [];
const widgetHeight = useWidgetHeight(moduleData);
const eventFilters = useAppSelector(
(state) =>
state.widgets.calendar[moduleData.hash]?.eventFilters ??
allowedCategories
);
const { selectedDate: storedDate, setSelectedDate: setStoredDate } =
useSelectedDate(moduleData.hash);
const storedCalType = useAppSelector(
selectSelectedCalendarType(moduleData.hash)
);
const defaultCalenderType =
storedCalType ||
(moduleData.widget?.data_type === EWidgetData.Static
? ECalendarType.List
: ECalendarType.Month); // Change the default CalType to based on the widget's data_type
const [calendarType, setCalendarType] =
useState<ECalendarType>(defaultCalenderType);
const handleCalType = useCallback(
(calType: ECalendarType) => {
setCalendarType(calType);
dispatch(
setSelectedCalendarType({
calType,
widgetHash: moduleData.hash,
})
);
},
[dispatch, moduleData.hash]
);
const switchCalendarType = useCallback(() => {
if (calendarType === ECalendarType.Month) {
handleCalType(ECalendarType.List);
toggleAdjustable();
}
if (calendarType === ECalendarType.List) {
handleCalType(ECalendarType.Month);
}
}, [calendarType, handleCalType, toggleAdjustable]);
const [selectedDate, setSelectedDate] = useState<Date>(storedDate);
const handleSelectedDate = useCallback(
(date: Date) => {
if (+selectedDate !== +date) {
setSelectedDate(date);
setStoredDate(date);
}
},
[selectedDate, setStoredDate]
);
const tagsSettings = moduleData.settings.filter(
(s) =>
s.widget_setting.setting.slug ===
EWidgetSettingsRegistry.IncludedTags
);
const tags =
tagsSettings[0] !== undefined ? tagsSettings[0].tags : undefined;
const pollingInterval =
(moduleData.widget.refresh_interval || POLLING_INTERVAL) * 1000;
const tagsParam = tags ? filteringListToStr(tags) : undefined;
const queryOpts = { skip: !selectedDate, pollingInterval };
// Compute month boundaries using native Date (immutable — each is a new object)
const monthStartDate = new Date(
selectedDate.getFullYear(),
selectedDate.getMonth(),
1
);
const formatDate = (d: Date) => d.toISOString().slice(0, 10);
const addMonths = (d: Date, n: number) =>
new Date(d.getFullYear(), d.getMonth() + n, 1);
const prevStart = formatDate(addMonths(monthStartDate, -1));
const currStart = formatDate(monthStartDate);
const nextStart = formatDate(addMonths(monthStartDate, 1));
const nextEnd = formatDate(addMonths(monthStartDate, 2));
const {
data: prevMonthData,
isLoading: isLoadingPrev,
isFetching: isFetchingPrev,
} = useGetEventsQuery(
{
period_after: prevStart,
period_before: currStart,
limit: QUERY_EVENTS_HARD_LIMIT,
tags: tagsParam,
},
queryOpts
);
const {
data: currMonthData,
isLoading: isLoadingCurr,
isFetching: isFetchingCurr,
} = useGetEventsQuery(
{
period_after: currStart,
period_before: nextStart,
limit: QUERY_EVENTS_HARD_LIMIT,
tags: tagsParam,
},
queryOpts
);
const {
data: nextMonthData,
isLoading: isLoadingNext,
isFetching: isFetchingNext,
} = useGetEventsQuery(
{
period_after: nextStart,
period_before: nextEnd,
limit: QUERY_EVENTS_HARD_LIMIT,
tags: tagsParam,
},
queryOpts
);
const mergedEvents = useMemo(() => {
const prev = prevMonthData?.results ?? [];
const curr = currMonthData?.results ?? [];
const next = nextMonthData?.results ?? [];
const seen = new Set<string>();
return [...prev, ...curr, ...next].filter((e) => {
if (seen.has(e.id)) return false;
seen.add(e.id);
return true;
});
}, [
prevMonthData?.results,
currMonthData?.results,
nextMonthData?.results,
]);
const isLoadingEvents = isLoadingPrev || isLoadingCurr || isLoadingNext;
const isFetchingEvents = isFetchingPrev || isFetchingCurr || isFetchingNext;
const closestEvent: TEvent | undefined = useMemo(
() => getClosestEvent(mergedEvents, selectedDate),
[mergedEvents, selectedDate]
);
const {
currentData: eventDetailsData,
isFetching: isFetchingEventDetails,
} = useGetEventQuery(
{
id: params.eventId ? params.eventId : closestEvent?.id || "",
},
{
skip: !selectedDate || !(params.eventId || closestEvent?.id),
}
);
const onClickEvent = (
eventId: string,
eventUrlTitle: string,
eventStart: string
): void => {
setSelectedDate(new Date(eventStart));
/**
* When a view is stale, it can be removed and re-added to the cache,
* so selectedView can be undefined for a transient interval
*/
if (viewPath === "/" || selectedView === undefined) return;
navigate.push(`${viewPath}calendar/event/${eventId}/${eventUrlTitle}`);
Logger.debug("onClickEvent", eventId, eventUrlTitle);
};
const onDatesSet = useCallback(
(dateStr: string) => {
/**
* This function is used to change the selectedDate when the user
* changes the view (current month) the calendar.
*
* It sets the selectedDate to the first day of the month.
*
* If the current selectedDate is not from the same month as dateStr,
* it sets the selectedDate to the same day as dateStr.
*
* Could be refactored to handle week view change as well when we need it.
*/
if (
!moment(new Date(dateStr)).isSame(moment(selectedDate), "month")
) {
handleSelectedDate(new Date(dateStr));
/**
* onDatesSet is called only when the user changes the view (month)
*
* If the user changes the month there is (technically) no
* selectedDate (except the one we set by default).
* So we navigate to the calendar.
*/
if (params.eventId && viewPath !== "/") {
navigate.push(`${viewPath}calendar/`);
}
}
},
[handleSelectedDate, navigate, params, selectedDate, viewPath]
);
const handleCatFilters = useCallback(
(eFilters: TEventCategory[]) => {
dispatch(
setEventFilters({
filters: eFilters,
widgetHash: moduleData.hash,
})
);
},
[moduleData.hash, dispatch]
);
const { eventId } = params;
if (
eventDetailsData !== undefined &&
shouldChangeSelectedDate(eventId, eventDetailsData, selectedDate)
) {
const { start } = eventDetailsData.result;
setSelectedDate(new Date(String(start)));
}
useEffect(() => {
/**
* This effect is included so as to run only once
* and that's on mount when `defaultCalenderType` is initialized
*
* However, in the scenario that we update a widget from admin,
* this effect would rerun as well
*/
if (defaultCalenderType === ECalendarType.Month) {
toggleAdjustable();
}
}, [defaultCalenderType, toggleAdjustable]);
/**
* the "loading" state of the event details component is determined as follows:
* - When we are passing the eventId, we just read `isFetchingEventDetails` because
* the query is triggered immediately.
* - When there is no eventId, we need to find the closest event. During that
* time, we need to fetch the event list (`eventData`) first, so there is a transient state
* in which both `eventDetailsData = undefined && isFetchingEventDetails = false`. After that,
* the query is triggered.
*/
const isLoadingEventDetails = eventId
? isFetchingEventDetails
: isFetchingEvents || isFetchingEventDetails;
return (
<CalendarModule
events={mergedEvents}
fetchEvents={fetchCalendarEvents}
onClickEvent={onClickEvent}
onDatesSet={onDatesSet}
selectedEventDetails={eventDetailsData?.result}
isLoadingEventDetails={isLoadingEventDetails}
selectedDate={selectedDate}
showFullSize={showFullSize}
calendarType={calendarType}
switchCalendarType={switchCalendarType}
widgetHash={moduleData.hash}
catFilters={eventFilters}
setCatFilters={handleCatFilters}
widgetHeight={widgetHeight}
allowedCategories={allowedCategories}
isLoadingEvents={isLoadingEvents}
isFetchingEvents={isFetchingEvents}
/>
);
};
export default CalendarContainer;