MDL-59750 core_calendar: better handling of event subscription
[moodle.git] / calendar / amd / src / calendar.js
CommitLineData
3b0738f0
SL
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
aa091225
RW
17 * This module is the highest level module for the calendar. It is
18 * responsible for initialising all of the components required for
19 * the calendar to run. It also coordinates the interaction between
20 * components by listening for and responding to different events
21 * triggered within the calendar UI.
3b0738f0
SL
22 *
23 * @module core_calendar/calendar
24 * @package core_calendar
25 * @copyright 2017 Simey Lameze <simey@moodle.com>
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
aa091225
RW
28define([
29 'jquery',
30 'core/ajax',
31 'core/str',
32 'core/templates',
33 'core/notification',
34 'core/custom_interaction_events',
35 'core/modal_events',
36 'core/modal_factory',
37 'core_calendar/modal_event_form',
38 'core_calendar/summary_modal',
39 'core_calendar/repository',
695c5726
AN
40 'core_calendar/events',
41 'core_calendar/view_manager'
aa091225
RW
42 ],
43 function(
44 $,
45 Ajax,
46 Str,
47 Templates,
48 Notification,
49 CustomEvents,
50 ModalEvents,
51 ModalFactory,
52 ModalEventForm,
53 SummaryModal,
54 CalendarRepository,
695c5726
AN
55 CalendarEvents,
56 CalendarViewManager
aa091225
RW
57 ) {
58
59 var SELECTORS = {
60 ROOT: "[data-region='calendar']",
f6e8cc83
RW
61 DAY: "[data-region='day']",
62 EVENT_ITEM: "[data-region='event-item']",
aa091225 63 EVENT_LINK: "[data-action='view-event']",
5ca142dc
RW
64 NEW_EVENT_BUTTON: "[data-action='new-event-button']",
65 DAY_CONTENT: "[data-region='day-content']",
66 LOADING_ICON: '.loading-icon',
29158c8b 67 VIEW_DAY_LINK: "[data-action='view-day-link']",
afa8c3da
SL
68 CALENDAR_MONTH_WRAPPER: ".calendarwrapper",
69 COURSE_SELECTOR: 'select[name="course"]'
aa091225
RW
70 };
71
72 /**
73 * Get the event type lang string.
74 *
75 * @param {String} eventType The event type.
76 * @return {promise} The lang string promise.
77 */
78 var getEventType = function(eventType) {
79 var lang = 'type' + eventType;
80 return Str.get_string(lang, 'core_calendar').then(function(langStr) {
81 return langStr;
82 });
83 };
84
aa091225
RW
85 /**
86 * Render the event summary modal.
87 *
88 * @param {Number} eventId The calendar event id.
89 */
90 var renderEventSummaryModal = function(eventId) {
91 // Calendar repository promise.
92 CalendarRepository.getEventById(eventId).then(function(getEventResponse) {
93 if (!getEventResponse.event) {
94 throw new Error('Error encountered while trying to fetch calendar event with ID: ' + eventId);
95 }
96 var eventData = getEventResponse.event;
aa091225 97
8afe9f8a 98 return getEventType(eventData.eventtype).then(function(eventType) {
aa091225
RW
99 eventData.eventtype = eventType;
100 return eventData;
101 });
aa091225
RW
102 }).then(function(eventData) {
103 // Build the modal parameters from the event data.
104 var modalParams = {
105 title: eventData.name,
106 type: SummaryModal.TYPE,
4df03a27
SL
107 body: Templates.render('core_calendar/event_summary_body', eventData),
108 templateContext: {
109 canedit: eventData.canedit,
4757780a
SL
110 candelete: eventData.candelete,
111 isactionevent: eventData.isactionevent,
112 url: eventData.url
4df03a27 113 }
aa091225 114 };
4df03a27 115
aa091225
RW
116 // Create the modal.
117 return ModalFactory.create(modalParams);
118
119 }).done(function(modal) {
120 // Handle hidden event.
121 modal.getRoot().on(ModalEvents.hidden, function() {
122 // Destroy when hidden.
123 modal.destroy();
124 });
125
126 // Finally, render the modal!
127 modal.show();
128
129 }).fail(Notification.exception);
130 };
131
5ca142dc
RW
132 /**
133 * Handler for the drag and drop move event. Provides a loading indicator
134 * while the request is sent to the server to update the event start date.
135 *
136 * Triggers a eventMoved calendar javascript event if the event was successfully
137 * updated.
138 *
139 * @param {event} e The calendar move event
aefb2950
RW
140 * @param {int} eventId The event id being moved
141 * @param {object|null} originElement The jQuery element for where the event is moving from
5ca142dc
RW
142 * @param {object} destinationElement The jQuery element for where the event is moving to
143 */
aefb2950
RW
144 var handleMoveEvent = function(e, eventId, originElement, destinationElement) {
145 var originTimestamp = null;
5ca142dc
RW
146 var destinationTimestamp = destinationElement.attr('data-day-timestamp');
147
aefb2950
RW
148 if (originElement) {
149 originTimestamp = originElement.attr('data-day-timestamp');
150 }
151
5ca142dc 152 // If the event has actually changed day.
aefb2950 153 if (!originElement || originTimestamp != destinationTimestamp) {
5ca142dc
RW
154 Templates.render('core/loading', {})
155 .then(function(html, js) {
156 // First we show some loading icons in each of the days being affected.
5ca142dc 157 destinationElement.find(SELECTORS.DAY_CONTENT).addClass('hidden');
5ca142dc 158 Templates.appendNodeContents(destinationElement, html, js);
aefb2950
RW
159
160 if (originElement) {
161 originElement.find(SELECTORS.DAY_CONTENT).addClass('hidden');
162 Templates.appendNodeContents(originElement, html, js);
163 }
5ca142dc
RW
164 return;
165 })
166 .then(function() {
167 // Send a request to the server to make the change.
168 return CalendarRepository.updateEventStartDay(eventId, destinationTimestamp);
169 })
170 .then(function() {
171 // If the update was successful then broadcast an event letting the calendar
172 // know that an event has been moved.
aefb2950 173 $('body').trigger(CalendarEvents.eventMoved, [eventId, originElement, destinationElement]);
5ca142dc
RW
174 return;
175 })
176 .always(function() {
177 // Always remove the loading icons regardless of whether the update
178 // request was successful or not.
5ca142dc 179 var destinationLoadingElement = destinationElement.find(SELECTORS.LOADING_ICON);
5ca142dc 180 destinationElement.find(SELECTORS.DAY_CONTENT).removeClass('hidden');
5ca142dc 181 Templates.replaceNode(destinationLoadingElement, '', '');
aefb2950
RW
182
183 if (originElement) {
184 var originLoadingElement = originElement.find(SELECTORS.LOADING_ICON);
185 originElement.find(SELECTORS.DAY_CONTENT).removeClass('hidden');
186 Templates.replaceNode(originLoadingElement, '', '');
187 }
5ca142dc
RW
188 return;
189 })
190 .fail(Notification.exception);
191 }
192 };
193
aa091225
RW
194 /**
195 * Create the event form modal for creating new events and
196 * editing existing events.
197 *
198 * @method registerEventFormModal
199 * @param {object} root The calendar root element
200 * @return {object} The create modal promise
201 */
202 var registerEventFormModal = function(root) {
203 var newEventButton = root.find(SELECTORS.NEW_EVENT_BUTTON);
204 var contextId = newEventButton.attr('data-context-id');
205
206 return ModalFactory.create(
207 {
208 type: ModalEventForm.TYPE,
209 large: true,
210 templateContext: {
211 contextid: contextId
3d67e83f 212 }
aa091225 213 },
6a7ad2cb 214 [root, SELECTORS.NEW_EVENT_BUTTON]
aa091225
RW
215 );
216 };
a43ec9eb 217
aa091225
RW
218 /**
219 * Listen to and handle any calendar events fired by the calendar UI.
220 *
221 * @method registerCalendarEventListeners
222 * @param {object} root The calendar root element
223 * @param {object} eventFormModalPromise A promise reolved with the event form modal
224 */
225 var registerCalendarEventListeners = function(root, eventFormModalPromise) {
29158c8b
SL
226 var body = $('body'),
227 courseId = $(root).find(SELECTORS.CALENDAR_MONTH_WRAPPER).data('courseid');
aa091225 228
d6942fb5 229 body.on(CalendarEvents.created, function() {
b31a1695 230 CalendarViewManager.reloadCurrentMonth(root);
d6942fb5
RW
231 });
232 body.on(CalendarEvents.deleted, function() {
b31a1695 233 CalendarViewManager.reloadCurrentMonth(root);
d6942fb5
RW
234 });
235 body.on(CalendarEvents.updated, function() {
b31a1695 236 CalendarViewManager.reloadCurrentMonth(root);
d6942fb5 237 });
c34e2002
SL
238 body.on(CalendarEvents.editActionEvent, function(e, url) {
239 // Action events needs to be edit directly on the course module.
240 window.location.assign(url);
241 });
5ca142dc
RW
242 // Handle the event fired by the drag and drop code.
243 body.on(CalendarEvents.moveEvent, handleMoveEvent);
244 // When an event is successfully moved we should updated the UI.
245 body.on(CalendarEvents.eventMoved, function() {
aefb2950 246 CalendarViewManager.reloadCurrentMonth(root);
5ca142dc 247 });
a43ec9eb 248
aa091225
RW
249 eventFormModalPromise.then(function(modal) {
250 // When something within the calendar tells us the user wants
251 // to edit an event then show the event form modal.
252 body.on(CalendarEvents.editEvent, function(e, eventId) {
253 modal.setEventId(eventId);
254 modal.show();
3b0738f0 255 });
29158c8b 256 modal.setCourseId(courseId);
aa091225
RW
257 return;
258 });
259 };
260
261 /**
262 * Register event listeners for the module.
263 */
6397ec54 264 var registerEventListeners = function(root) {
aa091225 265 // Bind click events to event links.
f6e8cc83 266 root.on('click', SELECTORS.EVENT_ITEM, function(e) {
aa091225 267 e.preventDefault();
f6e8cc83
RW
268 // We've handled the event so stop it from bubbling
269 // and causing the day click handler to fire.
270 e.stopPropagation();
271
272 var target = $(e.target);
273 var eventId = null;
274
275 if (target.is(SELECTORS.EVENT_LINK)) {
276 eventId = target.attr('data-event-id');
277 } else {
278 eventId = target.find(SELECTORS.EVENT_LINK).attr('data-event-id');
279 }
280
aa091225
RW
281 renderEventSummaryModal(eventId);
282 });
283
afa8c3da
SL
284 root.on('change', SELECTORS.COURSE_SELECTOR, function() {
285 var selectElement = $(this);
286 var courseId = selectElement.val();
287 CalendarViewManager.reloadCurrentMonth(root, courseId)
288 .then(function() {
289 // We need to get the selector again because the content has changed.
290 return root.find(SELECTORS.COURSE_SELECTOR).val(courseId);
291 })
292 .fail(Notification.exception);
293 });
294
aa091225
RW
295 var eventFormPromise = registerEventFormModal(root);
296 registerCalendarEventListeners(root, eventFormPromise);
f6e8cc83
RW
297
298 // Bind click events to calendar days.
299 root.on('click', SELECTORS.DAY, function(e) {
300 var target = $(e.target);
301
302 if (!target.is(SELECTORS.VIEW_DAY_LINK)) {
303 var startTime = $(this).attr('data-new-event-timestamp');
304 eventFormPromise.then(function(modal) {
305 modal.setStartTime(startTime);
306 modal.show();
307 return;
308 });
309
310 e.preventDefault();
311 }
312 });
aa091225
RW
313 };
314
315 return {
6397ec54
AN
316 init: function(root) {
317 root = $(root);
318
319 CalendarViewManager.init(root);
320 registerEventListeners(root);
aa091225
RW
321 }
322 };
323});