Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
/**
17
 * Javascript to load and render the list of calendar events for a
18
 * given day range.
19
 *
20
 * @module     block_timeline/event_list
21
 * @copyright  2016 Ryan Wyllie <ryan@moodle.com>
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
define(
25
[
26
    'jquery',
27
    'core/notification',
28
    'core/templates',
29
    'core/str',
30
    'core/user_date',
31
    'block_timeline/calendar_events_repository',
32
    'core/pending'
33
],
34
function(
35
    $,
36
    Notification,
37
    Templates,
38
    Str,
39
    UserDate,
40
    CalendarEventsRepository,
41
    Pending
42
) {
43
 
44
    var SECONDS_IN_DAY = 60 * 60 * 24;
45
    var courseview = false;
46
 
47
    var SELECTORS = {
48
        EMPTY_MESSAGE: '[data-region="no-events-empty-message"]',
49
        ROOT: '[data-region="event-list-container"]',
50
        EVENT_LIST_CONTENT: '[data-region="event-list-content"]',
51
        EVENT_LIST_WRAPPER: '[data-region="event-list-wrapper"]',
52
        EVENT_LIST_LOADING_PLACEHOLDER: '[data-region="event-list-loading-placeholder"]',
53
        TIMELINE_BLOCK: '[data-region="timeline"]',
54
        TIMELINE_SEARCH: '[data-action="search"]',
55
        MORE_ACTIVITIES_BUTTON: '[data-action="more-events"]',
56
        MORE_ACTIVITIES_BUTTON_CONTAINER: '[data-region="more-events-button-container"]'
57
    };
58
 
59
    var TEMPLATES = {
60
        EVENT_LIST_CONTENT: 'block_timeline/event-list-content',
61
        MORE_ACTIVITIES_BUTTON: 'block_timeline/event-list-loadmore',
62
        LOADING_ICON: 'core/loading'
63
    };
64
 
65
    /** @property {number} The total items will be shown on the first load. */
66
    const DEFAULT_LAZY_LOADING_ITEMS_FIRST_LOAD = 5;
67
    /** @property {number} The total items will be shown when click on the Show more activities button. */
68
    const DEFAULT_LAZY_LOADING_ITEMS_OTHER_LOAD = 10;
69
 
70
    /**
71
     * Hide the content area and display the empty content message.
72
     *
73
     * @param {object} root The container element
74
     */
75
    var hideContent = function(root) {
76
        root.find(SELECTORS.EVENT_LIST_CONTENT).addClass('hidden');
77
        root.find(SELECTORS.EMPTY_MESSAGE).removeClass('hidden');
78
    };
79
 
80
    /**
81
     * Show the content area and hide the empty content message.
82
     *
83
     * @param {object} root The container element
84
     */
85
    var showContent = function(root) {
86
        root.find(SELECTORS.EVENT_LIST_CONTENT).removeClass('hidden');
87
        root.find(SELECTORS.EMPTY_MESSAGE).addClass('hidden');
88
    };
89
 
90
    /**
91
     * Empty the content area.
92
     *
93
     * @param {object} root The container element
94
     */
95
    var emptyContent = function(root) {
96
        root.find(SELECTORS.EVENT_LIST_CONTENT).empty();
97
    };
98
 
99
    /**
100
     * Construct the template context from a list of calendar events. The events
101
     * are grouped by which day they are on. The day is calculated from the user's
102
     * midnight timestamp to ensure that the calculation is timezone agnostic.
103
     *
104
     * The return data structure will look like:
105
     * {
106
     *      eventsbyday: [
107
     *          {
108
     *              dayTimestamp: 1533744000,
109
     *              events: [
110
     *                  { ...event 1 data... },
111
     *                  { ...event 2 data... }
112
     *              ]
113
     *          },
114
     *          {
115
     *              dayTimestamp: 1533830400,
116
     *              events: [
117
     *                  { ...event 3 data... },
118
     *                  { ...event 4 data... }
119
     *              ]
120
     *          }
121
     *      ]
122
     * }
123
     *
124
     * Each day timestamp is the day's midnight in the user's timezone.
125
     *
126
     * @param {array} calendarEvents List of calendar events
127
     * @return {object}
128
     */
129
    var buildTemplateContext = function(calendarEvents) {
130
        var eventsByDay = {};
131
        var templateContext = {
132
            courseview,
133
            eventsbyday: []
134
        };
135
 
136
        calendarEvents.forEach(function(calendarEvent) {
137
            var dayTimestamp = calendarEvent.timeusermidnight;
138
            if (eventsByDay[dayTimestamp]) {
139
                eventsByDay[dayTimestamp].push(calendarEvent);
140
            } else {
141
                eventsByDay[dayTimestamp] = [calendarEvent];
142
            }
143
        });
144
 
145
        Object.keys(eventsByDay).forEach(function(dayTimestamp) {
146
            var events = eventsByDay[dayTimestamp];
147
            templateContext.eventsbyday.push({
148
                dayTimestamp: dayTimestamp,
149
                events: events
150
            });
151
        });
152
 
153
        return templateContext;
154
    };
155
 
156
    /**
157
     * Render the HTML for the given calendar events.
158
     *
159
     * @param {array} calendarEvents  A list of calendar events
160
     * @return {promise} Resolved with HTML and JS strings.
161
     */
162
    var render = function(calendarEvents) {
163
        var templateContext = buildTemplateContext(calendarEvents);
164
        var templateName = TEMPLATES.EVENT_LIST_CONTENT;
165
 
166
        return Templates.render(templateName, templateContext);
167
    };
168
 
169
    /**
170
     * Retrieve a list of calendar events from the server for the given
171
     * constraints.
172
     *
173
     * @param {Number} midnight The user's midnight time in unix timestamp.
174
     * @param {Number} limit Limit the result set to this number of items
175
     * @param {Number} daysOffset How many days (from midnight) to offset the results from
176
     * @param {int|undefined} daysLimit How many dates (from midnight) to limit the result to
177
     * @param {int|false} lastId The ID of the last seen event (if any)
178
     * @param {int|undefined} courseId Course ID to restrict events to
179
     * @param {string|undefined} searchValue Search value
180
     * @return {Promise} A jquery promise
181
     */
182
    var load = function(midnight, limit, daysOffset, daysLimit, lastId, courseId, searchValue) {
183
        var startTime = midnight + (daysOffset * SECONDS_IN_DAY);
184
        var endTime = daysLimit != undefined ? midnight + (daysLimit * SECONDS_IN_DAY) : false;
185
 
186
        var args = {
187
            starttime: startTime,
188
            limit: limit,
189
        };
190
 
191
        if (lastId) {
192
            args.aftereventid = lastId;
193
        }
194
 
195
        if (endTime) {
196
            args.endtime = endTime;
197
        }
198
 
199
        if (searchValue) {
200
            args.searchvalue = searchValue;
201
        }
202
 
203
        if (courseId) {
204
            // If we have a course id then we only want events from that course.
205
            args.courseid = courseId;
206
            return CalendarEventsRepository.queryByCourse(args);
207
        } else {
208
            // Otherwise we want events from any course.
209
            return CalendarEventsRepository.queryByTime(args);
210
        }
211
    };
212
 
213
    /**
214
     * Create a lazy-loading region for the calendar events in the given root element.
215
     *
216
     * @param {object} root The event list container element.
217
     * @param {object} additionalConfig Additional config options to pass to pagedContentFactory.
218
     */
219
    var init = function(root, additionalConfig = {}) {
220
        const pendingPromise = new Pending('block/timeline:event-init');
221
        root = $(root);
222
 
223
        courseview = !!additionalConfig.courseview;
224
 
225
        // Create a promise that will be resolved once the first set of page
226
        // data has been loaded. This ensures that the loading placeholder isn't
227
        // hidden until we have all of the data back to prevent the page elements
228
        // jumping around.
229
        var firstLoad = $.Deferred();
230
        var eventListContent = root.find(SELECTORS.EVENT_LIST_CONTENT);
231
        var loadingPlaceholder = root.find(SELECTORS.EVENT_LIST_LOADING_PLACEHOLDER);
232
        var courseId = root.attr('data-course-id');
233
        var daysOffset = parseInt(root.attr('data-days-offset'), 10);
234
        var daysLimit = root.attr('data-days-limit');
235
        var midnight = parseInt(root.attr('data-midnight'), 10);
236
        const searchValue = root.closest(SELECTORS.TIMELINE_BLOCK).find(SELECTORS.TIMELINE_SEARCH).val();
237
 
238
        // Make sure the content area and loading placeholder is visible.
239
        // This is because the init function can be called to re-initialise
240
        // an existing event list area.
241
        emptyContent(root);
242
        showContent(root);
243
        loadingPlaceholder.removeClass('hidden');
244
 
245
        // Days limit isn't mandatory.
246
        if (daysLimit != undefined) {
247
            daysLimit = parseInt(daysLimit, 10);
248
        }
249
 
250
        // Create the lazy loading content element.
251
        return createLazyLoadingContent(root, firstLoad,
252
            DEFAULT_LAZY_LOADING_ITEMS_FIRST_LOAD, midnight, 0, courseId, daysOffset, daysLimit, searchValue)
253
            .then(function(html, js) {
254
                firstLoad.then(function(data) {
255
                    if (!data.hasContent) {
256
                        loadingPlaceholder.addClass('hidden');
257
                        // If we didn't get any data then show the empty data message.
258
                        return hideContent(root);
259
                    }
260
 
261
                    html = $(html);
262
                    // Hide the content for now.
263
                    html.addClass('hidden');
264
                    // Replace existing elements with the newly created lazy-loading region.
265
                    Templates.replaceNodeContents(eventListContent, html, js);
266
 
267
                    // Prevent changing page elements too much by only showing the content
268
                    // once we've loaded some data for the first time. This allows our
269
                    // fancy loading placeholder to shine.
270
                    html.removeClass('hidden');
271
                    loadingPlaceholder.addClass('hidden');
272
 
273
                    if (!data.loadedAll) {
274
                        Templates.render(TEMPLATES.MORE_ACTIVITIES_BUTTON, {courseview}).then(function(html) {
275
                            eventListContent.append(html);
276
                            setLastTimestamp(root, data.lastTimeStamp);
277
                            // Init the event handler.
278
                            initEventListener(root);
279
                            return html;
280
                        }).catch(function() {
281
                            return false;
282
                        });
283
                    }
284
 
285
                    return data;
286
                })
287
                .catch(function() {
288
                    return false;
289
                });
290
 
291
                return html;
292
            }).then(() => {
293
                return pendingPromise.resolve();
294
            })
295
            .catch(Notification.exception);
296
    };
297
 
298
    /**
299
     * Create a lazy-loading content element for showing the event list for the initial load.
300
     *
301
     * @param {object} root The event list container element.
302
     * @param {object} firstLoad A jQuery promise to be resolved after the first set of data is loaded.
303
     * @param {int} itemLimit Limit the number of items.
304
     * @param {Number} midnight The user's midnight time in unix timestamp.
305
     * @param {int} lastId The last event ID for each loaded page. Page number is key, id is value.
306
     * @param {int|undefined} courseId Course ID to restrict events to.
307
     * @param {Number} daysOffset How many days (from midnight) to offset the results from.
308
     * @param {int|undefined} daysLimit How many dates (from midnight) to limit the result to.
309
     * @param {string|undefined} searchValue Search value.
310
     * @return {object} jQuery promise resolved with calendar events.
311
     */
312
    const createLazyLoadingContent = (root, firstLoad, itemLimit, midnight, lastId,
313
        courseId, daysOffset, daysLimit, searchValue) => {
314
        return loadEventsForLazyLoading(
315
            root,
316
            itemLimit,
317
            midnight,
318
            lastId,
319
            courseId,
320
            daysOffset,
321
            daysLimit,
322
            searchValue
323
        ).then(data => {
324
            if (data.calendarEvents.length) {
325
                const lastEventId = data.calendarEvents.at(-1).id;
326
                const lastTimeStamp = data.calendarEvents.at(-1).timeusermidnight;
327
                firstLoad.resolve({
328
                    hasContent: true,
329
                    lastId: lastEventId,
330
                    lastTimeStamp: lastTimeStamp,
331
                    loadedAll: data.loadedAll
332
                });
333
                return render(data.calendarEvents, midnight);
334
            } else {
335
                firstLoad.resolve({
336
                    hasContent: false,
337
                    lastId: 0,
338
                    lastTimeStamp: 0,
339
                    loadedAll: true
340
                });
341
                return data.calendarEvents;
342
            }
343
        }).catch(Notification.exception);
344
    };
345
 
346
    /**
347
     * Handle the request from the lazy-loading region.
348
     * Uses the given data like course id, offset... to request the events from the server.
349
     *
350
     * @param {object} root The event list container element.
351
     * @param {int} itemLimit Limit the number of items.
352
     * @param {Number} midnight The user's midnight time in unix timestamp.
353
     * @param {int} lastId The last event ID for each loaded page.
354
     * @param {int|undefined} courseId Course ID to restrict events to.
355
     * @param {Number} daysOffset How many days (from midnight) to offset the results from.
356
     * @param {int|undefined} daysLimit How many dates (from midnight) to limit the result to.
357
     * @param {string|undefined} searchValue Search value.
358
     * @return {object} jQuery promise resolved with calendar events.
359
     */
360
    const loadEventsForLazyLoading = (root, itemLimit, midnight, lastId, courseId, daysOffset, daysLimit, searchValue) => {
361
        // Load one more than the given limit so that we can tell if there
362
        // is more content to load after this.
363
        const eventsPromise = load(midnight, itemLimit + 1, daysOffset, daysLimit, lastId, courseId, searchValue);
364
        let calendarEvents = [];
365
        let loadedAll = true;
366
 
367
        return eventsPromise.then(result => {
368
            if (!result.events.length) {
369
                return {calendarEvents, loadedAll};
370
            }
371
 
372
            // Determine if the overdue filter is applied.
373
            const overdueFilter = document.querySelector("[data-filtername='overdue']");
374
            const filterByOverdue = (overdueFilter && overdueFilter.getAttribute('aria-current'));
375
 
376
            calendarEvents = result.events.filter(event => {
377
                if (event.eventtype == 'open' || event.eventtype == 'opensubmission') {
378
                    const dayTimestamp = UserDate.getUserMidnightForTimestamp(event.timesort, midnight);
379
                    return dayTimestamp > midnight;
380
                }
381
                // When filtering by overdue, we fetch all events due today, in case any have elapsed already and are overdue.
382
                // This means if filtering by overdue, some events fetched might not be required (eg if due later today).
383
                return (!filterByOverdue || event.overdue);
384
            });
385
 
386
            loadedAll = calendarEvents.length <= itemLimit;
387
 
388
            if (!loadedAll) {
389
                // Remove the last element from the array because it isn't
390
                // needed in this result set.
391
                calendarEvents.pop();
392
            }
393
 
394
            if (calendarEvents.length) {
395
                const lastEventId = calendarEvents.at(-1).id;
396
                setOffset(root, lastEventId);
397
            }
398
 
399
            return {calendarEvents, loadedAll};
400
        });
401
    };
402
 
403
    /**
404
     * Load new events and append to current list.
405
     *
406
     * @param {object} root The event list container element.
407
     */
408
    const loadMoreEvents = root => {
409
        const midnight = parseInt(root.attr('data-midnight'), 10);
410
        const courseId = root.attr('data-course-id');
411
        const daysOffset = parseInt(root.attr('data-days-offset'), 10);
412
        const daysLimit = root.attr('data-days-limit');
413
        const lastId = getOffset(root);
414
        const eventListWrapper = root.find(SELECTORS.EVENT_LIST_WRAPPER);
415
        const searchValue = root.closest(SELECTORS.TIMELINE_BLOCK).find(SELECTORS.TIMELINE_SEARCH).val();
416
        const eventsPromise = loadEventsForLazyLoading(
417
            root,
418
            DEFAULT_LAZY_LOADING_ITEMS_OTHER_LOAD,
419
            midnight,
420
            lastId,
421
            courseId,
422
            daysOffset,
423
            daysLimit,
424
            searchValue
425
        );
426
        eventsPromise.then(data => {
427
            if (data.calendarEvents.length) {
428
                const renderPromise = render(data.calendarEvents);
429
                const lastTimestamp = getLastTimestamp(root);
430
                renderPromise.then((html, js) => {
431
                    html = $(html);
432
 
433
                    // Remove the date heading if it has the same value as the previous one.
434
                    html.find(`[data-timestamp="${lastTimestamp}"]`).remove();
435
                    Templates.appendNodeContents(eventListWrapper, html.html(), js);
436
 
437
                    if (!data.loadedAll) {
438
                        Templates.render(TEMPLATES.MORE_ACTIVITIES_BUTTON, {}).then(html => {
439
                            eventListWrapper.append(html);
440
                            setLastTimestamp(root, data.calendarEvents.at(-1).timeusermidnight);
441
                            // Init the event handler.
442
                            initEventListener(root);
443
 
444
                            return html;
445
                        }).catch(() => {
446
                            return false;
447
                        });
448
                    }
449
 
450
                    return html;
451
                }).catch(Notification.exception);
452
            }
453
 
454
            return data;
455
        }).then(() => {
456
            return disableMoreActivitiesButtonLoading(root);
457
        }).catch(Notification.exception);
458
    };
459
 
460
    /**
461
     * Return the offset value for lazy loading fetching.
462
     *
463
     * @param {object} element The event list container element.
464
     * @return {Number} Offset value.
465
     */
466
    const getOffset = element => {
467
        return parseInt(element.attr('data-lazyload-offset'), 10);
468
    };
469
 
470
    /**
471
     * Set the offset value for lazy loading fetching.
472
     *
473
     * @param {object} element The event list container element.
474
     * @param {Number} offset Offset value.
475
     */
476
    const setOffset = (element, offset) => {
477
        element.attr('data-lazyload-offset', offset);
478
    };
479
 
480
    /**
481
     * Return the timestamp value for lazy loading fetching.
482
     *
483
     * @param {object} element The event list container element.
484
     * @return {Number} Timestamp value.
485
     */
486
    const getLastTimestamp = element => {
487
        return parseInt(element.attr('data-timestamp'), 10);
488
    };
489
 
490
    /**
491
     * Set the timestamp value for lazy loading fetching.
492
     *
493
     * @param {object} element The event list container element.
494
     * @param {Number} timestamp Timestamp value.
495
     */
496
    const setLastTimestamp = (element, timestamp) => {
497
        element.attr('data-timestamp', timestamp);
498
    };
499
 
500
    /**
501
     * Add the "Show more activities" button and remove and loading spinner.
502
     *
503
     * @param {object} root The event list container element.
504
     */
505
    const enableMoreActivitiesButtonLoading = root => {
506
        const loadMoreButton = root.find(SELECTORS.MORE_ACTIVITIES_BUTTON);
507
        loadMoreButton.prop('disabled', true);
508
        Templates.render(TEMPLATES.LOADING_ICON, {}).then(html => {
509
            loadMoreButton.append(html);
510
            return html;
511
        }).catch(() => {
512
            // It's not important if this false so just do so silently.
513
            return false;
514
        });
515
    };
516
 
517
    /**
518
     * Remove the "Show more activities" button and remove and loading spinner.
519
     *
520
     * @param {object} root The event list container element.
521
     */
522
    const disableMoreActivitiesButtonLoading = root => {
523
        const loadMoreButtonContainer = root.find(SELECTORS.MORE_ACTIVITIES_BUTTON_CONTAINER);
524
        loadMoreButtonContainer.remove();
525
    };
526
 
527
    /**
528
     * Event initialise.
529
     *
530
     * @param {object} root The event list container element.
531
     */
532
    const initEventListener = root => {
533
        const loadMoreButton = root.find(SELECTORS.MORE_ACTIVITIES_BUTTON);
534
        loadMoreButton.on('click', () => {
535
            enableMoreActivitiesButtonLoading(root);
536
            loadMoreEvents(root);
537
        });
538
    };
539
 
540
    return {
541
        init: init,
542
        rootSelector: SELECTORS.ROOT,
543
    };
544
});