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
 * Course state actions dispatcher.
18
 *
19
 * This module captures all data-dispatch links in the course content and dispatch the proper
20
 * state mutation, including any confirmation and modal required.
21
 *
22
 * @module     core_courseformat/local/content/actions
23
 * @class      core_courseformat/local/content/actions
24
 * @copyright  2021 Ferran Recio <ferran@moodle.com>
25
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26
 */
27
 
28
import {BaseComponent} from 'core/reactive';
29
import Modal from 'core/modal';
30
import ModalSaveCancel from 'core/modal_save_cancel';
31
import ModalDeleteCancel from 'core/modal_delete_cancel';
32
import ModalEvents from 'core/modal_events';
33
import Templates from 'core/templates';
34
import {prefetchStrings} from 'core/prefetch';
35
import {getString} from 'core/str';
36
import {getFirst} from 'core/normalise';
37
import {toggleBulkSelectionAction} from 'core_courseformat/local/content/actions/bulkselection';
38
import * as CourseEvents from 'core_course/events';
39
import Pending from 'core/pending';
40
import ContentTree from 'core_courseformat/local/courseeditor/contenttree';
41
// The jQuery module is only used for interacting with Boostrap 4. It can we removed when MDL-71979 is integrated.
42
import jQuery from 'jquery';
43
 
44
// Load global strings.
45
prefetchStrings('core', ['movecoursesection', 'movecoursemodule', 'confirm', 'delete']);
46
 
47
// Mutations are dispatched by the course content actions.
48
// Formats can use this module addActions static method to add custom actions.
49
// Direct mutations can be simple strings (mutation) name or functions.
50
const directMutations = {
51
    sectionHide: 'sectionHide',
52
    sectionShow: 'sectionShow',
53
    cmHide: 'cmHide',
54
    cmShow: 'cmShow',
55
    cmStealth: 'cmStealth',
56
    cmMoveRight: 'cmMoveRight',
57
    cmMoveLeft: 'cmMoveLeft',
58
    cmNoGroups: 'cmNoGroups',
59
    cmSeparateGroups: 'cmSeparateGroups',
60
    cmVisibleGroups: 'cmVisibleGroups',
61
};
62
 
63
export default class extends BaseComponent {
64
 
65
    /**
66
     * Constructor hook.
67
     */
68
    create() {
69
        // Optional component name for debugging.
70
        this.name = 'content_actions';
71
        // Default query selectors.
72
        this.selectors = {
73
            ACTIONLINK: `[data-action]`,
74
            // Move modal selectors.
75
            SECTIONLINK: `[data-for='section']`,
76
            CMLINK: `[data-for='cm']`,
77
            SECTIONNODE: `[data-for='sectionnode']`,
78
            MODALTOGGLER: `[data-toggle='collapse']`,
79
            ADDSECTION: `[data-action='addSection']`,
80
            CONTENTTREE: `#destination-selector`,
81
            ACTIONMENU: `.action-menu`,
82
            ACTIONMENUTOGGLER: `[data-toggle="dropdown"]`,
83
            // Availability modal selectors.
84
            OPTIONSRADIO: `[type='radio']`,
85
        };
86
        // Component css classes.
87
        this.classes = {
88
            DISABLED: `text-body`,
89
            ITALIC: `font-italic`,
90
        };
91
    }
92
 
93
    /**
94
     * Add extra actions to the module.
95
     *
96
     * @param {array} actions array of methods to execute
97
     */
98
    static addActions(actions) {
99
        for (const [action, mutationReference] of Object.entries(actions)) {
100
            if (typeof mutationReference !== 'function' && typeof mutationReference !== 'string') {
101
                throw new Error(`${action} action must be a mutation name or a function`);
102
            }
103
            directMutations[action] = mutationReference;
104
        }
105
    }
106
 
107
    /**
108
     * Initial state ready method.
109
     *
110
     * @param {Object} state the state data.
111
     *
112
     */
113
    stateReady(state) {
114
        // Delegate dispatch clicks.
115
        this.addEventListener(
116
            this.element,
117
            'click',
118
            this._dispatchClick
119
        );
120
        // Check section limit.
121
        this._checkSectionlist({state});
122
        // Add an Event listener to recalculate limits it if a section HTML is altered.
123
        this.addEventListener(
124
            this.element,
125
            CourseEvents.sectionRefreshed,
126
            () => this._checkSectionlist({state})
127
        );
128
    }
129
 
130
    /**
131
     * Return the component watchers.
132
     *
133
     * @returns {Array} of watchers
134
     */
135
    getWatchers() {
136
        return [
137
            // Check section limit.
138
            {watch: `course.sectionlist:updated`, handler: this._checkSectionlist},
139
        ];
140
    }
141
 
142
    _dispatchClick(event) {
143
        const target = event.target.closest(this.selectors.ACTIONLINK);
144
        if (!target) {
145
            return;
146
        }
147
        if (target.classList.contains(this.classes.DISABLED)) {
148
            event.preventDefault();
149
            return;
150
        }
151
 
152
        // Invoke proper method.
153
        const actionName = target.dataset.action;
154
        const methodName = this._actionMethodName(actionName);
155
 
156
        if (this[methodName] !== undefined) {
157
            this[methodName](target, event);
158
            return;
159
        }
160
 
161
        // Check direct mutations or mutations handlers.
162
        if (directMutations[actionName] !== undefined) {
163
            if (typeof directMutations[actionName] === 'function') {
164
                directMutations[actionName](target, event);
165
                return;
166
            }
167
            this._requestMutationAction(target, event, directMutations[actionName]);
168
            return;
169
        }
170
    }
171
 
172
    _actionMethodName(name) {
173
        const requestName = name.charAt(0).toUpperCase() + name.slice(1);
174
        return `_request${requestName}`;
175
    }
176
 
177
    /**
178
     * Check the section list and disable some options if needed.
179
     *
180
     * @param {Object} detail the update details.
181
     * @param {Object} detail.state the state object.
182
     */
183
    _checkSectionlist({state}) {
184
        // Disable "add section" actions if the course max sections has been exceeded.
185
        this._setAddSectionLocked(state.course.sectionlist.length > state.course.maxsections);
186
    }
187
 
188
    /**
189
     * Return the ids represented by this element.
190
     *
191
     * Depending on the dataset attributes the action could represent a single id
192
     * or a bulk actions with all the current selected ids.
193
     *
194
     * @param {HTMLElement} target
195
     * @returns {Number[]} array of Ids
196
     */
197
    _getTargetIds(target) {
198
        let ids = [];
199
        if (target?.dataset?.id) {
200
            ids.push(target.dataset.id);
201
        }
202
        const bulkType = target?.dataset?.bulk;
203
        if (!bulkType) {
204
            return ids;
205
        }
206
        const bulk = this.reactive.get('bulk');
207
        if (bulk.enabled && bulk.selectedType === bulkType) {
208
            ids = [...ids, ...bulk.selection];
209
        }
210
        return ids;
211
    }
212
 
213
    /**
214
     * Handle a move section request.
215
     *
216
     * @param {Element} target the dispatch action element
217
     * @param {Event} event the triggered event
218
     */
219
    async _requestMoveSection(target, event) {
220
        // Check we have an id.
221
        const sectionIds = this._getTargetIds(target);
222
        if (sectionIds.length == 0) {
223
            return;
224
        }
225
 
226
        event.preventDefault();
227
 
228
        const pendingModalReady = new Pending(`courseformat/actions:prepareMoveSectionModal`);
229
 
230
        // The section edit menu to refocus on end.
231
        const editTools = this._getClosestActionMenuToogler(target);
232
 
233
        // Collect section information from the state.
234
        const exporter = this.reactive.getExporter();
235
        const data = exporter.course(this.reactive.state);
236
        let titleText = null;
237
 
238
        // Add the target section id and title.
239
        let sectionInfo = null;
240
        if (sectionIds.length == 1) {
241
            sectionInfo = this.reactive.get('section', sectionIds[0]);
242
            data.sectionid = sectionInfo.id;
243
            data.sectiontitle = sectionInfo.title;
244
            data.information = await this.reactive.getFormatString('sectionmove_info', data.sectiontitle);
245
            titleText = this.reactive.getFormatString('sectionmove_title');
246
        } else {
247
            data.information = await this.reactive.getFormatString('sectionsmove_info', sectionIds.length);
248
            titleText = this.reactive.getFormatString('sectionsmove_title');
249
        }
250
 
251
 
252
        // Create the modal.
253
        // Build the modal parameters from the event data.
254
        const modal = await this._modalBodyRenderedPromise(Modal, {
255
            title: titleText,
256
            body: Templates.render('core_courseformat/local/content/movesection', data),
257
        });
258
 
259
        const modalBody = getFirst(modal.getBody());
260
 
261
        // Disable current selected section ids.
262
        sectionIds.forEach(sectionId => {
263
            const currentElement = modalBody.querySelector(`${this.selectors.SECTIONLINK}[data-id='${sectionId}']`);
264
            this._disableLink(currentElement);
265
        });
266
 
267
        // Setup keyboard navigation.
268
        new ContentTree(
269
            modalBody.querySelector(this.selectors.CONTENTTREE),
270
            {
271
                SECTION: this.selectors.SECTIONNODE,
272
                TOGGLER: this.selectors.MODALTOGGLER,
273
                COLLAPSE: this.selectors.MODALTOGGLER,
274
            },
275
            true
276
        );
277
 
278
        // Capture click.
279
        modalBody.addEventListener('click', (event) => {
280
            const target = event.target;
281
            if (!target.matches('a') || target.dataset.for != 'section' || target.dataset.id === undefined) {
282
                return;
283
            }
284
            if (target.getAttribute('aria-disabled')) {
285
                return;
286
            }
287
            event.preventDefault();
288
            this.reactive.dispatch('sectionMoveAfter', sectionIds, target.dataset.id);
289
            this._destroyModal(modal, editTools);
290
        });
291
 
292
        pendingModalReady.resolve();
293
    }
294
 
295
    /**
296
     * Handle a move cm request.
297
     *
298
     * @param {Element} target the dispatch action element
299
     * @param {Event} event the triggered event
300
     */
301
    async _requestMoveCm(target, event) {
302
        // Check we have an id.
303
        const cmIds = this._getTargetIds(target);
304
        if (cmIds.length == 0) {
305
            return;
306
        }
307
 
308
        event.preventDefault();
309
 
310
        const pendingModalReady = new Pending(`courseformat/actions:prepareMoveCmModal`);
311
 
312
        // The section edit menu to refocus on end.
313
        const editTools = this._getClosestActionMenuToogler(target);
314
 
315
        // Collect information from the state.
316
        const exporter = this.reactive.getExporter();
317
        const data = exporter.course(this.reactive.state);
318
 
319
        let titleText = null;
320
        if (cmIds.length == 1) {
321
            const cmInfo = this.reactive.get('cm', cmIds[0]);
322
            data.cmid = cmInfo.id;
323
            data.cmname = cmInfo.name;
324
            data.information = await this.reactive.getFormatString('cmmove_info', data.cmname);
325
            titleText = this.reactive.getFormatString('cmmove_title');
326
        } else {
327
            data.information = await this.reactive.getFormatString('cmsmove_info', cmIds.length);
328
            titleText = this.reactive.getFormatString('cmsmove_title');
329
        }
330
 
331
        // Create the modal.
332
        // Build the modal parameters from the event data.
333
        const modal = await this._modalBodyRenderedPromise(Modal, {
334
            title: titleText,
335
            body: Templates.render('core_courseformat/local/content/movecm', data),
336
        });
337
 
338
        const modalBody = getFirst(modal.getBody());
339
 
340
        // Disable current selected section ids.
341
        cmIds.forEach(cmId => {
342
            const currentElement = modalBody.querySelector(`${this.selectors.CMLINK}[data-id='${cmId}']`);
343
            this._disableLink(currentElement);
344
        });
345
 
346
        // Setup keyboard navigation.
347
        new ContentTree(
348
            modalBody.querySelector(this.selectors.CONTENTTREE),
349
            {
350
                SECTION: this.selectors.SECTIONNODE,
351
                TOGGLER: this.selectors.MODALTOGGLER,
352
                COLLAPSE: this.selectors.MODALTOGGLER,
353
                ENTER: this.selectors.SECTIONLINK,
354
            }
355
        );
356
 
357
        // Open the cm section node if possible (Bootstrap 4 uses jQuery to interact with collapsibles).
358
        // All jQuery in this code can be replaced when MDL-71979 is integrated.
359
        cmIds.forEach(cmId => {
360
            const currentElement = modalBody.querySelector(`${this.selectors.CMLINK}[data-id='${cmId}']`);
361
            const sectionnode = currentElement.closest(this.selectors.SECTIONNODE);
362
            const toggler = jQuery(sectionnode).find(this.selectors.MODALTOGGLER);
363
            let collapsibleId = toggler.data('target') ?? toggler.attr('href');
364
            if (collapsibleId) {
365
                // We cannot be sure we have # in the id element name.
366
                collapsibleId = collapsibleId.replace('#', '');
367
                const expandNode = modalBody.querySelector(`#${collapsibleId}`);
368
                jQuery(expandNode).collapse('show');
369
            }
370
        });
371
 
372
        modalBody.addEventListener('click', (event) => {
373
            const target = event.target;
374
            if (!target.matches('a') || target.dataset.for === undefined || target.dataset.id === undefined) {
375
                return;
376
            }
377
            if (target.getAttribute('aria-disabled')) {
378
                return;
379
            }
380
            event.preventDefault();
381
 
382
            let targetSectionId;
383
            let targetCmId;
384
            if (target.dataset.for == 'cm') {
385
                const dropData = exporter.cmDraggableData(this.reactive.state, target.dataset.id);
386
                targetSectionId = dropData.sectionid;
387
                targetCmId = dropData.nextcmid;
388
            } else {
389
                const section = this.reactive.get('section', target.dataset.id);
390
                targetSectionId = target.dataset.id;
391
                targetCmId = section?.cmlist[0];
392
            }
393
            this.reactive.dispatch('cmMove', cmIds, targetSectionId, targetCmId);
394
            this._destroyModal(modal, editTools);
395
        });
396
 
397
        pendingModalReady.resolve();
398
    }
399
 
400
    /**
401
     * Handle a create section request.
402
     *
403
     * @param {Element} target the dispatch action element
404
     * @param {Event} event the triggered event
405
     */
406
    async _requestAddSection(target, event) {
407
        event.preventDefault();
408
        this.reactive.dispatch('addSection', target.dataset.id ?? 0);
409
    }
410
 
411
    /**
412
     * Handle a delete section request.
413
     *
414
     * @param {Element} target the dispatch action element
415
     * @param {Event} event the triggered event
416
     */
417
    async _requestDeleteSection(target, event) {
418
        const sectionIds = this._getTargetIds(target);
419
        if (sectionIds.length == 0) {
420
            return;
421
        }
422
 
423
        event.preventDefault();
424
 
425
        // We don't need confirmation to delete empty sections.
426
        let needsConfirmation = sectionIds.some(sectionId => {
427
            const sectionInfo = this.reactive.get('section', sectionId);
428
            const cmList = sectionInfo.cmlist ?? [];
429
            return (cmList.length || sectionInfo.hassummary || sectionInfo.rawtitle);
430
        });
431
        if (!needsConfirmation) {
432
            this.reactive.dispatch('sectionDelete', sectionIds);
433
            return;
434
        }
435
 
436
        let bodyText = null;
437
        let titleText = null;
438
        if (sectionIds.length == 1) {
439
            titleText = this.reactive.getFormatString('sectiondelete_title');
440
            const sectionInfo = this.reactive.get('section', sectionIds[0]);
441
            bodyText = this.reactive.getFormatString('sectiondelete_info', {name: sectionInfo.title});
442
        } else {
443
            titleText = this.reactive.getFormatString('sectionsdelete_title');
444
            bodyText = this.reactive.getFormatString('sectionsdelete_info', {count: sectionIds.length});
445
        }
446
 
447
        const modal = await this._modalBodyRenderedPromise(ModalDeleteCancel, {
448
            title: titleText,
449
            body: bodyText,
450
        });
451
 
452
        modal.getRoot().on(
453
            ModalEvents.delete,
454
            e => {
455
                // Stop the default save button behaviour which is to close the modal.
456
                e.preventDefault();
457
                modal.destroy();
458
                this.reactive.dispatch('sectionDelete', sectionIds);
459
            }
460
        );
461
    }
462
 
463
    /**
464
     * Handle a toggle cm selection.
465
     *
466
     * @param {Element} target the dispatch action element
467
     * @param {Event} event the triggered event
468
     */
469
    async _requestToggleSelectionCm(target, event) {
470
        toggleBulkSelectionAction(this.reactive, target, event, 'cm');
471
    }
472
 
473
    /**
474
     * Handle a toggle section selection.
475
     *
476
     * @param {Element} target the dispatch action element
477
     * @param {Event} event the triggered event
478
     */
479
    async _requestToggleSelectionSection(target, event) {
480
        toggleBulkSelectionAction(this.reactive, target, event, 'section');
481
    }
482
 
483
    /**
484
     * Basic mutation action helper.
485
     *
486
     * @param {Element} target the dispatch action element
487
     * @param {Event} event the triggered event
488
     * @param {string} mutationName the mutation name
489
     */
490
    async _requestMutationAction(target, event, mutationName) {
491
        if (!target.dataset.id && target.dataset.for !== 'bulkaction') {
492
            return;
493
        }
494
        event.preventDefault();
495
        if (target.dataset.for === 'bulkaction') {
496
            // If the mutation is a bulk action we use the current selection.
497
            this.reactive.dispatch(mutationName, this.reactive.get('bulk').selection);
498
        } else {
499
            this.reactive.dispatch(mutationName, [target.dataset.id]);
500
        }
501
    }
502
 
503
    /**
504
     * Handle a course module duplicate request.
505
     *
506
     * @param {Element} target the dispatch action element
507
     * @param {Event} event the triggered event
508
     */
509
    async _requestCmDuplicate(target, event) {
510
        const cmIds = this._getTargetIds(target);
511
        if (cmIds.length == 0) {
512
            return;
513
        }
514
        const sectionId = target.dataset.sectionid ?? null;
515
        event.preventDefault();
516
        this.reactive.dispatch('cmDuplicate', cmIds, sectionId);
517
    }
518
 
519
    /**
520
     * Handle a delete cm request.
521
     *
522
     * @param {Element} target the dispatch action element
523
     * @param {Event} event the triggered event
524
     */
525
    async _requestCmDelete(target, event) {
526
        const cmIds = this._getTargetIds(target);
527
        if (cmIds.length == 0) {
528
            return;
529
        }
530
 
531
        event.preventDefault();
532
 
533
        let bodyText = null;
534
        let titleText = null;
535
        if (cmIds.length == 1) {
536
            const cmInfo = this.reactive.get('cm', cmIds[0]);
537
            titleText = getString('cmdelete_title', 'core_courseformat');
538
            bodyText = getString(
539
                'cmdelete_info',
540
                'core_courseformat',
541
                {
542
                    type: cmInfo.modname,
543
                    name: cmInfo.name,
544
                }
545
            );
546
        } else {
547
            titleText = getString('cmsdelete_title', 'core_courseformat');
548
            bodyText = getString(
549
                'cmsdelete_info',
550
                'core_courseformat',
551
                {count: cmIds.length}
552
            );
553
        }
554
 
555
        const modal = await this._modalBodyRenderedPromise(ModalDeleteCancel, {
556
            title: titleText,
557
            body: bodyText,
558
        });
559
 
560
        modal.getRoot().on(
561
            ModalEvents.delete,
562
            e => {
563
                // Stop the default save button behaviour which is to close the modal.
564
                e.preventDefault();
565
                modal.destroy();
566
                this.reactive.dispatch('cmDelete', cmIds);
567
            }
568
        );
569
    }
570
 
571
    /**
572
     * Handle a cm availability change request.
573
     *
574
     * @param {Element} target the dispatch action element
575
     */
576
    async _requestCmAvailability(target) {
577
        const cmIds = this._getTargetIds(target);
578
        if (cmIds.length == 0) {
579
            return;
580
        }
581
        // Show the availability modal to decide which action to trigger.
582
        const exporter = this.reactive.getExporter();
583
        const data = {
584
            allowstealth: exporter.canUseStealth(this.reactive.state, cmIds),
585
        };
586
        const modal = await this._modalBodyRenderedPromise(ModalSaveCancel, {
587
            title: getString('availability', 'core'),
588
            body: Templates.render('core_courseformat/local/content/cm/availabilitymodal', data),
589
            saveButtonText: getString('apply', 'core'),
590
        });
591
 
592
        this._setupMutationRadioButtonModal(modal, cmIds);
593
    }
594
 
595
    /**
596
     * Handle a section availability change request.
597
     *
598
     * @param {Element} target the dispatch action element
599
     */
600
    async _requestSectionAvailability(target) {
601
        const sectionIds = this._getTargetIds(target);
602
        if (sectionIds.length == 0) {
603
            return;
604
        }
605
        const title = (sectionIds.length == 1) ? 'sectionavailability_title' : 'sectionsavailability_title';
606
        // Show the availability modal to decide which action to trigger.
607
        const modal = await this._modalBodyRenderedPromise(ModalSaveCancel, {
608
            title: this.reactive.getFormatString(title),
609
            body: Templates.render('core_courseformat/local/content/section/availabilitymodal', []),
610
            saveButtonText: getString('apply', 'core'),
611
        });
612
 
613
        this._setupMutationRadioButtonModal(modal, sectionIds);
614
    }
615
 
616
    /**
617
     * Add events to a mutation selector radio buttons modal.
618
     * @param {Modal} modal
619
     * @param {Number[]} ids the section or cm ids to apply the mutation
620
     */
621
    _setupMutationRadioButtonModal(modal, ids) {
622
        // The save button is not enabled until the user selects an option.
623
        modal.setButtonDisabled('save', true);
624
 
625
        const submitFunction = (radio) => {
626
            const mutation = radio?.value;
627
            if (!mutation) {
628
                return false;
629
            }
630
            this.reactive.dispatch(mutation, ids);
631
            return true;
632
        };
633
 
634
        const modalBody = getFirst(modal.getBody());
635
        const radioOptions = modalBody.querySelectorAll(this.selectors.OPTIONSRADIO);
636
        radioOptions.forEach(radio => {
637
            radio.addEventListener('change', () => {
638
                modal.setButtonDisabled('save', false);
639
            });
640
            radio.parentNode.addEventListener('click', () => {
641
                radio.checked = true;
642
                modal.setButtonDisabled('save', false);
643
            });
644
            radio.parentNode.addEventListener('dblclick', dbClickEvent => {
645
                if (submitFunction(radio)) {
646
                    dbClickEvent.preventDefault();
647
                    modal.destroy();
648
                }
649
            });
650
        });
651
 
652
        modal.getRoot().on(
653
            ModalEvents.save,
654
            () => {
655
                const radio = modalBody.querySelector(`${this.selectors.OPTIONSRADIO}:checked`);
656
                submitFunction(radio);
657
            }
658
        );
659
    }
660
 
661
    /**
662
     * Disable all add sections actions.
663
     *
664
     * @param {boolean} locked the new locked value.
665
     */
666
    _setAddSectionLocked(locked) {
667
        const targets = this.getElements(this.selectors.ADDSECTION);
668
        targets.forEach(element => {
669
            element.classList.toggle(this.classes.DISABLED, locked);
670
            element.classList.toggle(this.classes.ITALIC, locked);
671
            this.setElementLocked(element, locked);
672
        });
673
    }
674
 
675
    /**
676
     * Replace an element with a copy with a different tag name.
677
     *
678
     * @param {Element} element the original element
679
     */
680
    _disableLink(element) {
681
        if (element) {
682
            element.style.pointerEvents = 'none';
683
            element.style.userSelect = 'none';
684
            element.classList.add(this.classes.DISABLED);
685
            element.classList.add(this.classes.ITALIC);
686
            element.setAttribute('aria-disabled', true);
687
            element.addEventListener('click', event => event.preventDefault());
688
        }
689
    }
690
 
691
    /**
692
     * Render a modal and return a body ready promise.
693
     *
694
     * @param {Modal} ModalClass the modal class
695
     * @param {object} modalParams the modal params
696
     * @return {Promise} the modal body ready promise
697
     */
698
    _modalBodyRenderedPromise(ModalClass, modalParams) {
699
        return new Promise((resolve, reject) => {
700
            ModalClass.create(modalParams).then((modal) => {
701
                modal.setRemoveOnClose(true);
702
                // Handle body loading event.
703
                modal.getRoot().on(ModalEvents.bodyRendered, () => {
704
                    resolve(modal);
705
                });
706
                // Configure some extra modal params.
707
                if (modalParams.saveButtonText !== undefined) {
708
                    modal.setSaveButtonText(modalParams.saveButtonText);
709
                }
710
                if (modalParams.deleteButtonText !== undefined) {
711
                    modal.setDeleteButtonText(modalParams.saveButtonText);
712
                }
713
                modal.show();
714
                return;
715
            }).catch(() => {
716
                reject(`Cannot load modal content`);
717
            });
718
        });
719
    }
720
 
721
    /**
722
     * Hide and later destroy a modal.
723
     *
724
     * Behat will fail if we remove the modal while some boostrap collapse is executing.
725
     *
726
     * @param {Modal} modal
727
     * @param {HTMLElement} element the dom element to focus on.
728
     */
729
    _destroyModal(modal, element) {
730
        modal.hide();
731
        const pendingDestroy = new Pending(`courseformat/actions:destroyModal`);
732
        if (element) {
733
            element.focus();
734
        }
735
        setTimeout(() =>{
736
            modal.destroy();
737
            pendingDestroy.resolve();
738
        }, 500);
739
    }
740
 
741
    /**
742
     * Get the closest actions menu toggler to an action element.
743
     *
744
     * @param {HTMLElement} element the action link element
745
     * @returns {HTMLElement|undefined}
746
     */
747
    _getClosestActionMenuToogler(element) {
748
        const actionMenu = element.closest(this.selectors.ACTIONMENU);
749
        if (!actionMenu) {
750
            return undefined;
751
        }
752
        return actionMenu.querySelector(this.selectors.ACTIONMENUTOGGLER);
753
    }
754
}