Proyectos de Subversion Moodle

Rev

Ir a la última revisión | | 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
 * Contain the logic for the add random question modal.
18
 *
19
 * @module     mod_quiz/modal_add_random_question
20
 * @copyright  2018 Ryan Wyllie <ryan@moodle.com>
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 */
23
 
24
import $ from 'jquery';
25
import Modal from './add_question_modal';
26
import * as Notification from 'core/notification';
27
import * as Fragment from 'core/fragment';
28
import * as Templates from 'core/templates';
29
import * as FormChangeChecker from 'core_form/changechecker';
30
import {call as fetchMany} from 'core/ajax';
31
import Pending from 'core/pending';
32
 
33
const SELECTORS = {
34
    EXISTING_CATEGORY_CONTAINER: '[data-region="existing-category-container"]',
35
    EXISTING_CATEGORY_TAB: '#id_existingcategoryheader',
36
    NEW_CATEGORY_CONTAINER: '[data-region="new-category-container"]',
37
    NEW_CATEGORY_TAB: '#id_newcategoryheader',
38
    TAB_CONTENT: '[data-region="tab-content"]',
39
    ADD_ON_PAGE_FORM_ELEMENT: '[name="addonpage"]',
40
    ADD_RANDOM_BUTTON: 'input[type="submit"][name="addrandom"]',
41
    ADD_NEW_CATEGORY_BUTTON: 'input[type="submit"][name="newcategory"]',
42
    SUBMIT_BUTTON_ELEMENT: 'input[type="submit"][name="addrandom"], input[type="submit"][name="newcategory"]',
43
    FORM_HEADER: 'legend',
44
    SELECT_NUMBER_TO_ADD: '#menurandomcount',
45
    NEW_CATEGORY_ELEMENT: '#categoryname',
46
    PARENT_CATEGORY_ELEMENT: '#parentcategory',
47
    FILTER_CONDITION_ELEMENT: '[data-filtercondition]',
48
    FORM_ELEMENT: '#add_random_question_form',
49
    MESSAGE_INPUT: '[name="message"]',
50
};
51
 
52
export default class ModalAddRandomQuestion extends Modal {
53
    static TYPE = 'mod_quiz-quiz-add-random-question';
54
    static TEMPLATE = 'mod_quiz/modal_add_random_question';
55
 
56
    /**
57
     * Create the add random question modal.
58
     *
59
     * @param  {Number} contextId Current context id.
60
     * @param  {string} category Category id and category context id comma separated.
61
     * @param  {string} returnUrl URL to return to after form submission.
62
     * @param  {Number} cmid Current course module id.
63
     * @param  {boolean} showNewCategory Display the New category tab when selecting random questions.
64
     */
65
    static init(contextId, category, returnUrl, cmid, showNewCategory = true) {
66
        const selector = '.menu [data-action="addarandomquestion"]';
67
        document.addEventListener('click', (e) => {
68
            const trigger = e.target.closest(selector);
69
            if (!trigger) {
70
                return;
71
            }
72
            e.preventDefault();
73
 
74
            ModalAddRandomQuestion.create({
75
                contextId,
76
                category,
77
                returnUrl,
78
                cmid,
79
 
80
                title: trigger.dataset.header,
81
                addOnPage: trigger.dataset.addonpage,
82
 
83
                templateContext: {
84
                    hidden: showNewCategory,
85
                },
86
            });
87
        });
88
    }
89
 
90
    /**
91
     * Constructor for the Modal.
92
     *
93
     * @param {object} root The root jQuery element for the modal
94
     */
95
    constructor(root) {
96
        super(root);
97
        this.category = null;
98
        this.returnUrl = null;
99
        this.cmid = null;
100
        this.loadedForm = false;
101
    }
102
 
103
    configure(modalConfig) {
104
        this.setCategory(modalConfig.category);
105
        this.setReturnUrl(modalConfig.returnUrl);
106
        this.setCMID(modalConfig.cmid);
107
 
108
        super.configure(modalConfig);
109
    }
110
 
111
    /**
112
     * Set the id of the page that the question should be added to
113
     * when the user clicks the add to quiz link.
114
     *
115
     * @method setAddOnPageId
116
     * @param {int} id
117
     */
118
    setAddOnPageId(id) {
119
        super.setAddOnPageId(id);
120
        this.getBody().find(SELECTORS.ADD_ON_PAGE_FORM_ELEMENT).val(id);
121
    }
122
 
123
    /**
124
     * Set the category for this form. The category is a comma separated
125
     * category id and category context id.
126
     *
127
     * @method setCategory
128
     * @param {string} category
129
     */
130
    setCategory(category) {
131
        this.category = category;
132
    }
133
 
134
    /**
135
     * Returns the saved category.
136
     *
137
     * @method getCategory
138
     * @return {string}
139
     */
140
    getCategory() {
141
        return this.category;
142
    }
143
 
144
    /**
145
     * Set the return URL for the form.
146
     *
147
     * @method setReturnUrl
148
     * @param {string} url
149
     */
150
    setReturnUrl(url) {
151
        this.returnUrl = url;
152
    }
153
 
154
    /**
155
     * Returns the return URL for the form.
156
     *
157
     * @method getReturnUrl
158
     * @return {string}
159
     */
160
    getReturnUrl() {
161
        return this.returnUrl;
162
    }
163
 
164
    /**
165
     * Set the course module id for the form.
166
     *
167
     * @method setCMID
168
     * @param {Number} id
169
     */
170
    setCMID(id) {
171
        this.cmid = id;
172
    }
173
 
174
    /**
175
     * Returns the course module id for the form.
176
     *
177
     * @method getCMID
178
     * @return {Number}
179
     */
180
    getCMID() {
181
        return this.cmid;
182
    }
183
 
184
    /**
185
     * Moves a given form element inside (a child of) a given tab element.
186
     *
187
     * Hides the 'legend' (e.g. header) element of the form element because the
188
     * tab has the name.
189
     *
190
     * Moves the submit button into a footer element at the bottom of the form
191
     * element for styling purposes.
192
     *
193
     * @method moveContentIntoTab
194
     * @param  {jquery} tabContent The form element to move into the tab.
195
     * @param  {jquey} tabElement The tab element for the form element to move into.
196
     */
197
    moveContentIntoTab(tabContent, tabElement) {
198
        // Hide the header because the tabs show us which part of the form we're
199
        // looking at.
200
        tabContent.find(SELECTORS.FORM_HEADER).addClass('hidden');
201
        // Move the element inside a tab.
202
        tabContent.wrap(tabElement);
203
    }
204
 
205
    /**
206
     * Empty the tab content container and move all tabs from the form into the
207
     * tab container element.
208
     *
209
     * @method moveTabsIntoTabContent
210
     * @param  {jquery} form The form element.
211
     */
212
    moveTabsIntoTabContent(form) {
213
        // Empty it to remove the loading icon.
214
        const tabContent = this.getBody().find(SELECTORS.TAB_CONTENT).empty();
215
        // Make sure all tabs are inside the tab content element.
216
        form.find('[role="tabpanel"]').wrapAll(tabContent);
217
    }
218
 
219
    /**
220
     * Make sure all of the tabs have a cancel button in their fotter to sit along
221
     * side the submit button.
222
     *
223
     * @method moveCancelButtonToTabs
224
     * @param  {jquey} form The form element.
225
     */
226
    moveCancelButtonToTabs(form) {
227
        const cancelButton = form.find(SELECTORS.CANCEL_BUTTON_ELEMENT).addClass('ml-1');
228
        const tabFooters = form.find('[data-region="footer"]');
229
        // Remove the buttons container element.
230
        cancelButton.closest(SELECTORS.BUTTON_CONTAINER).remove();
231
        cancelButton.clone().appendTo(tabFooters);
232
    }
233
 
234
    /**
235
     * Load the add random question form in a fragement and perform some transformation
236
     * on the HTML to convert it into tabs for rendering in the modal.
237
     *
238
     * @method loadForm
239
     * @return {promise} Resolved with form HTML and JS.
240
     */
241
    loadForm() {
242
        const cmid = this.getCMID();
243
        const cat = this.getCategory();
244
        const addonpage = this.getAddOnPageId();
245
        const returnurl = this.getReturnUrl();
246
 
247
        return Fragment.loadFragment(
248
            'mod_quiz',
249
            'add_random_question_form',
250
            this.getContextId(),
251
            {
252
                addonpage,
253
                cat,
254
                returnurl,
255
                cmid,
256
            }
257
        )
258
        .then((html, js) =>{
259
            const form = $(html);
260
            const existingCategoryTabContent = form.find(SELECTORS.EXISTING_CATEGORY_TAB);
261
            const existingCategoryTab = this.getBody().find(SELECTORS.EXISTING_CATEGORY_CONTAINER);
262
            const newCategoryTabContent = form.find(SELECTORS.NEW_CATEGORY_TAB);
263
            const newCategoryTab = this.getBody().find(SELECTORS.NEW_CATEGORY_CONTAINER);
264
 
265
            // Transform the form into tabs for better rendering in the modal.
266
            this.moveContentIntoTab(existingCategoryTabContent, existingCategoryTab);
267
            this.moveContentIntoTab(newCategoryTabContent, newCategoryTab);
268
            this.moveTabsIntoTabContent(form);
269
 
270
            Templates.replaceNode(this.getBody().find(SELECTORS.TAB_CONTENT), form, js);
271
            return;
272
        })
273
        .then(() => {
274
            // Make sure the form change checker is disabled otherwise it'll stop the user from navigating away from the
275
            // page once the modal is hidden.
276
            FormChangeChecker.disableAllChecks();
277
 
278
            // Add question to quiz.
279
            this.getBody()[0].addEventListener('click', (e) => {
280
                const button = e.target.closest(SELECTORS.SUBMIT_BUTTON_ELEMENT);
281
                if (!button) {
282
                    return;
283
                }
284
                e.preventDefault();
285
 
286
                // Add Random questions if the add random button was clicked.
287
                const addRandomButton = e.target.closest(SELECTORS.ADD_RANDOM_BUTTON);
288
                if (addRandomButton) {
289
                    const randomcount = document.querySelector(SELECTORS.SELECT_NUMBER_TO_ADD).value;
290
                    const filtercondition = document.querySelector(SELECTORS.FILTER_CONDITION_ELEMENT).dataset?.filtercondition;
291
 
292
                    this.addQuestions(cmid, addonpage, randomcount, filtercondition, '', '');
293
                    return;
294
                }
295
                // Add new category if the add category button was clicked.
296
                const addCategoryButton = e.target.closest(SELECTORS.ADD_NEW_CATEGORY_BUTTON);
297
                if (addCategoryButton) {
298
                    this.addQuestions(
299
                        cmid,
300
                        addonpage,
301
                        1,
302
                        '',
303
                        document.querySelector(SELECTORS.NEW_CATEGORY_ELEMENT).value,
304
                        document.querySelector(SELECTORS.PARENT_CATEGORY_ELEMENT).value
305
                    );
306
                    return;
307
                }
308
            });
309
        })
310
        .catch(Notification.exception);
311
    }
312
 
313
    /**
314
     * Call web service function to add random questions
315
     *
316
     * @param {number} cmid course module id
317
     * @param {number} addonpage the page where random questions will be added to
318
     * @param {number} randomcount Number of random questions
319
     * @param {string} filtercondition Filter condition
320
     * @param {string} newcategory add new category
321
     * @param {string} parentcategory parent category of new category
322
     */
323
    async addQuestions(
324
        cmid,
325
        addonpage,
326
        randomcount,
327
        filtercondition,
328
        newcategory,
329
        parentcategory
330
    ) {
331
        // We do not need to resolve this Pending because the form submission will result in a page redirect.
332
        new Pending('mod-quiz/modal_add_random_questions');
333
        const call = {
334
            methodname: 'mod_quiz_add_random_questions',
335
            args: {
336
                cmid,
337
                addonpage,
338
                randomcount,
339
                filtercondition,
340
                newcategory,
341
                parentcategory,
342
            }
343
        };
344
        try {
345
            const response = await fetchMany([call])[0];
346
            const form = document.querySelector(SELECTORS.FORM_ELEMENT);
347
            const messageInput = form.querySelector(SELECTORS.MESSAGE_INPUT);
348
            messageInput.value = response.message;
349
            form.submit();
350
        } catch (e) {
351
            Notification.exception(e);
352
        }
353
    }
354
 
355
    /**
356
     * Override the modal show function to load the form when this modal is first
357
     * shown.
358
     *
359
     * @method show
360
     */
361
    show() {
362
        super.show(this);
363
 
364
        if (!this.loadedForm) {
365
            this.loadForm(window.location.search);
366
            this.loadedForm = true;
367
        }
368
    }
369
}
370
 
371
ModalAddRandomQuestion.registerModalType();