MDL-60621 core_course: Disable scrollable in the activity chooser modal
[moodle.git] / course / amd / src / activitychooser.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 modules in a course.
18 *
19 * @module core_course/activitychooser
20 * @package core_course
21 * @copyright 2020 Mathew May <mathew.solutions>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25import * as ChooserDialogue from 'core_course/local/activitychooser/dialogue';
26import * as Repository from 'core_course/local/activitychooser/repository';
27import selectors from 'core_course/local/activitychooser/selectors';
28import CustomEvents from 'core/custom_interaction_events';
29import * as Templates from 'core/templates';
30import * as ModalFactory from 'core/modal_factory';
31import {get_string as getString} from 'core/str';
32import Pending from 'core/pending';
33
e146a2ca
MM
34// Set up some JS module wide constants that can be added to in the future.
35
36// Tab config options.
37const ALLACTIVITIESRESOURCES = 0;
38const ONLYALL = 1;
39const ACTIVITIESRESOURCES = 2;
40
41// Module types.
42const ACTIVITY = 0;
43const RESOURCE = 1;
44
05b27f21
MM
45/**
46 * Set up the activity chooser.
47 *
48 * @method init
49 * @param {Number} courseId Course ID to use later on in fetchModules()
e146a2ca 50 * @param {Object} chooserConfig Any PHP config settings that we may need to reference
05b27f21 51 */
e146a2ca 52export const init = (courseId, chooserConfig) => {
05b27f21
MM
53 const pendingPromise = new Pending();
54
e146a2ca 55 registerListenerEvents(courseId, chooserConfig);
05b27f21
MM
56
57 pendingPromise.resolve();
58};
59
60/**
61 * Once a selection has been made make the modal & module information and pass it along
62 *
63 * @method registerListenerEvents
64 * @param {Number} courseId
e146a2ca 65 * @param {Object} chooserConfig Any PHP config settings that we may need to reference
05b27f21 66 */
e146a2ca 67const registerListenerEvents = (courseId, chooserConfig) => {
05b27f21
MM
68 const events = [
69 'click',
70 CustomEvents.events.activate,
71 CustomEvents.events.keyboardActivate
72 ];
73
74 const fetchModuleData = (() => {
75 let innerPromise = null;
76
77 return () => {
78 if (!innerPromise) {
79 innerPromise = new Promise((resolve) => {
80 resolve(Repository.activityModules(courseId));
81 });
82 }
83
84 return innerPromise;
85 };
86 })();
87
16d77f18
MM
88 const fetchFooterData = (() => {
89 let footerInnerPromise = null;
90
91 return (sectionId) => {
92 if (!footerInnerPromise) {
93 footerInnerPromise = new Promise((resolve) => {
94 resolve(Repository.fetchFooterData(courseId, sectionId));
95 });
96 }
97
98 return footerInnerPromise;
99 };
100 })();
101
05b27f21
MM
102 CustomEvents.define(document, events);
103
104 // Display module chooser event listeners.
105 events.forEach((event) => {
106 document.addEventListener(event, async(e) => {
107 if (e.target.closest(selectors.elements.sectionmodchooser)) {
e74bcf19 108 let caller;
edf52a0e
MM
109 // We need to know who called this.
110 // Standard courses use the ID in the main section info.
111 const sectionDiv = e.target.closest(selectors.elements.section);
112 // Front page courses need some special handling.
113 const button = e.target.closest(selectors.elements.sectionmodchooser);
e74bcf19 114
edf52a0e 115 // If we don't have a section ID use the fallback ID.
e74bcf19
MM
116 // We always want the sectionDiv caller first as it keeps track of section ID's after DnD changes.
117 // The button attribute is always just a fallback for us as the section div is not always available.
118 // A YUI change could be done maybe to only update the button attribute but we are going for minimal change here.
119 if (sectionDiv !== null && sectionDiv.hasAttribute('data-sectionid')) {
120 // We check for attributes just in case of outdated contrib course formats.
121 caller = sectionDiv;
122 } else {
123 caller = button;
124 }
f2d033a2
MM
125
126 // We want to show the modal instantly but loading whilst waiting for our data.
127 let bodyPromiseResolver;
128 const bodyPromise = new Promise(resolve => {
129 bodyPromiseResolver = resolve;
130 });
131
16d77f18
MM
132 const footerData = await fetchFooterData(caller.dataset.sectionid);
133 const sectionModal = buildModal(bodyPromise, footerData);
f2d033a2
MM
134
135 // Now we have a modal we should start fetching data.
136 const data = await fetchModuleData();
137
138 // Apply the section id to all the module instance links.
c8388ead 139 const builtModuleData = sectionIdMapper(data, caller.dataset.sectionid, caller.dataset.sectionreturnid);
05b27f21 140
f2d033a2
MM
141 ChooserDialogue.displayChooser(
142 sectionModal,
143 builtModuleData,
144 partiallyAppliedFavouriteManager(data, caller.dataset.sectionid),
16d77f18 145 footerData,
f2d033a2
MM
146 );
147
148 bodyPromiseResolver(await Templates.render(
149 'core_course/activitychooser',
e146a2ca 150 templateDataBuilder(builtModuleData, chooserConfig)
f2d033a2 151 ));
05b27f21
MM
152 }
153 });
154 });
155};
156
157/**
158 * Given the web service data and an ID we want to make a deep copy
159 * of the WS data then add on the section ID to the addoption URL
160 *
161 * @method sectionIdMapper
162 * @param {Object} webServiceData Our original data from the Web service call
f2d033a2 163 * @param {Number} id The ID of the section we need to append to the links
c8388ead 164 * @param {Number|null} sectionreturnid The ID of the section return we need to append to the links
05b27f21
MM
165 * @return {Array} [modules] with URL's built
166 */
c8388ead 167const sectionIdMapper = (webServiceData, id, sectionreturnid) => {
05b27f21
MM
168 // We need to take a fresh deep copy of the original data as an object is a reference type.
169 const newData = JSON.parse(JSON.stringify(webServiceData));
806e736a 170 newData.content_items.forEach((module) => {
c8388ead 171 module.link += '&section=' + id + '&sr=' + (sectionreturnid ?? 0);
05b27f21 172 });
806e736a 173 return newData.content_items;
05b27f21
MM
174};
175
05b27f21
MM
176/**
177 * Given an array of modules we want to figure out where & how to place them into our template object
178 *
179 * @method templateDataBuilder
180 * @param {Array} data our modules to manipulate into a Templatable object
e146a2ca 181 * @param {Object} chooserConfig Any PHP config settings that we may need to reference
05b27f21
MM
182 * @return {Object} Our built object ready to render out
183 */
e146a2ca
MM
184const templateDataBuilder = (data, chooserConfig) => {
185 // Setup of various bits and pieces we need to mutate before throwing it to the wolves.
186 let activities = [];
187 let resources = [];
188 let showAll = true;
189 let showActivities = false;
190 let showResources = false;
191
192 // Tab mode can be the following [All, Resources & Activities, All & Activities & Resources].
193 const tabMode = parseInt(chooserConfig.tabmode);
194
c58c23d6 195 // Filter the incoming data to find favourite & recommended modules.
6e1a4477 196 const favourites = data.filter(mod => mod.favourite === true);
e04b4be6 197 const recommended = data.filter(mod => mod.recommended === true);
c58c23d6 198
e146a2ca
MM
199 // Both of these modes need Activity & Resource tabs.
200 if ((tabMode === ALLACTIVITIESRESOURCES || tabMode === ACTIVITIESRESOURCES) && tabMode !== ONLYALL) {
201 // Filter the incoming data to find activities then resources.
202 activities = data.filter(mod => mod.archetype === ACTIVITY);
203 resources = data.filter(mod => mod.archetype === RESOURCE);
204 showActivities = true;
205 showResources = true;
c58c23d6 206
e146a2ca
MM
207 // We want all of the previous information but no 'All' tab.
208 if (tabMode === ACTIVITIESRESOURCES) {
209 showAll = false;
210 }
211 }
212
213 // Given the results of the above filters lets figure out what tab to set active.
c58c23d6
MM
214 // We have some favourites.
215 const favouritesFirst = !!favourites.length;
e146a2ca
MM
216 // We are in tabMode 2 without any favourites.
217 const activitiesFirst = showAll === false && favouritesFirst === false;
c58c23d6 218 // We have nothing fallback to show all modules.
e146a2ca 219 const fallback = showAll === true && favouritesFirst === false;
c58c23d6 220
05b27f21
MM
221 return {
222 'default': data,
e146a2ca
MM
223 showAll: showAll,
224 activities: activities,
225 showActivities: showActivities,
226 activitiesFirst: activitiesFirst,
227 resources: resources,
228 showResources: showResources,
c58c23d6
MM
229 favourites: favourites,
230 recommended: recommended,
231 favouritesFirst: favouritesFirst,
c58c23d6 232 fallback: fallback,
05b27f21
MM
233 };
234};
235
236/**
4883aabf 237 * Given an object we want to build a modal ready to show
05b27f21
MM
238 *
239 * @method buildModal
f2d033a2 240 * @param {Promise} bodyPromise
16d77f18 241 * @param {String|Boolean} footer Either a footer to add or nothing
f2d033a2 242 * @return {Object} The modal ready to display immediately and render body in later.
05b27f21 243 */
16d77f18 244const buildModal = (bodyPromise, footer) => {
05b27f21
MM
245 return ModalFactory.create({
246 type: ModalFactory.types.DEFAULT,
247 title: getString('addresourceoractivity'),
f2d033a2 248 body: bodyPromise,
16d77f18 249 footer: footer.customfootertemplate,
05b27f21 250 large: true,
8ee9fbca 251 scrollable: false,
05b27f21
MM
252 templateContext: {
253 classes: 'modchooser'
254 }
f2d033a2
MM
255 })
256 .then(modal => {
257 modal.show();
258 return modal;
05b27f21
MM
259 });
260};
6e1a4477
MM
261
262/**
263 * A small helper function to handle the case where there are no more favourites
264 * and we need to mess a bit with the available tabs in the chooser
265 *
266 * @method nullFavouriteDomManager
267 * @param {HTMLElement} favouriteTabNav Dom node of the favourite tab nav
268 * @param {HTMLElement} modalBody Our current modals' body
269 */
270const nullFavouriteDomManager = (favouriteTabNav, modalBody) => {
9f1bfca2 271 favouriteTabNav.tabIndex = -1;
6e1a4477
MM
272 favouriteTabNav.classList.add('d-none');
273 // Need to set active to an available tab.
274 if (favouriteTabNav.classList.contains('active')) {
275 favouriteTabNav.classList.remove('active');
9f1bfca2 276 favouriteTabNav.setAttribute('aria-selected', 'false');
6e1a4477
MM
277 const favouriteTab = modalBody.querySelector(selectors.regions.favouriteTab);
278 favouriteTab.classList.remove('active');
6e1a4477 279 const defaultTabNav = modalBody.querySelector(selectors.regions.defaultTabNav);
e146a2ca
MM
280 const activitiesTabNav = modalBody.querySelector(selectors.regions.activityTabNav);
281 if (defaultTabNav.classList.contains('d-none') === false) {
6e1a4477 282 defaultTabNav.classList.add('active');
9f1bfca2
MG
283 defaultTabNav.setAttribute('aria-selected', 'true');
284 defaultTabNav.tabIndex = 0;
285 defaultTabNav.focus();
6e1a4477
MM
286 const defaultTab = modalBody.querySelector(selectors.regions.defaultTab);
287 defaultTab.classList.add('active');
e146a2ca
MM
288 } else {
289 activitiesTabNav.classList.add('active');
290 activitiesTabNav.setAttribute('aria-selected', 'true');
291 activitiesTabNav.tabIndex = 0;
292 activitiesTabNav.focus();
293 const activitiesTab = modalBody.querySelector(selectors.regions.activityTab);
294 activitiesTab.classList.add('active');
6e1a4477
MM
295 }
296
297 }
298};
299
300/**
301 * Export a curried function where the builtModules has been applied.
302 * We have our array of modules so we can rerender the favourites area and have all of the items sorted.
303 *
304 * @method partiallyAppliedFavouriteManager
305 * @param {Array} moduleData This is our raw WS data that we need to manipulate
306 * @param {Number} sectionId We need this to add the sectionID to the URL's in the faves area after rerender
307 * @return {Function} partially applied function so we can manipulate DOM nodes easily & update our internal array
308 */
309const partiallyAppliedFavouriteManager = (moduleData, sectionId) => {
310 /**
311 * Curried function that is being returned.
312 *
313 * @param {String} internal Internal name of the module to manage
314 * @param {Boolean} favourite Is the caller adding a favourite or removing one?
315 * @param {HTMLElement} modalBody What we need to update whilst we are here
316 */
317 return async(internal, favourite, modalBody) => {
318 const favouriteArea = modalBody.querySelector(selectors.render.favourites);
319
320 // eslint-disable-next-line max-len
321 const favouriteButtons = modalBody.querySelectorAll(`[data-internal="${internal}"] ${selectors.actions.optionActions.manageFavourite}`);
322 const favouriteTabNav = modalBody.querySelector(selectors.regions.favouriteTabNav);
323 const result = moduleData.content_items.find(({name}) => name === internal);
324 const newFaves = {};
325 if (result) {
326 if (favourite) {
327 result.favourite = true;
328
f2d033a2 329 // eslint-disable-next-line camelcase
6e1a4477
MM
330 newFaves.content_items = moduleData.content_items.filter(mod => mod.favourite === true);
331
332 const builtFaves = sectionIdMapper(newFaves, sectionId);
333
d2695ab2
MM
334 const {html, js} = await Templates.renderForPromise('core_course/local/activitychooser/favourites',
335 {favourites: builtFaves});
6e1a4477
MM
336
337 await Templates.replaceNodeContents(favouriteArea, html, js);
338
339 Array.from(favouriteButtons).forEach((element) => {
340 element.classList.remove('text-muted');
341 element.classList.add('text-primary');
342 element.dataset.favourited = 'true';
343 element.setAttribute('aria-pressed', true);
344 element.firstElementChild.classList.remove('fa-star-o');
345 element.firstElementChild.classList.add('fa-star');
346 });
347
348 favouriteTabNav.classList.remove('d-none');
349 } else {
350 result.favourite = false;
351
352 const nodeToRemove = favouriteArea.querySelector(`[data-internal="${internal}"]`);
353
354 nodeToRemove.parentNode.removeChild(nodeToRemove);
355
356 Array.from(favouriteButtons).forEach((element) => {
357 element.classList.add('text-muted');
358 element.classList.remove('text-primary');
359 element.dataset.favourited = 'false';
360 element.setAttribute('aria-pressed', false);
361 element.firstElementChild.classList.remove('fa-star');
362 element.firstElementChild.classList.add('fa-star-o');
363 });
364 const newFaves = moduleData.content_items.filter(mod => mod.favourite === true);
365
366 if (newFaves.length === 0) {
367 nullFavouriteDomManager(favouriteTabNav, modalBody);
368 }
369 }
370 }
371 };
372};