weekly release 3.4dev
[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
85 /**
86 * Get the event source.
87 *
88 * @param {Object} subscription The event subscription object.
89 * @return {promise} The lang string promise.
90 */
91 var getEventSource = function(subscription) {
92 return Str.get_string('subsource', 'core_calendar', subscription).then(function(langStr) {
93 if (subscription.url) {
94 return '<a href="' + subscription.url + '">' + langStr + '</a>';
95 }
96 return langStr;
97 });
98 };
a43ec9eb 99
aa091225
RW
100 /**
101 * Render the event summary modal.
102 *
103 * @param {Number} eventId The calendar event id.
104 */
105 var renderEventSummaryModal = function(eventId) {
106 // Calendar repository promise.
107 CalendarRepository.getEventById(eventId).then(function(getEventResponse) {
108 if (!getEventResponse.event) {
109 throw new Error('Error encountered while trying to fetch calendar event with ID: ' + eventId);
110 }
111 var eventData = getEventResponse.event;
112 var eventTypePromise = getEventType(eventData.eventtype);
113
114 // If the calendar event has event source, get the source's language string/link.
115 if (eventData.displayeventsource) {
116 eventData.subscription = JSON.parse(eventData.subscription);
117 var eventSourceParams = {
118 url: eventData.subscription.url,
119 name: eventData.subscription.name
120 };
121 var eventSourcePromise = getEventSource(eventSourceParams);
122
123 // Return event data with event type and event source info.
124 return $.when(eventTypePromise, eventSourcePromise).then(function(eventType, eventSource) {
a43ec9eb 125 eventData.eventtype = eventType;
aa091225 126 eventData.source = eventSource;
a43ec9eb 127 return eventData;
3b0738f0 128 });
aa091225 129 }
3d67e83f 130
aa091225
RW
131 // Return event data with event type info.
132 return eventTypePromise.then(function(eventType) {
133 eventData.eventtype = eventType;
134 return eventData;
135 });
136
137 }).then(function(eventData) {
138 // Build the modal parameters from the event data.
139 var modalParams = {
140 title: eventData.name,
141 type: SummaryModal.TYPE,
4df03a27
SL
142 body: Templates.render('core_calendar/event_summary_body', eventData),
143 templateContext: {
144 canedit: eventData.canedit,
4757780a
SL
145 candelete: eventData.candelete,
146 isactionevent: eventData.isactionevent,
147 url: eventData.url
4df03a27 148 }
aa091225 149 };
4df03a27 150
aa091225
RW
151 // Create the modal.
152 return ModalFactory.create(modalParams);
153
154 }).done(function(modal) {
155 // Handle hidden event.
156 modal.getRoot().on(ModalEvents.hidden, function() {
157 // Destroy when hidden.
158 modal.destroy();
159 });
160
161 // Finally, render the modal!
162 modal.show();
163
164 }).fail(Notification.exception);
165 };
166
5ca142dc
RW
167 /**
168 * Handler for the drag and drop move event. Provides a loading indicator
169 * while the request is sent to the server to update the event start date.
170 *
171 * Triggers a eventMoved calendar javascript event if the event was successfully
172 * updated.
173 *
174 * @param {event} e The calendar move event
aefb2950
RW
175 * @param {int} eventId The event id being moved
176 * @param {object|null} originElement The jQuery element for where the event is moving from
5ca142dc
RW
177 * @param {object} destinationElement The jQuery element for where the event is moving to
178 */
aefb2950
RW
179 var handleMoveEvent = function(e, eventId, originElement, destinationElement) {
180 var originTimestamp = null;
5ca142dc
RW
181 var destinationTimestamp = destinationElement.attr('data-day-timestamp');
182
aefb2950
RW
183 if (originElement) {
184 originTimestamp = originElement.attr('data-day-timestamp');
185 }
186
5ca142dc 187 // If the event has actually changed day.
aefb2950 188 if (!originElement || originTimestamp != destinationTimestamp) {
5ca142dc
RW
189 Templates.render('core/loading', {})
190 .then(function(html, js) {
191 // First we show some loading icons in each of the days being affected.
5ca142dc 192 destinationElement.find(SELECTORS.DAY_CONTENT).addClass('hidden');
5ca142dc 193 Templates.appendNodeContents(destinationElement, html, js);
aefb2950
RW
194
195 if (originElement) {
196 originElement.find(SELECTORS.DAY_CONTENT).addClass('hidden');
197 Templates.appendNodeContents(originElement, html, js);
198 }
5ca142dc
RW
199 return;
200 })
201 .then(function() {
202 // Send a request to the server to make the change.
203 return CalendarRepository.updateEventStartDay(eventId, destinationTimestamp);
204 })
205 .then(function() {
206 // If the update was successful then broadcast an event letting the calendar
207 // know that an event has been moved.
aefb2950 208 $('body').trigger(CalendarEvents.eventMoved, [eventId, originElement, destinationElement]);
5ca142dc
RW
209 return;
210 })
211 .always(function() {
212 // Always remove the loading icons regardless of whether the update
213 // request was successful or not.
5ca142dc 214 var destinationLoadingElement = destinationElement.find(SELECTORS.LOADING_ICON);
5ca142dc 215 destinationElement.find(SELECTORS.DAY_CONTENT).removeClass('hidden');
5ca142dc 216 Templates.replaceNode(destinationLoadingElement, '', '');
aefb2950
RW
217
218 if (originElement) {
219 var originLoadingElement = originElement.find(SELECTORS.LOADING_ICON);
220 originElement.find(SELECTORS.DAY_CONTENT).removeClass('hidden');
221 Templates.replaceNode(originLoadingElement, '', '');
222 }
5ca142dc
RW
223 return;
224 })
225 .fail(Notification.exception);
226 }
227 };
228
aa091225
RW
229 /**
230 * Create the event form modal for creating new events and
231 * editing existing events.
232 *
233 * @method registerEventFormModal
234 * @param {object} root The calendar root element
235 * @return {object} The create modal promise
236 */
237 var registerEventFormModal = function(root) {
238 var newEventButton = root.find(SELECTORS.NEW_EVENT_BUTTON);
239 var contextId = newEventButton.attr('data-context-id');
240
241 return ModalFactory.create(
242 {
243 type: ModalEventForm.TYPE,
244 large: true,
245 templateContext: {
246 contextid: contextId
3d67e83f 247 }
aa091225 248 },
6a7ad2cb 249 [root, SELECTORS.NEW_EVENT_BUTTON]
aa091225
RW
250 );
251 };
a43ec9eb 252
aa091225
RW
253 /**
254 * Listen to and handle any calendar events fired by the calendar UI.
255 *
256 * @method registerCalendarEventListeners
257 * @param {object} root The calendar root element
258 * @param {object} eventFormModalPromise A promise reolved with the event form modal
259 */
260 var registerCalendarEventListeners = function(root, eventFormModalPromise) {
29158c8b
SL
261 var body = $('body'),
262 courseId = $(root).find(SELECTORS.CALENDAR_MONTH_WRAPPER).data('courseid');
aa091225 263
d6942fb5 264 body.on(CalendarEvents.created, function() {
b31a1695 265 CalendarViewManager.reloadCurrentMonth(root);
d6942fb5
RW
266 });
267 body.on(CalendarEvents.deleted, function() {
b31a1695 268 CalendarViewManager.reloadCurrentMonth(root);
d6942fb5
RW
269 });
270 body.on(CalendarEvents.updated, function() {
b31a1695 271 CalendarViewManager.reloadCurrentMonth(root);
d6942fb5 272 });
c34e2002
SL
273 body.on(CalendarEvents.editActionEvent, function(e, url) {
274 // Action events needs to be edit directly on the course module.
275 window.location.assign(url);
276 });
5ca142dc
RW
277 // Handle the event fired by the drag and drop code.
278 body.on(CalendarEvents.moveEvent, handleMoveEvent);
279 // When an event is successfully moved we should updated the UI.
280 body.on(CalendarEvents.eventMoved, function() {
aefb2950 281 CalendarViewManager.reloadCurrentMonth(root);
5ca142dc 282 });
a43ec9eb 283
aa091225
RW
284 eventFormModalPromise.then(function(modal) {
285 // When something within the calendar tells us the user wants
286 // to edit an event then show the event form modal.
287 body.on(CalendarEvents.editEvent, function(e, eventId) {
288 modal.setEventId(eventId);
289 modal.show();
3b0738f0 290 });
29158c8b 291 modal.setCourseId(courseId);
aa091225
RW
292 return;
293 });
294 };
295
296 /**
297 * Register event listeners for the module.
298 */
299 var registerEventListeners = function() {
300 var root = $(SELECTORS.ROOT);
301
302 // Bind click events to event links.
f6e8cc83 303 root.on('click', SELECTORS.EVENT_ITEM, function(e) {
aa091225 304 e.preventDefault();
f6e8cc83
RW
305 // We've handled the event so stop it from bubbling
306 // and causing the day click handler to fire.
307 e.stopPropagation();
308
309 var target = $(e.target);
310 var eventId = null;
311
312 if (target.is(SELECTORS.EVENT_LINK)) {
313 eventId = target.attr('data-event-id');
314 } else {
315 eventId = target.find(SELECTORS.EVENT_LINK).attr('data-event-id');
316 }
317
aa091225
RW
318 renderEventSummaryModal(eventId);
319 });
320
afa8c3da
SL
321 root.on('change', SELECTORS.COURSE_SELECTOR, function() {
322 var selectElement = $(this);
323 var courseId = selectElement.val();
324 CalendarViewManager.reloadCurrentMonth(root, courseId)
325 .then(function() {
326 // We need to get the selector again because the content has changed.
327 return root.find(SELECTORS.COURSE_SELECTOR).val(courseId);
328 })
329 .fail(Notification.exception);
330 });
331
aa091225
RW
332 var eventFormPromise = registerEventFormModal(root);
333 registerCalendarEventListeners(root, eventFormPromise);
f6e8cc83
RW
334
335 // Bind click events to calendar days.
336 root.on('click', SELECTORS.DAY, function(e) {
337 var target = $(e.target);
338
339 if (!target.is(SELECTORS.VIEW_DAY_LINK)) {
340 var startTime = $(this).attr('data-new-event-timestamp');
341 eventFormPromise.then(function(modal) {
342 modal.setStartTime(startTime);
343 modal.show();
344 return;
345 });
346
347 e.preventDefault();
348 }
349 });
aa091225
RW
350 };
351
352 return {
353 init: function() {
695c5726 354 CalendarViewManager.init();
aa091225
RW
355 registerEventListeners();
356 }
357 };
358});