Proyectos de Subversion Moodle

Rev

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