MDL-67883 core: Make core ready for MoodleNet.
[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.
6e1a4477 139 const builtModuleData = sectionIdMapper(data, caller.dataset.sectionid);
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
05b27f21
MM
164 * @return {Array} [modules] with URL's built
165 */
166const sectionIdMapper = (webServiceData, id) => {
167 // We need to take a fresh deep copy of the original data as an object is a reference type.
168 const newData = JSON.parse(JSON.stringify(webServiceData));
806e736a
JD
169 newData.content_items.forEach((module) => {
170 module.link += '&section=' + id;
05b27f21 171 });
806e736a 172 return newData.content_items;
05b27f21
MM
173};
174
05b27f21
MM
175/**
176 * Given an array of modules we want to figure out where & how to place them into our template object
177 *
178 * @method templateDataBuilder
179 * @param {Array} data our modules to manipulate into a Templatable object
e146a2ca 180 * @param {Object} chooserConfig Any PHP config settings that we may need to reference
05b27f21
MM
181 * @return {Object} Our built object ready to render out
182 */
e146a2ca
MM
183const templateDataBuilder = (data, chooserConfig) => {
184 // Setup of various bits and pieces we need to mutate before throwing it to the wolves.
185 let activities = [];
186 let resources = [];
187 let showAll = true;
188 let showActivities = false;
189 let showResources = false;
190
191 // Tab mode can be the following [All, Resources & Activities, All & Activities & Resources].
192 const tabMode = parseInt(chooserConfig.tabmode);
193
c58c23d6 194 // Filter the incoming data to find favourite & recommended modules.
6e1a4477 195 const favourites = data.filter(mod => mod.favourite === true);
e04b4be6 196 const recommended = data.filter(mod => mod.recommended === true);
c58c23d6 197
e146a2ca
MM
198 // Both of these modes need Activity & Resource tabs.
199 if ((tabMode === ALLACTIVITIESRESOURCES || tabMode === ACTIVITIESRESOURCES) && tabMode !== ONLYALL) {
200 // Filter the incoming data to find activities then resources.
201 activities = data.filter(mod => mod.archetype === ACTIVITY);
202 resources = data.filter(mod => mod.archetype === RESOURCE);
203 showActivities = true;
204 showResources = true;
c58c23d6 205
e146a2ca
MM
206 // We want all of the previous information but no 'All' tab.
207 if (tabMode === ACTIVITIESRESOURCES) {
208 showAll = false;
209 }
210 }
211
212 // Given the results of the above filters lets figure out what tab to set active.
c58c23d6
MM
213 // We have some favourites.
214 const favouritesFirst = !!favourites.length;
e146a2ca
MM
215 // We are in tabMode 2 without any favourites.
216 const activitiesFirst = showAll === false && favouritesFirst === false;
c58c23d6 217 // We have nothing fallback to show all modules.
e146a2ca 218 const fallback = showAll === true && favouritesFirst === false;
c58c23d6 219
05b27f21
MM
220 return {
221 'default': data,
e146a2ca
MM
222 showAll: showAll,
223 activities: activities,
224 showActivities: showActivities,
225 activitiesFirst: activitiesFirst,
226 resources: resources,
227 showResources: showResources,
c58c23d6
MM
228 favourites: favourites,
229 recommended: recommended,
230 favouritesFirst: favouritesFirst,
c58c23d6 231 fallback: fallback,
05b27f21
MM
232 };
233};
234
235/**
4883aabf 236 * Given an object we want to build a modal ready to show
05b27f21
MM
237 *
238 * @method buildModal
f2d033a2 239 * @param {Promise} bodyPromise
16d77f18 240 * @param {String|Boolean} footer Either a footer to add or nothing
f2d033a2 241 * @return {Object} The modal ready to display immediately and render body in later.
05b27f21 242 */
16d77f18 243const buildModal = (bodyPromise, footer) => {
05b27f21
MM
244 return ModalFactory.create({
245 type: ModalFactory.types.DEFAULT,
246 title: getString('addresourceoractivity'),
f2d033a2 247 body: bodyPromise,
16d77f18 248 footer: footer.customfootertemplate,
05b27f21
MM
249 large: true,
250 templateContext: {
251 classes: 'modchooser'
252 }
f2d033a2
MM
253 })
254 .then(modal => {
255 modal.show();
256 return modal;
05b27f21
MM
257 });
258};
6e1a4477
MM
259
260/**
261 * A small helper function to handle the case where there are no more favourites
262 * and we need to mess a bit with the available tabs in the chooser
263 *
264 * @method nullFavouriteDomManager
265 * @param {HTMLElement} favouriteTabNav Dom node of the favourite tab nav
266 * @param {HTMLElement} modalBody Our current modals' body
267 */
268const nullFavouriteDomManager = (favouriteTabNav, modalBody) => {
9f1bfca2 269 favouriteTabNav.tabIndex = -1;
6e1a4477
MM
270 favouriteTabNav.classList.add('d-none');
271 // Need to set active to an available tab.
272 if (favouriteTabNav.classList.contains('active')) {
273 favouriteTabNav.classList.remove('active');
9f1bfca2 274 favouriteTabNav.setAttribute('aria-selected', 'false');
6e1a4477
MM
275 const favouriteTab = modalBody.querySelector(selectors.regions.favouriteTab);
276 favouriteTab.classList.remove('active');
6e1a4477 277 const defaultTabNav = modalBody.querySelector(selectors.regions.defaultTabNav);
e146a2ca
MM
278 const activitiesTabNav = modalBody.querySelector(selectors.regions.activityTabNav);
279 if (defaultTabNav.classList.contains('d-none') === false) {
6e1a4477 280 defaultTabNav.classList.add('active');
9f1bfca2
MG
281 defaultTabNav.setAttribute('aria-selected', 'true');
282 defaultTabNav.tabIndex = 0;
283 defaultTabNav.focus();
6e1a4477
MM
284 const defaultTab = modalBody.querySelector(selectors.regions.defaultTab);
285 defaultTab.classList.add('active');
e146a2ca
MM
286 } else {
287 activitiesTabNav.classList.add('active');
288 activitiesTabNav.setAttribute('aria-selected', 'true');
289 activitiesTabNav.tabIndex = 0;
290 activitiesTabNav.focus();
291 const activitiesTab = modalBody.querySelector(selectors.regions.activityTab);
292 activitiesTab.classList.add('active');
6e1a4477
MM
293 }
294
295 }
296};
297
298/**
299 * Export a curried function where the builtModules has been applied.
300 * We have our array of modules so we can rerender the favourites area and have all of the items sorted.
301 *
302 * @method partiallyAppliedFavouriteManager
303 * @param {Array} moduleData This is our raw WS data that we need to manipulate
304 * @param {Number} sectionId We need this to add the sectionID to the URL's in the faves area after rerender
305 * @return {Function} partially applied function so we can manipulate DOM nodes easily & update our internal array
306 */
307const partiallyAppliedFavouriteManager = (moduleData, sectionId) => {
308 /**
309 * Curried function that is being returned.
310 *
311 * @param {String} internal Internal name of the module to manage
312 * @param {Boolean} favourite Is the caller adding a favourite or removing one?
313 * @param {HTMLElement} modalBody What we need to update whilst we are here
314 */
315 return async(internal, favourite, modalBody) => {
316 const favouriteArea = modalBody.querySelector(selectors.render.favourites);
317
318 // eslint-disable-next-line max-len
319 const favouriteButtons = modalBody.querySelectorAll(`[data-internal="${internal}"] ${selectors.actions.optionActions.manageFavourite}`);
320 const favouriteTabNav = modalBody.querySelector(selectors.regions.favouriteTabNav);
321 const result = moduleData.content_items.find(({name}) => name === internal);
322 const newFaves = {};
323 if (result) {
324 if (favourite) {
325 result.favourite = true;
326
f2d033a2 327 // eslint-disable-next-line camelcase
6e1a4477
MM
328 newFaves.content_items = moduleData.content_items.filter(mod => mod.favourite === true);
329
330 const builtFaves = sectionIdMapper(newFaves, sectionId);
331
d2695ab2
MM
332 const {html, js} = await Templates.renderForPromise('core_course/local/activitychooser/favourites',
333 {favourites: builtFaves});
6e1a4477
MM
334
335 await Templates.replaceNodeContents(favouriteArea, html, js);
336
337 Array.from(favouriteButtons).forEach((element) => {
338 element.classList.remove('text-muted');
339 element.classList.add('text-primary');
340 element.dataset.favourited = 'true';
341 element.setAttribute('aria-pressed', true);
342 element.firstElementChild.classList.remove('fa-star-o');
343 element.firstElementChild.classList.add('fa-star');
344 });
345
346 favouriteTabNav.classList.remove('d-none');
347 } else {
348 result.favourite = false;
349
350 const nodeToRemove = favouriteArea.querySelector(`[data-internal="${internal}"]`);
351
352 nodeToRemove.parentNode.removeChild(nodeToRemove);
353
354 Array.from(favouriteButtons).forEach((element) => {
355 element.classList.add('text-muted');
356 element.classList.remove('text-primary');
357 element.dataset.favourited = 'false';
358 element.setAttribute('aria-pressed', false);
359 element.firstElementChild.classList.remove('fa-star');
360 element.firstElementChild.classList.add('fa-star-o');
361 });
362 const newFaves = moduleData.content_items.filter(mod => mod.favourite === true);
363
364 if (newFaves.length === 0) {
365 nullFavouriteDomManager(favouriteTabNav, modalBody);
366 }
367 }
368 }
369 };
370};