Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
913 ariadna 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 index main component.
18
 *
19
 * @module     theme_universe/courseindex/courseindex
20
 * @class     theme_universe/courseindex/courseindex
21
 * @copyright  2021 Ferran Recio <ferran@moodle.com>
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
import {BaseComponent} from 'core/reactive';
26
import {getCurrentCourseEditor} from 'core_courseformat/courseeditor';
27
import jQuery from 'jquery';
28
import ContentTree from 'theme_universe_child/courseeditor/contenttree';
29
 
30
export default class Component extends BaseComponent {
31
 
32
    /**
33
     * Constructor hook.
34
     */
35
    create() {
36
        // Optional component name for debugging.
37
        this.name = 'courseindex';
38
        // Default query selectors.
39
        this.selectors = {
40
            SECTION: `[data-for='section']`,
41
            SECTION_CMLIST: `[data-for='cmlist']`,
42
            CM: `[data-for='cm']`,
43
            TOGGLER: `[data-action="togglecourseindexsection"]`,
44
            COLLAPSE: `[data-toggle="collapse"]`,
45
            DRAWER: `.drawer`,
46
        };
47
        // Default classes to toggle on refresh.
48
        this.classes = {
49
            SECTIONHIDDEN: 'dimmed',
50
            CMHIDDEN: 'dimmed',
51
            SECTIONCURRENT: 'current',
52
            COLLAPSED: `collapsed`,
53
            SHOW: `show`,
54
        };
55
        // Arrays to keep cms and sections elements.
56
        this.sections = {};
57
        this.cms = {};
58
    }
59
 
60
    /**
61
     * Static method to create a component instance form the mustache template.
62
     *
63
     * @param {element|string} target the DOM main element or its ID
64
     * @param {object} selectors optional css selector overrides
65
     * @return {Component}
66
     */
67
    static init(target, selectors) {
68
        return new this({
69
            element: document.getElementById(target),
70
            reactive: getCurrentCourseEditor(),
71
            selectors,
72
        });
73
    }
74
 
75
    /**
76
     * Initial state ready method.
77
     *
78
     * @param {Object} state the state data
79
     */
80
    stateReady(state) {
81
        // Activate section togglers.
82
        this.addEventListener(this.element, 'click', this._sectionTogglers);
83
 
84
        // Get cms and sections elements.
85
        const sections = this.getElements(this.selectors.SECTION);
86
        sections.forEach((section) => {
87
            this.sections[section.dataset.id] = section;
88
        });
89
        const cms = this.getElements(this.selectors.CM);
90
        cms.forEach((cm) => {
91
            this.cms[cm.dataset.id] = cm;
92
        });
93
 
94
        this._expandPageCmSectionIfNecessary(state);
95
        this._refreshPageItem({element: state.course, state});
96
 
97
        // Configure Aria Tree.
98
        this.contentTree = new ContentTree(this.element, this.selectors, this.reactive.isEditing);
99
    }
100
 
101
    getWatchers() {
102
        return [
103
            {watch: `section.indexcollapsed:updated`, handler: this._refreshSectionCollapsed},
104
            {watch: `cm:created`, handler: this._createCm},
105
            {watch: `cm:deleted`, handler: this._deleteCm},
106
            {watch: `section:created`, handler: this._createSection},
107
            {watch: `section:deleted`, handler: this._deleteSection},
108
            {watch: `course.pageItem:created`, handler: this._refreshPageItem},
109
            {watch: `course.pageItem:updated`, handler: this._refreshPageItem},
110
            // Sections and cm sorting.
111
            {watch: `course.sectionlist:updated`, handler: this._refreshCourseSectionlist},
112
            {watch: `section.cmlist:updated`, handler: this._refreshSectionCmlist},
113
        ];
114
    }
115
 
116
    /**
117
     * Setup sections toggler.
118
     *
119
     * Toggler click is delegated to the main course index element because new sections can
120
     * appear at any moment and this way we prevent accidental double bindings.
121
     *
122
     * @param {Event} event the triggered event
123
     */
124
    _sectionTogglers(event) {
125
        const sectionlink = event.target.closest(this.selectors.TOGGLER);
126
        const isChevron = event.target.closest(this.selectors.COLLAPSE);
127
 
128
        if (sectionlink || isChevron) {
129
 
130
            const section = event.target.closest(this.selectors.SECTION);
131
            const toggler = section.querySelector(this.selectors.COLLAPSE);
132
            const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;
133
 
134
            // Update the state.
135
            const sectionId = section.getAttribute('data-id');
136
            if (!sectionlink || isCollapsed) {
137
                this.reactive.dispatch(
138
                    'sectionIndexCollapsed',
139
                    [sectionId],
140
                    !isCollapsed
141
                );
142
            }
143
        }
144
    }
145
 
146
    /**
147
     * Update section collapsed.
148
     *
149
     * @param {object} args
150
     * @param {object} args.element The leement to be expanded
151
     */
152
    _refreshSectionCollapsed({element}) {
153
        const target = this.getElement(this.selectors.SECTION, element.id);
154
        if (!target) {
155
            throw new Error(`Unkown section with ID ${element.id}`);
156
        }
157
        // Check if it is already done.
158
        const toggler = target.querySelector(this.selectors.COLLAPSE);
159
        const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false;
160
 
161
        if (element.indexcollapsed !== isCollapsed) {
162
            this._expandSectionNode(element);
163
        }
164
    }
165
 
166
    /**
167
     * Expand a section node.
168
     *
169
     * By default the method will use element.indexcollapsed to decide if the
170
     * section is opened or closed. However, using forceValue it is possible
171
     * to open or close a section independant from the indexcollapsed attribute.
172
     *
173
     * @param {Object} element the course module state element
174
     * @param {boolean} forceValue optional forced expanded value
175
     */
176
    _expandSectionNode(element, forceValue) {
177
        const target = this.getElement(this.selectors.SECTION, element.id);
178
        const toggler = target.querySelector(this.selectors.COLLAPSE);
179
        let collapsibleId = toggler.dataset.target ?? toggler.getAttribute("href");
180
        if (!collapsibleId) {
181
            return;
182
        }
183
        collapsibleId = collapsibleId.replace('#', '');
184
        const collapsible = document.getElementById(collapsibleId);
185
        if (!collapsible) {
186
            return;
187
        }
188
 
189
        if (forceValue === undefined) {
190
            forceValue = (element.indexcollapsed) ? false : true;
191
        }
192
 
193
        // Course index is based on Bootstrap 4 collapsibles. To collapse them we need jQuery to
194
        // interact with collapsibles methods. Hopefully, this will change in Bootstrap 5 because
195
        // it does not require jQuery anymore (when MDL-71979 is integrated).
196
        const togglerValue = (forceValue) ? 'show' : 'hide';
197
        jQuery(collapsible).collapse(togglerValue);
198
    }
199
 
200
    /**
201
     * Handle a page item update.
202
     *
203
     * @param {Object} details the update details
204
     * @param {Object} details.state the state data.
205
     * @param {Object} details.element the course state data.
206
     */
207
    _refreshPageItem({element, state}) {
208
        if (!element?.pageItem?.isStatic || element.pageItem.type != 'cm') {
209
            return;
210
        }
211
        // Check if we need to uncollapse the section and scroll to the element.
212
        const section = state.section.get(element.pageItem.sectionId);
213
        if (section.indexcollapsed) {
214
            this._expandSectionNode(section, true);
215
            setTimeout(
216
                () => this.cms[element.pageItem.id]?.scrollIntoView({block: "nearest"}),
217
                250
218
            );
219
        }
220
    }
221
 
222
    /**
223
     * Expand a section if the current page is a section's cm.
224
     *
225
     * @private
226
     * @param {Object} state the course state.
227
     */
228
    _expandPageCmSectionIfNecessary(state) {
229
        const pageCmInfo = this.reactive.getPageAnchorCmInfo();
230
        if (!pageCmInfo) {
231
            return;
232
        }
233
        this._expandSectionNode(state.section.get(pageCmInfo.sectionid), true);
234
    }
235
 
236
    /**
237
     * Create a newcm instance.
238
     *
239
     * @param {object} param
240
     * @param {Object} param.state
241
     * @param {Object} param.element
242
     */
243
    async _createCm({state, element}) {
244
        // Create a fake node while the component is loading.
245
        const fakeelement = document.createElement('li');
246
        fakeelement.classList.add('bg-pulse-grey', 'w-100');
247
        fakeelement.innerHTML = '&nbsp;';
248
        this.cms[element.id] = fakeelement;
249
        // Place the fake node on the correct position.
250
        this._refreshSectionCmlist({
251
            state,
252
            element: state.section.get(element.sectionid),
253
        });
254
        // Collect render data.
255
        const exporter = this.reactive.getExporter();
256
        const data = exporter.cm(state, element);
257
        // Create the new content.
258
        const newcomponent = await this.renderComponent(fakeelement, 'theme_universe/courseindex/cm', data);
259
        // Replace the fake node with the real content.
260
        const newelement = newcomponent.getElement();
261
        this.cms[element.id] = newelement;
262
        fakeelement.parentNode.replaceChild(newelement, fakeelement);
263
    }
264
 
265
    /**
266
     * Create a new section instance.
267
     *
268
     * @param {Object} details the update details.
269
     * @param {Object} details.state the state data.
270
     * @param {Object} details.element the element data.
271
     */
272
    async _createSection({state, element}) {
273
        // Create a fake node while the component is loading.
274
        const fakeelement = document.createElement('div');
275
        fakeelement.classList.add('bg-pulse-grey', 'w-100');
276
        fakeelement.innerHTML = '&nbsp;';
277
        this.sections[element.id] = fakeelement;
278
        // Place the fake node on the correct position.
279
        this._refreshCourseSectionlist({
280
            state,
281
            element: state.course,
282
        });
283
        // Collect render data.
284
        const exporter = this.reactive.getExporter();
285
        const data = exporter.section(state, element);
286
        // Create the new content.
287
        const newcomponent = await this.renderComponent(fakeelement, 'theme_universe/courseindex/section', data);
288
        // Replace the fake node with the real content.
289
        const newelement = newcomponent.getElement();
290
        this.sections[element.id] = newelement;
291
        fakeelement.parentNode.replaceChild(newelement, fakeelement);
292
    }
293
 
294
    /**
295
     * Refresh a section cm list.
296
     *
297
     * @param {object} param
298
     * @param {Object} param.element
299
     */
300
    _refreshSectionCmlist({element}) {
301
        const cmlist = element.cmlist ?? [];
302
        const listparent = this.getElement(this.selectors.SECTION_CMLIST, element.id);
303
        this._fixOrder(listparent, cmlist, this.cms);
304
    }
305
 
306
    /**
307
     * Refresh the section list.
308
     *
309
     * @param {object} param
310
     * @param {Object} param.state
311
     */
312
    _refreshCourseSectionlist({state}) {
313
        const sectionlist = this.reactive.getExporter().listedSectionIds(state);
314
        this._fixOrder(this.element, sectionlist, this.sections);
315
    }
316
 
317
    /**
318
     * Fix/reorder the section or cms order.
319
     *
320
     * @param {Element} container the HTML element to reorder.
321
     * @param {Array} neworder an array with the ids order
322
     * @param {Array} allitems the list of html elements that can be placed in the container
323
     */
324
    _fixOrder(container, neworder, allitems) {
325
 
326
        // Empty lists should not be visible.
327
        if (!neworder.length) {
328
            container.classList.add('hidden');
329
            container.innerHTML = '';
330
            return;
331
        }
332
 
333
        // Grant the list is visible (in case it was empty).
334
        container.classList.remove('hidden');
335
 
336
        // Move the elements in order at the beginning of the list.
337
        neworder.forEach((itemid, index) => {
338
            const item = allitems[itemid];
339
            // Get the current element at that position.
340
            const currentitem = container.children[index];
341
            if (currentitem === undefined) {
342
                container.append(item);
343
                return;
344
            }
345
            if (currentitem !== item && item) {
346
                container.insertBefore(item, currentitem);
347
            }
348
        });
349
        // Remove the remaining elements.
350
        while (container.children.length > neworder.length) {
351
            container.removeChild(container.lastChild);
352
        }
353
    }
354
 
355
    /**
356
     * Remove a cm from the list.
357
     *
358
     * The actual DOM element removal is delegated to the cm component.
359
     *
360
     * @param {object} param
361
     * @param {Object} param.element
362
     */
363
    _deleteCm({element}) {
364
        delete this.cms[element.id];
365
    }
366
 
367
    /**
368
     * Remove a section from the list.
369
     *
370
     * The actual DOM element removal is delegated to the section component.
371
     *
372
     * @param {Object} details the update details.
373
     * @param {Object} details.element the element data.
374
     */
375
    _deleteSection({element}) {
376
        delete this.sections[element.id];
377
    }
378
}