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
 * Manage the courses view for the overview block.
18
 *
19
 * @copyright  2018 Bas Brands <bas@moodle.com>
20
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
21
 */
22
 
23
import $ from 'jquery';
24
import * as Repository from 'block_myoverview/repository';
25
import * as PagedContentFactory from 'core/paged_content_factory';
26
import * as PubSub from 'core/pubsub';
27
import * as CustomEvents from 'core/custom_interaction_events';
28
import * as Notification from 'core/notification';
29
import * as Templates from 'core/templates';
30
import * as CourseEvents from 'core_course/events';
31
import SELECTORS from 'block_myoverview/selectors';
32
import * as PagedContentEvents from 'core/paged_content_events';
33
import * as Aria from 'core/aria';
34
import {debounce} from 'core/utils';
35
import {setUserPreference} from 'core_user/repository';
36
 
37
const TEMPLATES = {
38
    COURSES_CARDS: 'block_myoverview/view-cards',
39
    COURSES_LIST: 'block_myoverview/view-list',
40
    COURSES_SUMMARY: 'block_myoverview/view-summary',
41
    NOCOURSES: 'core_course/no-courses'
42
};
43
 
44
const GROUPINGS = {
45
    GROUPING_ALLINCLUDINGHIDDEN: 'allincludinghidden',
46
    GROUPING_ALL: 'all',
47
    GROUPING_INPROGRESS: 'inprogress',
48
    GROUPING_FUTURE: 'future',
49
    GROUPING_PAST: 'past',
50
    GROUPING_FAVOURITES: 'favourites',
51
    GROUPING_HIDDEN: 'hidden'
52
};
53
 
54
const NUMCOURSES_PERPAGE = [12, 24, 48, 96, 0];
55
 
56
let loadedPages = [];
57
 
58
let courseOffset = 0;
59
 
60
let lastPage = 0;
61
 
62
let lastLimit = 0;
63
 
64
let namespace = null;
65
 
66
/**
67
 * Whether the summary display has been loaded.
68
 *
69
 * If true, this means that courses have been loaded with the summary text.
70
 * Otherwise, switching to the summary display mode will require course data to be fetched with the summary text.
71
 *
72
 * @type {boolean}
73
 */
74
let summaryDisplayLoaded = false;
75
 
76
/**
77
 * Get filter values from DOM.
78
 *
79
 * @param {object} root The root element for the courses view.
80
 * @return {filters} Set filters.
81
 */
82
const getFilterValues = root => {
83
    const courseRegion = root.find(SELECTORS.courseView.region);
84
    return {
85
        display: courseRegion.attr('data-display'),
86
        grouping: courseRegion.attr('data-grouping'),
87
        sort: courseRegion.attr('data-sort'),
88
        displaycategories: courseRegion.attr('data-displaycategories'),
89
        customfieldname: courseRegion.attr('data-customfieldname'),
90
        customfieldvalue: courseRegion.attr('data-customfieldvalue'),
91
    };
92
};
93
 
94
// We want the paged content controls below the paged content area.
95
// and the controls should be ignored while data is loading.
96
const DEFAULT_PAGED_CONTENT_CONFIG = {
97
    ignoreControlWhileLoading: true,
98
    controlPlacementBottom: true,
99
    persistentLimitKey: 'block_myoverview_user_paging_preference'
100
};
101
 
102
/**
103
 * Get enrolled courses from backend.
104
 *
105
 * @param {object} filters The filters for this view.
106
 * @param {int} limit The number of courses to show.
107
 * @return {promise} Resolved with an array of courses.
108
 */
109
const getMyCourses = (filters, limit) => {
110
    const params = {
111
        offset: courseOffset,
112
        limit: limit,
113
        classification: filters.grouping,
114
        sort: filters.sort,
115
        customfieldname: filters.customfieldname,
116
        customfieldvalue: filters.customfieldvalue,
117
    };
118
    if (filters.display === 'summary') {
119
        params.requiredfields = Repository.SUMMARY_REQUIRED_FIELDS;
120
        summaryDisplayLoaded = true;
121
    } else {
122
        params.requiredfields = Repository.CARDLIST_REQUIRED_FIELDS;
123
    }
124
    return Repository.getEnrolledCoursesByTimeline(params);
125
};
126
 
127
/**
128
 * Search for enrolled courses from backend.
129
 *
130
 * @param {object} filters The filters for this view.
131
 * @param {int} limit The number of courses to show.
132
 * @param {string} searchValue What does the user want to search within their courses.
133
 * @return {promise} Resolved with an array of courses.
134
 */
135
const getSearchMyCourses = (filters, limit, searchValue) => {
136
    const params = {
137
        offset: courseOffset,
138
        limit: limit,
139
        classification: 'search',
140
        sort: filters.sort,
141
        customfieldname: filters.customfieldname,
142
        customfieldvalue: filters.customfieldvalue,
143
        searchvalue: searchValue,
144
    };
145
    if (filters.display === 'summary') {
146
        params.requiredfields = Repository.SUMMARY_REQUIRED_FIELDS;
147
        summaryDisplayLoaded = true;
148
    } else {
149
        params.requiredfields = Repository.CARDLIST_REQUIRED_FIELDS;
150
        summaryDisplayLoaded = false;
151
    }
152
    return Repository.getEnrolledCoursesByTimeline(params);
153
};
154
 
155
/**
156
 * Get the container element for the favourite icon.
157
 *
158
 * @param {Object} root The course overview container
159
 * @param {Number} courseId Course id number
160
 * @return {Object} The favourite icon container
161
 */
162
const getFavouriteIconContainer = (root, courseId) => {
163
    return root.find(SELECTORS.FAVOURITE_ICON + '[data-course-id="' + courseId + '"]');
164
};
165
 
166
/**
167
 * Get the paged content container element.
168
 *
169
 * @param {Object} root The course overview container
170
 * @param {Number} index Rendered page index.
171
 * @return {Object} The rendered paged container.
172
 */
173
const getPagedContentContainer = (root, index) => {
174
    return root.find('[data-region="paged-content-page"][data-page="' + index + '"]');
175
};
176
 
177
/**
178
 * Get the course id from a favourite element.
179
 *
180
 * @param {Object} root The favourite icon container element.
181
 * @return {Number} Course id.
182
 */
183
const getCourseId = root => {
184
    return root.attr('data-course-id');
185
};
186
 
187
/**
188
 * Hide the favourite icon.
189
 *
190
 * @param {Object} root The favourite icon container element.
191
 * @param {Number} courseId Course id number.
192
 */
193
const hideFavouriteIcon = (root, courseId) => {
194
    const iconContainer = getFavouriteIconContainer(root, courseId);
195
 
196
    const isFavouriteIcon = iconContainer.find(SELECTORS.ICON_IS_FAVOURITE);
197
    isFavouriteIcon.addClass('hidden');
198
    Aria.hide(isFavouriteIcon);
199
 
200
    const notFavourteIcon = iconContainer.find(SELECTORS.ICON_NOT_FAVOURITE);
201
    notFavourteIcon.removeClass('hidden');
202
    Aria.unhide(notFavourteIcon);
203
};
204
 
205
/**
206
 * Show the favourite icon.
207
 *
208
 * @param {Object} root The course overview container.
209
 * @param {Number} courseId Course id number.
210
 */
211
const showFavouriteIcon = (root, courseId) => {
212
    const iconContainer = getFavouriteIconContainer(root, courseId);
213
 
214
    const isFavouriteIcon = iconContainer.find(SELECTORS.ICON_IS_FAVOURITE);
215
    isFavouriteIcon.removeClass('hidden');
216
    Aria.unhide(isFavouriteIcon);
217
 
218
    const notFavourteIcon = iconContainer.find(SELECTORS.ICON_NOT_FAVOURITE);
219
    notFavourteIcon.addClass('hidden');
220
    Aria.hide(notFavourteIcon);
221
};
222
 
223
/**
224
 * Get the action menu item
225
 *
226
 * @param {Object} root The course overview container
227
 * @param {Number} courseId Course id.
228
 * @return {Object} The add to favourite menu item.
229
 */
230
const getAddFavouriteMenuItem = (root, courseId) => {
231
    return root.find('[data-action="add-favourite"][data-course-id="' + courseId + '"]');
232
};
233
 
234
/**
235
 * Get the action menu item
236
 *
237
 * @param {Object} root The course overview container
238
 * @param {Number} courseId Course id.
239
 * @return {Object} The remove from favourites menu item.
240
 */
241
const getRemoveFavouriteMenuItem = (root, courseId) => {
242
    return root.find('[data-action="remove-favourite"][data-course-id="' + courseId + '"]');
243
};
244
 
245
/**
246
 * Add course to favourites
247
 *
248
 * @param {Object} root The course overview container
249
 * @param {Number} courseId Course id number
250
 */
251
const addToFavourites = (root, courseId) => {
252
    const removeAction = getRemoveFavouriteMenuItem(root, courseId);
253
    const addAction = getAddFavouriteMenuItem(root, courseId);
254
 
255
    setCourseFavouriteState(courseId, true).then(success => {
256
        if (success) {
257
            PubSub.publish(CourseEvents.favourited, courseId);
258
            removeAction.removeClass('hidden');
259
            addAction.addClass('hidden');
260
            showFavouriteIcon(root, courseId);
261
        } else {
262
            Notification.alert('Starring course failed', 'Could not change favourite state');
263
        }
264
        return;
265
    }).catch(Notification.exception);
266
};
267
 
268
/**
269
 * Remove course from favourites
270
 *
271
 * @param {Object} root The course overview container
272
 * @param {Number} courseId Course id number
273
 */
274
const removeFromFavourites = (root, courseId) => {
275
    const removeAction = getRemoveFavouriteMenuItem(root, courseId);
276
    const addAction = getAddFavouriteMenuItem(root, courseId);
277
 
278
    setCourseFavouriteState(courseId, false).then(success => {
279
        if (success) {
280
            PubSub.publish(CourseEvents.unfavorited, courseId);
281
            removeAction.addClass('hidden');
282
            addAction.removeClass('hidden');
283
            hideFavouriteIcon(root, courseId);
284
        } else {
285
            Notification.alert('Starring course failed', 'Could not change favourite state');
286
        }
287
        return;
288
    }).catch(Notification.exception);
289
};
290
 
291
/**
292
 * Get the action menu item
293
 *
294
 * @param {Object} root The course overview container
295
 * @param {Number} courseId Course id.
296
 * @return {Object} The hide course menu item.
297
 */
298
const getHideCourseMenuItem = (root, courseId) => {
299
    return root.find('[data-action="hide-course"][data-course-id="' + courseId + '"]');
300
};
301
 
302
/**
303
 * Get the action menu item
304
 *
305
 * @param {Object} root The course overview container
306
 * @param {Number} courseId Course id.
307
 * @return {Object} The show course menu item.
308
 */
309
const getShowCourseMenuItem = (root, courseId) => {
310
    return root.find('[data-action="show-course"][data-course-id="' + courseId + '"]');
311
};
312
 
313
/**
314
 * Hide course
315
 *
316
 * @param {Object} root The course overview container
317
 * @param {Number} courseId Course id number
318
 */
319
const hideCourse = (root, courseId) => {
320
    const hideAction = getHideCourseMenuItem(root, courseId);
321
    const showAction = getShowCourseMenuItem(root, courseId);
322
    const filters = getFilterValues(root);
323
 
324
    setCourseHiddenState(courseId, true);
325
 
326
    // Remove the course from this view as it is now hidden and thus not covered by this view anymore.
327
    // Do only if we are not in "All (including archived)" view mode where really all courses are shown.
328
    if (filters.grouping !== GROUPINGS.GROUPING_ALLINCLUDINGHIDDEN) {
329
        hideElement(root, courseId);
330
    }
331
 
332
    hideAction.addClass('hidden');
333
    showAction.removeClass('hidden');
334
};
335
 
336
/**
337
 * Show course
338
 *
339
 * @param {Object} root The course overview container
340
 * @param {Number} courseId Course id number
341
 */
342
const showCourse = (root, courseId) => {
343
    const hideAction = getHideCourseMenuItem(root, courseId);
344
    const showAction = getShowCourseMenuItem(root, courseId);
345
    const filters = getFilterValues(root);
346
 
347
    setCourseHiddenState(courseId, null);
348
 
349
    // Remove the course from this view as it is now shown again and thus not covered by this view anymore.
350
    // Do only if we are not in "All (including archived)" view mode where really all courses are shown.
351
    if (filters.grouping !== GROUPINGS.GROUPING_ALLINCLUDINGHIDDEN) {
352
        hideElement(root, courseId);
353
    }
354
 
355
    hideAction.removeClass('hidden');
356
    showAction.addClass('hidden');
357
};
358
 
359
/**
360
 * Set the courses hidden status and push to repository
361
 *
362
 * @param {Number} courseId Course id to favourite.
363
 * @param {Boolean} status new hidden status.
364
 * @return {Promise} Repository promise.
365
 */
366
const setCourseHiddenState = (courseId, status) => {
367
 
368
    // If the given status is not hidden, the preference has to be deleted with a null value.
369
    if (status === false) {
370
        status = null;
371
    }
372
 
373
    return setUserPreference(`block_myoverview_hidden_course_${courseId}`, status)
374
        .catch(Notification.exception);
375
};
376
 
377
/**
378
 * Reset the loadedPages dataset to take into account the hidden element
379
 *
380
 * @param {Object} root The course overview container
381
 * @param {Number} id The course id number
382
 */
383
const hideElement = (root, id) => {
384
    const pagingBar = root.find('[data-region="paging-bar"]');
385
    const jumpto = parseInt(pagingBar.attr('data-active-page-number'));
386
 
387
    // Get a reduced dataset for the current page.
388
    const courseList = loadedPages[jumpto];
389
    let reducedCourse = courseList.courses.reduce((accumulator, current) => {
390
        if (+id !== +current.id) {
391
            accumulator.push(current);
392
        }
393
        return accumulator;
394
    }, []);
395
 
396
    // Get the next page's data if loaded and pop the first element from it.
397
    if (typeof (loadedPages[jumpto + 1]) !== 'undefined') {
398
        const newElement = loadedPages[jumpto + 1].courses.slice(0, 1);
399
 
400
        // Adjust the dataset for the reset of the pages that are loaded.
401
        loadedPages.forEach((courseList, index) => {
402
            if (index > jumpto) {
403
                let popElement = [];
404
                if (typeof (loadedPages[index + 1]) !== 'undefined') {
405
                    popElement = loadedPages[index + 1].courses.slice(0, 1);
406
                }
407
                loadedPages[index].courses = [...loadedPages[index].courses.slice(1), ...popElement];
408
            }
409
        });
410
 
411
        reducedCourse = [...reducedCourse, ...newElement];
412
    }
413
 
414
    // Check if the next page is the last page and if it still has data associated to it.
415
    if (lastPage === jumpto + 1 && loadedPages[jumpto + 1].courses.length === 0) {
416
        const pagedContentContainer = root.find('[data-region="paged-content-container"]');
417
        PagedContentFactory.resetLastPageNumber($(pagedContentContainer).attr('id'), jumpto);
418
    }
419
 
420
    loadedPages[jumpto].courses = reducedCourse;
421
 
422
    // Reduce the course offset.
423
    courseOffset--;
424
 
425
    // Render the paged content for the current.
426
    const pagedContentPage = getPagedContentContainer(root, jumpto);
427
    renderCourses(root, loadedPages[jumpto]).then((html, js) => {
428
        return Templates.replaceNodeContents(pagedContentPage, html, js);
429
    }).catch(Notification.exception);
430
 
431
    // Delete subsequent pages in order to trigger the callback.
432
    loadedPages.forEach((courseList, index) => {
433
        if (index > jumpto) {
434
            const page = getPagedContentContainer(root, index);
435
            page.remove();
436
        }
437
    });
438
};
439
 
440
/**
441
 * Set the courses favourite status and push to repository
442
 *
443
 * @param {Number} courseId Course id to favourite.
444
 * @param {boolean} status new favourite status.
445
 * @return {Promise} Repository promise.
446
 */
447
const setCourseFavouriteState = (courseId, status) => {
448
 
449
    return Repository.setFavouriteCourses({
450
        courses: [
451
            {
452
                'id': courseId,
453
                'favourite': status
454
            }
455
        ]
456
    }).then(result => {
457
        if (result.warnings.length === 0) {
458
            loadedPages.forEach(courseList => {
459
                courseList.courses.forEach((course, index) => {
460
                    if (course.id == courseId) {
461
                        courseList.courses[index].isfavourite = status;
462
                    }
463
                });
464
            });
465
            return true;
466
        } else {
467
            return false;
468
        }
469
    }).catch(Notification.exception);
470
};
471
 
472
/**
473
 * Given there are no courses to render provide the rendered template.
474
 *
475
 * @param {object} root The root element for the courses view.
476
 * @return {promise} jQuery promise resolved after rendering is complete.
477
 */
478
const noCoursesRender = root => {
479
    const nocoursesimg = root.find(SELECTORS.courseView.region).attr('data-nocoursesimg');
480
    const newcourseurl = root.find(SELECTORS.courseView.region).attr('data-newcourseurl');
481
    return Templates.render(TEMPLATES.NOCOURSES, {
482
        nocoursesimg: nocoursesimg,
483
        newcourseurl: newcourseurl
484
    });
485
};
486
 
487
/**
488
 * Render the dashboard courses.
489
 *
490
 * @param {object} root The root element for the courses view.
491
 * @param {array} coursesData containing array of returned courses.
492
 * @return {promise} jQuery promise resolved after rendering is complete.
493
 */
494
const renderCourses = (root, coursesData) => {
495
 
496
    const filters = getFilterValues(root);
497
 
498
    let currentTemplate = '';
499
    if (filters.display === 'card') {
500
        currentTemplate = TEMPLATES.COURSES_CARDS;
501
    } else if (filters.display === 'list') {
502
        currentTemplate = TEMPLATES.COURSES_LIST;
503
    } else {
504
        currentTemplate = TEMPLATES.COURSES_SUMMARY;
505
    }
506
 
507
    if (!coursesData) {
508
        return noCoursesRender(root);
509
    } else {
510
        // Sometimes we get weird objects coming after a failed search, cast to ensure typing functions.
511
        if (Array.isArray(coursesData.courses) === false) {
512
            coursesData.courses = Object.values(coursesData.courses);
513
        }
514
        // Whether the course category should be displayed in the course item.
515
        coursesData.courses = coursesData.courses.map(course => {
516
            course.showcoursecategory = filters.displaycategories === 'on';
517
            return course;
518
        });
519
        if (coursesData.courses.length) {
520
            return Templates.render(currentTemplate, {
521
                courses: coursesData.courses,
522
            });
523
        } else {
524
            return noCoursesRender(root);
525
        }
526
    }
527
};
528
 
529
/**
530
 * Return the callback to be passed to the subscribe event
531
 *
532
 * @param {object} root The root element for the courses view
533
 * @return {function} Partially applied function that'll execute when passed a limit
534
 */
535
const setLimit = root => {
536
    // @param {Number} limit The paged limit that is passed through the event.
537
    return limit => root.find(SELECTORS.courseView.region).attr('data-paging', limit);
538
};
539
 
540
/**
541
 * Intialise the paged list and cards views on page load.
542
 * Returns an array of paged contents that we would like to handle here
543
 *
544
 * @param {object} root The root element for the courses view
545
 * @param {string} namespace The namespace for all the events attached
546
 */
547
const registerPagedEventHandlers = (root, namespace) => {
548
    const event = namespace + PagedContentEvents.SET_ITEMS_PER_PAGE_LIMIT;
549
    PubSub.subscribe(event, setLimit(root));
550
};
551
 
552
/**
553
 * Figure out how many items are going to be allowed to be rendered in the block.
554
 *
555
 * @param  {Number} pagingLimit How many courses to display
556
 * @param  {Object} root The course overview container
557
 * @return {Number[]} How many courses will be rendered
558
 */
559
const itemsPerPageFunc = (pagingLimit, root) => {
560
    let itemsPerPage = NUMCOURSES_PERPAGE.map(value => {
561
        let active = false;
562
        if (value === pagingLimit) {
563
            active = true;
564
        }
565
 
566
        return {
567
            value: value,
568
            active: active
569
        };
570
    });
571
 
572
    // Filter out all pagination options which are too large for the amount of courses user is enrolled in.
573
    const totalCourseCount = parseInt(root.find(SELECTORS.courseView.region).attr('data-totalcoursecount'), 10);
574
    return itemsPerPage.filter(pagingOption => {
575
        if (pagingOption.value === 0 && totalCourseCount > 100) {
576
            // To minimise performance issues, do not show the "All" option if the user is enrolled in more than 100 courses.
577
            return false;
578
        }
579
        return pagingOption.value < totalCourseCount;
580
    });
581
};
582
 
583
/**
584
 * Mutates and controls the loadedPages array and handles the bootstrapping.
585
 *
586
 * @param {Array|Object} coursesData Array of all of the courses to start building the page from
587
 * @param {Number} currentPage What page are we currently on?
588
 * @param {Object} pageData Any current page information
589
 * @param {Object} actions Paged content helper
590
 * @param {null|boolean} activeSearch Are we currently actively searching and building up search results?
591
 */
592
const pageBuilder = (coursesData, currentPage, pageData, actions, activeSearch = null) => {
593
    // If the courseData comes in an object then get the value otherwise it is a pure array.
594
    let courses = coursesData.courses ? coursesData.courses : coursesData;
595
    let nextPageStart = 0;
596
    let pageCourses = [];
597
 
598
    // If current page's data is loaded make sure we max it to page limit.
599
    if (typeof (loadedPages[currentPage]) !== 'undefined') {
600
        pageCourses = loadedPages[currentPage].courses;
601
        const currentPageLength = pageCourses.length;
602
        if (currentPageLength < pageData.limit) {
603
            nextPageStart = pageData.limit - currentPageLength;
604
            pageCourses = {...loadedPages[currentPage].courses, ...courses.slice(0, nextPageStart)};
605
        }
606
    } else {
607
        // When the page limit is zero, there is only one page of courses, no start for next page.
608
        nextPageStart = pageData.limit || false;
609
        pageCourses = (pageData.limit > 0) ? courses.slice(0, pageData.limit) : courses;
610
    }
611
 
612
    // Finished setting up the current page.
613
    loadedPages[currentPage] = {
614
        courses: pageCourses
615
    };
616
 
617
    // Set up the next page (if there is more than one page).
618
    const remainingCourses = nextPageStart !== false ? courses.slice(nextPageStart, courses.length) : [];
619
    if (remainingCourses.length) {
620
        loadedPages[currentPage + 1] = {
621
            courses: remainingCourses
622
        };
623
    }
624
 
625
    // Set the last page to either the current or next page.
626
    if (loadedPages[currentPage].courses.length < pageData.limit || !remainingCourses.length) {
627
        lastPage = currentPage;
628
        if (activeSearch === null) {
629
            actions.allItemsLoaded(currentPage);
630
        }
631
    } else if (typeof (loadedPages[currentPage + 1]) !== 'undefined'
632
        && loadedPages[currentPage + 1].courses.length < pageData.limit) {
633
        lastPage = currentPage + 1;
634
    }
635
 
636
    courseOffset = coursesData.nextoffset;
637
};
638
 
639
/**
640
 * In cases when switching between regular rendering and search rendering we need to reset some variables.
641
 */
642
const resetGlobals = () => {
643
    courseOffset = 0;
644
    loadedPages = [];
645
    lastPage = 0;
646
    lastLimit = 0;
647
};
648
 
649
/**
650
 * The default functionality of fetching paginated courses without special handling.
651
 *
652
 * @return {function(Object, Object, Object, Object, Object, Promise, Number): void}
653
 */
654
const standardFunctionalityCurry = () => {
655
    resetGlobals();
656
    return (filters, currentPage, pageData, actions, root, promises, limit) => {
657
        const pagePromise = getMyCourses(
658
            filters,
659
            limit
660
        ).then(coursesData => {
661
            pageBuilder(coursesData, currentPage, pageData, actions);
662
            return renderCourses(root, loadedPages[currentPage]);
663
        }).catch(Notification.exception);
664
 
665
        promises.push(pagePromise);
666
    };
667
};
668
 
669
/**
670
 * Initialize the searching functionality so we can call it when required.
671
 *
672
 * @return {function(Object, Number, Object, Object, Object, Promise, Number, String): void}
673
 */
674
const searchFunctionalityCurry = () => {
675
    resetGlobals();
676
    return (filters, currentPage, pageData, actions, root, promises, limit, inputValue) => {
677
        const searchingPromise = getSearchMyCourses(
678
            filters,
679
            limit,
680
            inputValue
681
        ).then(coursesData => {
682
            pageBuilder(coursesData, currentPage, pageData, actions);
683
            return renderCourses(root, loadedPages[currentPage]);
684
        }).catch(Notification.exception);
685
 
686
        promises.push(searchingPromise);
687
    };
688
};
689
 
690
/**
691
 * Initialise the courses list and cards views on page load.
692
 *
693
 * @param {object} root The root element for the courses view.
694
 * @param {function} promiseFunction How do we fetch the courses and what do we do with them?
695
 * @param {null | string} inputValue What to search for
696
 */
697
const initializePagedContent = (root, promiseFunction, inputValue = null) => {
698
    const pagingLimit = parseInt(root.find(SELECTORS.courseView.region).attr('data-paging'), 10);
699
    let itemsPerPage = itemsPerPageFunc(pagingLimit, root);
700
 
701
    const config = {...{}, ...DEFAULT_PAGED_CONTENT_CONFIG};
702
    config.eventNamespace = namespace;
703
 
704
    const pagedContentPromise = PagedContentFactory.createWithLimit(
705
        itemsPerPage,
706
        (pagesData, actions) => {
707
            let promises = [];
708
            pagesData.forEach(pageData => {
709
                const currentPage = pageData.pageNumber;
710
                let limit = (pageData.limit > 0) ? pageData.limit : 0;
711
 
712
                // Reset local variables if limits have changed.
713
                if (+lastLimit !== +limit) {
714
                    loadedPages = [];
715
                    courseOffset = 0;
716
                    lastPage = 0;
717
                }
718
 
719
                if (lastPage === currentPage) {
720
                    // If we are on the last page and have it's data then load it from cache.
721
                    actions.allItemsLoaded(lastPage);
722
                    promises.push(renderCourses(root, loadedPages[currentPage]));
723
                    return;
724
                }
725
 
726
                lastLimit = limit;
727
 
728
                // Get 2 pages worth of data as we will need it for the hidden functionality.
729
                if (typeof (loadedPages[currentPage + 1]) === 'undefined') {
730
                    if (typeof (loadedPages[currentPage]) === 'undefined') {
731
                        limit *= 2;
732
                    }
733
                }
734
 
735
                // Get the current applied filters.
736
                const filters = getFilterValues(root);
737
 
738
                // Call the curried function that'll handle the course promise and any manipulation of it.
739
                promiseFunction(filters, currentPage, pageData, actions, root, promises, limit, inputValue);
740
            });
741
            return promises;
742
        },
743
        config
744
    );
745
 
746
    pagedContentPromise.then((html, js) => {
747
        registerPagedEventHandlers(root, namespace);
748
        return Templates.replaceNodeContents(root.find(SELECTORS.courseView.region), html, js);
749
    }).catch(Notification.exception);
750
};
751
 
752
/**
753
 * Listen to, and handle events for the myoverview block.
754
 *
755
 * @param {Object} root The myoverview block container element.
756
 * @param {HTMLElement} page The whole HTMLElement for our block.
757
 */
758
const registerEventListeners = (root, page) => {
759
 
760
    CustomEvents.define(root, [
761
        CustomEvents.events.activate
762
    ]);
763
 
764
    root.on(CustomEvents.events.activate, SELECTORS.ACTION_ADD_FAVOURITE, (e, data) => {
765
        const favourite = $(e.target).closest(SELECTORS.ACTION_ADD_FAVOURITE);
766
        const courseId = getCourseId(favourite);
767
        addToFavourites(root, courseId);
768
        data.originalEvent.preventDefault();
769
    });
770
 
771
    root.on(CustomEvents.events.activate, SELECTORS.ACTION_REMOVE_FAVOURITE, (e, data) => {
772
        const favourite = $(e.target).closest(SELECTORS.ACTION_REMOVE_FAVOURITE);
773
        const courseId = getCourseId(favourite);
774
        removeFromFavourites(root, courseId);
775
        data.originalEvent.preventDefault();
776
    });
777
 
778
    root.on(CustomEvents.events.activate, SELECTORS.FAVOURITE_ICON, (e, data) => {
779
        data.originalEvent.preventDefault();
780
    });
781
 
782
    root.on(CustomEvents.events.activate, SELECTORS.ACTION_HIDE_COURSE, (e, data) => {
783
        const target = $(e.target).closest(SELECTORS.ACTION_HIDE_COURSE);
784
        const courseId = getCourseId(target);
785
        hideCourse(root, courseId);
786
        data.originalEvent.preventDefault();
787
    });
788
 
789
    root.on(CustomEvents.events.activate, SELECTORS.ACTION_SHOW_COURSE, (e, data) => {
790
        const target = $(e.target).closest(SELECTORS.ACTION_SHOW_COURSE);
791
        const courseId = getCourseId(target);
792
        showCourse(root, courseId);
793
        data.originalEvent.preventDefault();
794
    });
795
 
796
    // Searching functionality event handlers.
797
    const input = page.querySelector(SELECTORS.region.searchInput);
798
    const clearIcon = page.querySelector(SELECTORS.region.clearIcon);
799
 
800
    clearIcon.addEventListener('click', () => {
801
        input.value = '';
802
        input.focus();
803
        clearSearch(clearIcon, root);
804
    });
805
 
806
    input.addEventListener('input', debounce(() => {
807
        if (input.value === '') {
808
            clearSearch(clearIcon, root);
809
        } else {
810
            activeSearch(clearIcon);
811
            initializePagedContent(root, searchFunctionalityCurry(), input.value.trim());
812
        }
813
    }, 1000));
814
};
815
 
816
/**
817
 * Reset the search icon and trigger the init for the block.
818
 *
819
 * @param {HTMLElement} clearIcon Our closing icon to manipulate.
820
 * @param {Object} root The myoverview block container element.
821
 */
822
export const clearSearch = (clearIcon, root) => {
823
    clearIcon.classList.add('d-none');
824
    init(root);
825
};
826
 
827
/**
828
 * Change the searching icon to its' active state.
829
 *
830
 * @param {HTMLElement} clearIcon Our closing icon to manipulate.
831
 */
832
const activeSearch = (clearIcon) => {
833
    clearIcon.classList.remove('d-none');
834
};
835
 
836
/**
837
 * Intialise the courses list and cards views on page load.
838
 *
839
 * @param {object} root The root element for the courses view.
840
 */
841
export const init = root => {
842
    root = $(root);
843
    loadedPages = [];
844
    lastPage = 0;
845
    courseOffset = 0;
846
 
847
    if (!root.attr('data-init')) {
848
        const page = document.querySelector(SELECTORS.region.selectBlock);
849
        registerEventListeners(root, page);
850
        namespace = "block_myoverview_" + root.attr('id') + "_" + Math.random();
851
        root.attr('data-init', true);
852
    }
853
 
854
    initializePagedContent(root, standardFunctionalityCurry());
855
};
856
 
857
/**
858
 * Reset the courses views to their original
859
 * state on first page load.courseOffset
860
 *
861
 * This is called when configuration has changed for the event lists
862
 * to cause them to reload their data.
863
 *
864
 * @param {Object} root The root element for the timeline view.
865
 */
866
export const reset = root => {
867
    if (loadedPages.length > 0) {
868
        const filters = getFilterValues(root);
869
        // If the display mode is changed to 'summary' but the summary display has not been loaded yet,
870
        // we need to re-fetch the courses to include the course summary text.
871
        if (filters.display === 'summary' && !summaryDisplayLoaded) {
872
            const page = document.querySelector(SELECTORS.region.selectBlock);
873
            const input = page.querySelector(SELECTORS.region.searchInput);
874
            if (input.value !== '') {
875
                initializePagedContent(root, searchFunctionalityCurry(), input.value.trim());
876
            } else {
877
                initializePagedContent(root, standardFunctionalityCurry());
878
            }
879
        } else {
880
            loadedPages.forEach((courseList, index) => {
881
                let pagedContentPage = getPagedContentContainer(root, index);
882
                renderCourses(root, courseList).then((html, js) => {
883
                    return Templates.replaceNodeContents(pagedContentPage, html, js);
884
                }).catch(Notification.exception);
885
            });
886
        }
887
    } else {
888
        init(root);
889
    }
890
};