Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | 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
 * A type of dialogue used as for choosing options.
18
 *
19
 * @module     core_course/local/activitychooser/dialogue
20
 * @copyright  2019 Mihail Geshoski <mihail@moodle.com>
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 */
23
 
1441 ariadna 24
import Carousel from 'theme_boost/bootstrap/carousel';
1 efrain 25
import * as ModalEvents from 'core/modal_events';
26
import selectors from 'core_course/local/activitychooser/selectors';
27
import * as Templates from 'core/templates';
28
import {end, arrowLeft, arrowRight, home, enter, space} from 'core/key_codes';
29
import {addIconToContainer} from 'core/loadingicon';
30
import * as Repository from 'core_course/local/activitychooser/repository';
31
import Notification from 'core/notification';
32
import {debounce} from 'core/utils';
1441 ariadna 33
import {getFirst} from 'core/normalise';
1 efrain 34
const getPlugin = pluginName => import(pluginName);
35
 
36
/**
37
 * Given an event from the main module 'page' navigate to it's help section via a carousel.
38
 *
39
 * @method showModuleHelp
1441 ariadna 40
 * @param {Element} carousel Our initialized carousel to manipulate
1 efrain 41
 * @param {Object} moduleData Data of the module to carousel to
42
 * @param {jQuery} modal We need to figure out if the current modal has a footer.
43
 */
44
const showModuleHelp = (carousel, moduleData, modal = null) => {
45
    // If we have a real footer then we need to change temporarily.
46
    if (modal !== null && moduleData.showFooter === true) {
47
        modal.setFooter(Templates.render('core_course/local/activitychooser/footer_partial', moduleData));
48
    }
1441 ariadna 49
    const help = carousel.querySelector(selectors.regions.help);
1 efrain 50
    help.innerHTML = '';
51
    help.classList.add('m-auto');
52
 
53
    // Add a spinner.
54
    const spinnerPromise = addIconToContainer(help);
55
 
56
    // Used later...
57
    let transitionPromiseResolver = null;
58
    const transitionPromise = new Promise(resolve => {
59
        transitionPromiseResolver = resolve;
60
    });
61
 
62
    // Build up the html & js ready to place into the help section.
63
    const contentPromise = Templates.renderForPromise('core_course/local/activitychooser/help', moduleData);
64
 
65
    // Wait for the content to be ready, and for the transition to be complet.
66
    Promise.all([contentPromise, spinnerPromise, transitionPromise])
67
        .then(([{html, js}]) => Templates.replaceNodeContents(help, html, js))
68
        .then(() => {
69
            help.querySelector(selectors.regions.chooserSummary.header).focus();
70
            return help;
71
        })
72
        .catch(Notification.exception);
73
 
74
    // Move to the next slide, and resolve the transition promise when it's done.
1441 ariadna 75
    carousel.addEventListener('slid.bs.carousel', () => {
1 efrain 76
        transitionPromiseResolver();
1441 ariadna 77
    }, {once: true});
1 efrain 78
    // Trigger the transition between 'pages'.
1441 ariadna 79
    Carousel.getInstance(carousel).next();
1 efrain 80
};
81
 
82
/**
83
 * Given a user wants to change the favourite state of a module we either add or remove the status.
84
 * We also propergate this change across our map of modals.
85
 *
86
 * @method manageFavouriteState
87
 * @param {HTMLElement} modalBody The DOM node of the modal to manipulate
88
 * @param {HTMLElement} caller
89
 * @param {Function} partialFavourite Partially applied function we need to manage favourite status
90
 */
91
const manageFavouriteState = async(modalBody, caller, partialFavourite) => {
92
    const isFavourite = caller.dataset.favourited;
93
    const id = caller.dataset.id;
94
    const name = caller.dataset.name;
95
    const internal = caller.dataset.internal;
96
    // Switch on fave or not.
97
    if (isFavourite === 'true') {
98
        await Repository.unfavouriteModule(name, id);
99
 
100
        partialFavourite(internal, false, modalBody);
101
    } else {
102
        await Repository.favouriteModule(name, id);
103
 
104
        partialFavourite(internal, true, modalBody);
105
    }
106
 
107
};
108
 
109
/**
110
 * Register chooser related event listeners.
111
 *
112
 * @method registerListenerEvents
113
 * @param {Promise} modal Our modal that we are working with
114
 * @param {Map} mappedModules A map of all of the modules we are working with with K: mod_name V: {Object}
115
 * @param {Function} partialFavourite Partially applied function we need to manage favourite status
116
 * @param {Object} footerData Our base footer object.
117
 */
118
const registerListenerEvents = (modal, mappedModules, partialFavourite, footerData) => {
1441 ariadna 119
    const modalBody = getFirst(modal.getBody());
1 efrain 120
    const bodyClickListener = async(e) => {
121
        if (e.target.closest(selectors.actions.optionActions.showSummary)) {
1441 ariadna 122
            const carousel = modalBody.querySelector(selectors.regions.carousel);
1 efrain 123
 
124
            const module = e.target.closest(selectors.regions.chooserOption.container);
125
            const moduleName = module.dataset.modname;
126
            const moduleData = mappedModules.get(moduleName);
127
            // We need to know if the overall modal has a footer so we know when to show a real / vs fake footer.
128
            moduleData.showFooter = modal.hasFooterContent();
129
            showModuleHelp(carousel, moduleData, modal);
130
        }
131
 
132
        if (e.target.closest(selectors.actions.optionActions.manageFavourite)) {
133
            const caller = e.target.closest(selectors.actions.optionActions.manageFavourite);
1441 ariadna 134
            await manageFavouriteState(modalBody, caller, partialFavourite);
135
            const activeSectionId = modalBody.querySelector(selectors.elements.activetab).getAttribute("href");
136
            const sectionChooserOptions = modalBody
1 efrain 137
                .querySelector(selectors.regions.getSectionChooserOptions(activeSectionId));
138
            const firstChooserOption = sectionChooserOptions
139
                .querySelector(selectors.regions.chooserOption.container);
140
            toggleFocusableChooserOption(firstChooserOption, true);
1441 ariadna 141
            initChooserOptionsKeyboardNavigation(modalBody, mappedModules, sectionChooserOptions, modal);
1 efrain 142
        }
143
 
144
        // From the help screen go back to the module overview.
145
        if (e.target.matches(selectors.actions.closeOption)) {
1441 ariadna 146
            const carousel = modalBody.querySelector(selectors.regions.carousel);
1 efrain 147
 
148
            // Trigger the transition between 'pages'.
1441 ariadna 149
            Carousel.getInstance(carousel).prev();
150
            carousel.addEventListener('slid.bs.carousel', () => {
151
                const allModules = modalBody.querySelector(selectors.regions.modules);
1 efrain 152
                const caller = allModules.querySelector(selectors.regions.getModuleSelector(e.target.dataset.modname));
153
                caller.focus();
154
            });
155
        }
156
 
157
        // The "clear search" button is triggered.
158
        if (e.target.closest(selectors.actions.clearSearch)) {
159
            // Clear the entered search query in the search bar and hide the search results container.
1441 ariadna 160
            const searchInput = modalBody.querySelector(selectors.actions.search);
1 efrain 161
            searchInput.value = "";
162
            searchInput.focus();
163
            toggleSearchResultsView(modal, mappedModules, searchInput.value);
164
        }
165
    };
166
 
167
    // We essentially have two types of footer.
168
    // A fake one that is handled within the template for chooser_help and then all of the stuff for
169
    // modal.footer. We need to ensure we know exactly what type of footer we are using so we know what we
170
    // need to manage. The below code handles a real footer going to a mnet carousel item.
171
    const footerClickListener = async(e) => {
172
        if (footerData.footer === true) {
173
            const footerjs = await getPlugin(footerData.customfooterjs);
174
            await footerjs.footerClickListener(e, footerData, modal);
175
        }
176
    };
177
 
178
    modal.getBodyPromise()
179
 
180
    // The return value of getBodyPromise is a jquery object containing the body NodeElement.
181
    .then(body => body[0])
182
 
183
    // Set up the carousel.
184
    .then(body => {
1441 ariadna 185
        const carousel = document.querySelector(selectors.regions.carousel);
186
        new Carousel(carousel, {
1 efrain 187
                interval: false,
188
                pause: true,
189
                keyboard: false
1441 ariadna 190
        });
1 efrain 191
 
192
        return body;
193
    })
194
 
195
    // Add the listener for clicks on the body.
196
    .then(body => {
197
        body.addEventListener('click', bodyClickListener);
198
        return body;
199
    })
200
 
201
    // Add a listener for an input change in the activity chooser's search bar.
202
    .then(body => {
203
        const searchInput = body.querySelector(selectors.actions.search);
204
        // The search input is triggered.
205
        searchInput.addEventListener('input', debounce(() => {
206
            // Display the search results.
207
            toggleSearchResultsView(modal, mappedModules, searchInput.value);
208
        }, 300));
209
        return body;
210
    })
211
 
212
    // Register event listeners related to the keyboard navigation controls.
213
    .then(body => {
214
        // Get the active chooser options section.
215
        const activeSectionId = body.querySelector(selectors.elements.activetab).getAttribute("href");
216
        const sectionChooserOptions = body.querySelector(selectors.regions.getSectionChooserOptions(activeSectionId));
217
        const firstChooserOption = sectionChooserOptions.querySelector(selectors.regions.chooserOption.container);
218
 
219
        toggleFocusableChooserOption(firstChooserOption, true);
220
        initChooserOptionsKeyboardNavigation(body, mappedModules, sectionChooserOptions, modal);
221
 
222
        return body;
223
    })
1441 ariadna 224
    .catch(Notification.exception);
1 efrain 225
 
226
    modal.getFooterPromise()
227
 
228
    // The return value of getBodyPromise is a jquery object containing the body NodeElement.
229
    .then(footer => footer[0])
230
    // Add the listener for clicks on the footer.
231
    .then(footer => {
232
        footer.addEventListener('click', footerClickListener);
233
        return footer;
234
    })
1441 ariadna 235
    .catch(Notification.exception);
1 efrain 236
};
237
 
238
/**
239
 * Initialise the keyboard navigation controls for the chooser options.
240
 *
241
 * @method initChooserOptionsKeyboardNavigation
242
 * @param {HTMLElement} body Our modal that we are working with
243
 * @param {Map} mappedModules A map of all of the modules we are working with with K: mod_name V: {Object}
244
 * @param {HTMLElement} chooserOptionsContainer The section that contains the chooser items
245
 * @param {Object} modal Our created modal for the section
246
 */
247
const initChooserOptionsKeyboardNavigation = (body, mappedModules, chooserOptionsContainer, modal = null) => {
248
    const chooserOptions = chooserOptionsContainer.querySelectorAll(selectors.regions.chooserOption.container);
249
 
250
    Array.from(chooserOptions).forEach((element) => {
251
        return element.addEventListener('keydown', (e) => {
252
 
253
            // Check for enter/ space triggers for showing the help.
254
            if (e.keyCode === enter || e.keyCode === space) {
255
                if (e.target.matches(selectors.actions.optionActions.showSummary)) {
256
                    e.preventDefault();
257
                    const module = e.target.closest(selectors.regions.chooserOption.container);
258
                    const moduleName = module.dataset.modname;
259
                    const moduleData = mappedModules.get(moduleName);
1441 ariadna 260
                    const carousel = document.querySelector(selectors.regions.carousel);
261
                    new Carousel({
1 efrain 262
                        interval: false,
263
                        pause: true,
264
                        keyboard: false
265
                    });
266
 
267
                    // We need to know if the overall modal has a footer so we know when to show a real / vs fake footer.
268
                    moduleData.showFooter = modal.hasFooterContent();
269
                    showModuleHelp(carousel, moduleData, modal);
270
                }
271
            }
272
 
273
            // Next.
274
            if (e.keyCode === arrowRight) {
275
                e.preventDefault();
276
                const currentOption = e.target.closest(selectors.regions.chooserOption.container);
277
                const nextOption = currentOption.nextElementSibling;
278
                const firstOption = chooserOptionsContainer.firstElementChild;
279
                const toFocusOption = clickErrorHandler(nextOption, firstOption);
280
                focusChooserOption(toFocusOption, currentOption);
281
            }
282
 
283
            // Previous.
284
            if (e.keyCode === arrowLeft) {
285
                e.preventDefault();
286
                const currentOption = e.target.closest(selectors.regions.chooserOption.container);
287
                const previousOption = currentOption.previousElementSibling;
288
                const lastOption = chooserOptionsContainer.lastElementChild;
289
                const toFocusOption = clickErrorHandler(previousOption, lastOption);
290
                focusChooserOption(toFocusOption, currentOption);
291
            }
292
 
293
            if (e.keyCode === home) {
294
                e.preventDefault();
295
                const currentOption = e.target.closest(selectors.regions.chooserOption.container);
296
                const firstOption = chooserOptionsContainer.firstElementChild;
297
                focusChooserOption(firstOption, currentOption);
298
            }
299
 
300
            if (e.keyCode === end) {
301
                e.preventDefault();
302
                const currentOption = e.target.closest(selectors.regions.chooserOption.container);
303
                const lastOption = chooserOptionsContainer.lastElementChild;
304
                focusChooserOption(lastOption, currentOption);
305
            }
306
        });
307
    });
308
};
309
 
310
/**
311
 * Focus on a chooser option element and remove the previous chooser element from the focus order
312
 *
313
 * @method focusChooserOption
314
 * @param {HTMLElement} currentChooserOption The current chooser option element that we want to focus
315
 * @param {HTMLElement|null} previousChooserOption The previous focused option element
316
 */
317
const focusChooserOption = (currentChooserOption, previousChooserOption = null) => {
318
    if (previousChooserOption !== null) {
319
        toggleFocusableChooserOption(previousChooserOption, false);
320
    }
321
 
322
    toggleFocusableChooserOption(currentChooserOption, true);
323
    currentChooserOption.focus();
324
};
325
 
326
/**
327
 * Add or remove a chooser option from the focus order.
328
 *
329
 * @method toggleFocusableChooserOption
330
 * @param {HTMLElement} chooserOption The chooser option element which should be added or removed from the focus order
331
 * @param {Boolean} isFocusable Whether the chooser element is focusable or not
332
 */
333
const toggleFocusableChooserOption = (chooserOption, isFocusable) => {
334
    const chooserOptionLink = chooserOption.querySelector(selectors.actions.addChooser);
335
    const chooserOptionHelp = chooserOption.querySelector(selectors.actions.optionActions.showSummary);
336
    const chooserOptionFavourite = chooserOption.querySelector(selectors.actions.optionActions.manageFavourite);
337
 
338
    if (isFocusable) {
339
        // Set tabindex to 0 to add current chooser option element to the focus order.
340
        chooserOption.tabIndex = 0;
341
        chooserOptionLink.tabIndex = 0;
342
        chooserOptionHelp.tabIndex = 0;
343
        chooserOptionFavourite.tabIndex = 0;
344
    } else {
345
        // Set tabindex to -1 to remove the previous chooser option element from the focus order.
346
        chooserOption.tabIndex = -1;
347
        chooserOptionLink.tabIndex = -1;
348
        chooserOptionHelp.tabIndex = -1;
349
        chooserOptionFavourite.tabIndex = -1;
350
    }
351
};
352
 
353
/**
354
 * Small error handling function to make sure the navigated to object exists
355
 *
356
 * @method clickErrorHandler
357
 * @param {HTMLElement} item What we want to check exists
358
 * @param {HTMLElement} fallback If we dont match anything fallback the focus
359
 * @return {HTMLElement}
360
 */
361
const clickErrorHandler = (item, fallback) => {
362
    if (item !== null) {
363
        return item;
364
    } else {
365
        return fallback;
366
    }
367
};
368
 
369
/**
370
 * Render the search results in a defined container
371
 *
372
 * @method renderSearchResults
373
 * @param {HTMLElement} searchResultsContainer The container where the data should be rendered
374
 * @param {Object} searchResultsData Data containing the module items that satisfy the search criteria
375
 */
376
const renderSearchResults = async(searchResultsContainer, searchResultsData) => {
377
    const templateData = {
378
        'searchresultsnumber': searchResultsData.length,
379
        'searchresults': searchResultsData
380
    };
381
    // Build up the html & js ready to place into the help section.
382
    const {html, js} = await Templates.renderForPromise('core_course/local/activitychooser/search_results', templateData);
383
    await Templates.replaceNodeContents(searchResultsContainer, html, js);
384
};
385
 
386
/**
387
 * Toggle (display/hide) the search results depending on the value of the search query
388
 *
389
 * @method toggleSearchResultsView
390
 * @param {Object} modal Our created modal for the section
391
 * @param {Map} mappedModules A map of all of the modules we are working with with K: mod_name V: {Object}
392
 * @param {String} searchQuery The search query
393
 */
394
const toggleSearchResultsView = async(modal, mappedModules, searchQuery) => {
395
    const modalBody = modal.getBody()[0];
396
    const searchResultsContainer = modalBody.querySelector(selectors.regions.searchResults);
397
    const chooserContainer = modalBody.querySelector(selectors.regions.chooser);
398
    const clearSearchButton = modalBody.querySelector(selectors.actions.clearSearch);
399
 
400
    if (searchQuery.length > 0) { // Search query is present.
401
        const searchResultsData = searchModules(mappedModules, searchQuery);
402
        await renderSearchResults(searchResultsContainer, searchResultsData);
403
        const searchResultItemsContainer = searchResultsContainer.querySelector(selectors.regions.searchResultItems);
404
        const firstSearchResultItem = searchResultItemsContainer.querySelector(selectors.regions.chooserOption.container);
405
        if (firstSearchResultItem) {
406
            // Set the first result item to be focusable.
407
            toggleFocusableChooserOption(firstSearchResultItem, true);
408
            // Register keyboard events on the created search result items.
409
            initChooserOptionsKeyboardNavigation(modalBody, mappedModules, searchResultItemsContainer, modal);
410
        }
411
        // Display the "clear" search button in the activity chooser search bar.
412
        clearSearchButton.classList.remove('d-none');
413
        // Hide the default chooser options container.
414
        chooserContainer.setAttribute('hidden', 'hidden');
415
        // Display the search results container.
416
        searchResultsContainer.removeAttribute('hidden');
417
    } else { // Search query is not present.
418
        // Hide the "clear" search button in the activity chooser search bar.
419
        clearSearchButton.classList.add('d-none');
420
        // Hide the search results container.
421
        searchResultsContainer.setAttribute('hidden', 'hidden');
422
        // Display the default chooser options container.
423
        chooserContainer.removeAttribute('hidden');
424
    }
425
};
426
 
427
/**
428
 * Return the list of modules which have a name or description that matches the given search term.
429
 *
430
 * @method searchModules
431
 * @param {Array} modules List of available modules
432
 * @param {String} searchTerm The search term to match
433
 * @return {Array}
434
 */
435
const searchModules = (modules, searchTerm) => {
436
    if (searchTerm === '') {
437
        return modules;
438
    }
439
    searchTerm = searchTerm.toLowerCase();
440
    const searchResults = [];
441
    modules.forEach((activity) => {
442
        const activityName = activity.title.toLowerCase();
443
        const activityDesc = activity.help.toLowerCase();
444
        if (activityName.includes(searchTerm) || activityDesc.includes(searchTerm)) {
445
            searchResults.push(activity);
446
        }
447
    });
448
 
449
    return searchResults;
450
};
451
 
452
/**
453
 * Set up our tabindex information across the chooser.
454
 *
455
 * @method setupKeyboardAccessibility
456
 * @param {Promise} modal Our created modal for the section
457
 * @param {Map} mappedModules A map of all of the built module information
458
 */
459
const setupKeyboardAccessibility = (modal, mappedModules) => {
460
    modal.getModal()[0].tabIndex = -1;
461
 
462
    modal.getBodyPromise().then(body => {
1441 ariadna 463
        document.querySelectorAll(selectors.elements.tab).forEach((tab) => {
464
            tab.addEventListener('shown.bs.tab', (e) => {
465
                const activeSectionId = e.target.getAttribute("href");
466
                const activeSectionChooserOptions = body[0]
467
                    .querySelector(selectors.regions.getSectionChooserOptions(activeSectionId));
468
                const firstChooserOption = activeSectionChooserOptions
469
                    .querySelector(selectors.regions.chooserOption.container);
470
                const prevActiveSectionId = e.relatedTarget.getAttribute("href");
471
                const prevActiveSectionChooserOptions = body[0]
472
                    .querySelector(selectors.regions.getSectionChooserOptions(prevActiveSectionId));
1 efrain 473
 
1441 ariadna 474
                // Disable the focus of every chooser option in the previous active section.
475
                disableFocusAllChooserOptions(prevActiveSectionChooserOptions);
476
                // Enable the focus of the first chooser option in the current active section.
477
                toggleFocusableChooserOption(firstChooserOption, true);
478
                initChooserOptionsKeyboardNavigation(body[0], mappedModules, activeSectionChooserOptions, modal);
479
            });
1 efrain 480
        });
481
        return;
482
    }).catch(Notification.exception);
483
};
484
 
485
/**
486
 * Disable the focus of all chooser options in a specific container (section).
487
 *
488
 * @method disableFocusAllChooserOptions
489
 * @param {HTMLElement} sectionChooserOptions The section that contains the chooser items
490
 */
491
const disableFocusAllChooserOptions = (sectionChooserOptions) => {
492
    const allChooserOptions = sectionChooserOptions.querySelectorAll(selectors.regions.chooserOption.container);
493
    allChooserOptions.forEach((chooserOption) => {
494
        toggleFocusableChooserOption(chooserOption, false);
495
    });
496
};
497
 
498
/**
499
 * Display the module chooser.
500
 *
501
 * @method displayChooser
502
 * @param {Promise} modalPromise Our created modal for the section
503
 * @param {Array} sectionModules An array of all of the built module information
504
 * @param {Function} partialFavourite Partially applied function we need to manage favourite status
505
 * @param {Object} footerData Our base footer object.
506
 */
507
export const displayChooser = (modalPromise, sectionModules, partialFavourite, footerData) => {
508
    // Make a map so we can quickly fetch a specific module's object for either rendering or searching.
509
    const mappedModules = new Map();
510
    sectionModules.forEach((module) => {
511
        mappedModules.set(module.componentname + '_' + module.link, module);
512
    });
513
 
514
    // Register event listeners.
515
    modalPromise.then(modal => {
516
        registerListenerEvents(modal, mappedModules, partialFavourite, footerData);
517
 
518
        // We want to focus on the first chooser option element as soon as the modal is opened.
519
        setupKeyboardAccessibility(modal, mappedModules);
520
 
521
        // We want to focus on the action select when the dialog is closed.
522
        modal.getRoot().on(ModalEvents.hidden, () => {
523
            modal.destroy();
524
        });
525
 
526
        return modal;
1441 ariadna 527
    }).catch(Notification.exception);
1 efrain 528
};