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