Proyectos de Subversion Moodle

Rev

Rev 1 | | 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
 * Javascript controller for the "Grading" panel at the right of the page.
18
 *
19
 * @module     mod_assign/grading_panel
20
 * @copyright  2016 Damyon Wiese <damyon@moodle.com>
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 * @since      3.1
23
 */
24
define([
25
    'jquery',
26
    'core/yui',
27
    'core/notification',
28
    'core/templates',
29
    'core/fragment',
30
    'core/ajax',
31
    'core/str',
32
    'mod_assign/grading_form_change_checker',
33
    'mod_assign/grading_events',
34
    'core_form/events',
35
    'core/toast',
36
    'core_form/changechecker',
37
], function(
38
    $,
39
    Y,
40
    notification,
41
    templates,
42
    fragment,
43
    ajax,
44
    str,
45
    checker,
46
    GradingEvents,
47
    FormEvents,
48
    Toast,
49
    FormChangeChecker
50
) {
51
 
52
    /**
53
     * GradingPanel class.
54
     *
55
     * @class mod_assign/grading_panel
56
     * @param {String} selector The selector for the page region containing the user navigation.
57
     */
58
    var GradingPanel = function(selector) {
59
        this._regionSelector = selector;
60
        this._region = $(selector);
61
        this._userCache = [];
62
 
63
        this.registerEventListeners();
64
    };
65
 
66
    /** @property {String} Selector for the page region containing the user navigation. */
67
    GradingPanel.prototype._regionSelector = null;
68
 
69
    /** @property {Integer} Remember the last user id to prevent unnessecary reloads. */
70
    GradingPanel.prototype._lastUserId = 0;
71
 
72
    /** @property {Integer} Remember the last attempt number to prevent unnessecary reloads. */
73
    GradingPanel.prototype._lastAttemptNumber = -1;
74
 
75
    /** @property {JQuery} JQuery node for the page region containing the user navigation. */
76
    GradingPanel.prototype._region = null;
77
 
78
     /** @property {Integer} The id of the next user in the grading list */
79
    GradingPanel.prototype.nextUserId = null;
80
 
81
     /** @property {Boolean} Next user exists in the grading list */
82
    GradingPanel.prototype.nextUser = false;
83
 
84
    /**
85
     * Fade the dom node out, update it, and fade it back.
86
     *
87
     * @private
88
     * @method _niceReplaceNodeContents
89
     * @param {JQuery} node
90
     * @param {String} html
91
     * @param {String} js
92
     * @return {Deferred} promise resolved when the animations are complete.
93
     */
94
    GradingPanel.prototype._niceReplaceNodeContents = function(node, html, js) {
95
        var promise = $.Deferred();
96
 
97
        node.fadeOut("fast", function() {
98
            templates.replaceNodeContents(node, html, js);
99
            node.fadeIn("fast", function() {
100
                promise.resolve();
101
            });
102
        });
103
 
104
        return promise.promise();
105
    };
106
 
107
    /**
108
     * Make sure all form fields have the latest saved state.
109
     * @private
110
     * @method _saveFormState
111
     */
112
    GradingPanel.prototype._saveFormState = function() {
113
        // Copy data from notify students checkbox which was moved out of the form.
114
        var checked = $('[data-region="grading-actions-form"] [name="sendstudentnotifications"]').prop("checked");
115
        $('.gradeform [name="sendstudentnotifications"]').val(checked);
116
    };
117
 
118
    /**
119
     * Make form submit via ajax.
120
     *
121
     * @private
122
     * @param {Object} event
123
     * @param {Integer} nextUserId
124
     * @param {Boolean} nextUser optional. Load next user in the grading list.
125
     * @method _submitForm
126
     * @fires event:formSubmittedByJavascript
127
     */
128
    GradingPanel.prototype._submitForm = function(event, nextUserId, nextUser) {
129
        // If the form has data in comment-area, then we need to save that comment
130
        var commentAreaElement = document.querySelector('.comment-area');
131
        if (commentAreaElement) {
132
            var commentTextAreaElement = commentAreaElement.querySelector('.db > textarea');
133
            if (commentTextAreaElement.value !== '') {
134
                var commentActionPostElement = commentAreaElement.querySelector('.fd a[id^="comment-action-post-"]');
135
                commentActionPostElement.click();
136
            }
137
        }
138
 
139
        // The form was submitted - send it via ajax instead.
140
        var form = $(this._region.find('form.gradeform'));
141
 
142
        $('[data-region="overlay"]').show();
143
 
144
        // Mark the form as submitted in the change checker.
145
        FormChangeChecker.markFormSubmitted(form[0]);
146
 
147
        // We call this, so other modules can update the form with the latest state.
148
        form.trigger('save-form-state');
149
 
150
        // Tell all form fields we are about to submit the form.
151
        FormEvents.notifyFormSubmittedByJavascript(form[0]);
152
 
153
        // Now we get all the current values from the form.
154
        var data = form.serialize();
155
        var assignmentid = this._region.attr('data-assignmentid');
156
 
157
        // Now we can continue...
158
        ajax.call([{
159
            methodname: 'mod_assign_submit_grading_form',
160
            args: {assignmentid: assignmentid, userid: this._lastUserId, jsonformdata: JSON.stringify(data)},
161
            done: this._handleFormSubmissionResponse.bind(this, data, nextUserId, nextUser),
162
            fail: notification.exception
163
        }]);
164
    };
165
 
166
    /**
167
     * Handle form submission response.
168
     *
169
     * @private
170
     * @method _handleFormSubmissionResponse
171
     * @param {Array} formdata - submitted values
172
     * @param {Number} [nextUserId] The id of the user to load after the form is saved
173
     * @param {Boolean} [nextUser] - Whether to switch to next user in the grading list.
174
     * @param {Array} response List of errors.
175
     */
176
    GradingPanel.prototype._handleFormSubmissionResponse = function(formdata, nextUserId, nextUser, response) {
177
        if (typeof nextUserId === "undefined") {
178
            nextUserId = this._lastUserId;
179
        }
180
        if (response.length) {
1441 ariadna 181
            str.get_string('errorgradechangessaveddetail', 'mod_assign')
182
                .then(function(str) {
183
                    Toast.add(str, {type: 'danger', delay: 4000});
184
                    return str;
185
                })
186
                .catch(notification.exception);
187
 
1 efrain 188
            // There was an error saving the grade. Re-render the form using the submitted data so we can show
189
            // validation errors.
1441 ariadna 190
            $(document).trigger('reset', [this._lastUserId, formdata, true]);
1 efrain 191
        } else {
192
            str.get_string('gradechangessaveddetail', 'mod_assign')
193
            .then(function(str) {
194
                Toast.add(str);
195
                return str;
196
            })
197
            .catch(notification.exception);
198
 
199
            // Reset the form state.
200
            var form = $(this._region.find('form.gradeform'));
201
            FormChangeChecker.resetFormDirtyState(form[0]);
202
 
203
            if (nextUserId == this._lastUserId) {
204
                $(document).trigger('reset', nextUserId);
205
            } else if (nextUser) {
206
                $(document).trigger('done-saving-show-next', true);
207
            } else {
208
                $(document).trigger('user-changed', nextUserId);
209
            }
210
        }
211
        $('[data-region="overlay"]').hide();
212
    };
213
 
214
    /**
215
     * Refresh form with default values.
216
     *
217
     * @private
218
     * @method _resetForm
219
     * @param {Event} e
220
     * @param {Integer} userid
221
     * @param {Array} formdata
1441 ariadna 222
     * @param {Boolean} unresolvederror
1 efrain 223
     */
1441 ariadna 224
    GradingPanel.prototype._resetForm = function(e, userid, formdata, unresolvederror) {
1 efrain 225
        // The form was cancelled - refresh with default values.
226
        var event = $.Event("custom");
227
        if (typeof userid == "undefined") {
228
            userid = this._lastUserId;
229
        }
230
        this._lastUserId = 0;
1441 ariadna 231
        this._refreshGradingPanel(event, userid, formdata, -1, unresolvederror);
1 efrain 232
    };
233
 
234
    /**
235
     * Open a picker to choose an older attempt.
236
     *
237
     * @private
238
     * @param {Object} e
239
     * @method _chooseAttempt
240
     */
241
    GradingPanel.prototype._chooseAttempt = function(e) {
242
        // Show a dialog.
243
 
244
        // The form is in the element pointed to by data-submissions.
245
        var link = $(e.target);
246
        var submissionsId = link.data('submissions');
247
        var submissionsform = $(document.getElementById(submissionsId));
248
        var formcopy = submissionsform.clone();
249
        var formhtml = formcopy.wrap($('<form/>')).html();
250
 
251
        str.get_strings([
252
            {key: 'viewadifferentattempt', component: 'mod_assign'},
253
            {key: 'view', component: 'core'},
254
            {key: 'cancel', component: 'core'},
255
        ]).done(function(strs) {
256
            notification.confirm(strs[0], formhtml, strs[1], strs[2], function() {
257
                var attemptnumber = $("input:radio[name='select-attemptnumber']:checked").val();
258
 
259
                this._refreshGradingPanel(null, this._lastUserId, '', attemptnumber);
260
            }.bind(this));
261
        }.bind(this)).fail(notification.exception);
262
    };
263
 
264
    /**
265
     * Add popout buttons
266
     *
267
     * @private
268
     * @method _addPopoutButtons
269
     * @param {JQuery} selector The region selector to add popout buttons to.
270
     */
271
    GradingPanel.prototype._addPopoutButtons = function(selector) {
272
        var region = $(selector);
273
 
274
        templates.render('mod_assign/popout_button', {}).done(function(html) {
275
            var parents = region.find('[data-fieldtype="filemanager"],[data-fieldtype="editor"],[data-fieldtype="grading"]')
276
                    .closest('.fitem');
1441 ariadna 277
            parents.addClass('has-popout').find('label:first').parent().append(html);
1 efrain 278
 
279
            region.on('click', '[data-region="popout-button"]', this._togglePopout.bind(this));
280
        }.bind(this)).fail(notification.exception);
281
    };
282
 
283
    /**
284
     * Make a div "popout" or "popback".
285
     *
286
     * @private
287
     * @method _togglePopout
288
     * @param {Event} event
289
     */
290
    GradingPanel.prototype._togglePopout = function(event) {
291
        event.preventDefault();
292
        var container = $(event.target).closest('.fitem');
293
        if (container.hasClass('popout')) {
294
            $('.popout').removeClass('popout');
295
        } else {
296
            $('.popout').removeClass('popout');
297
            container.addClass('popout');
298
            container.addClass('moodle-has-zindex');
299
        }
300
    };
301
 
302
    /**
303
     * Get the user context - re-render the template in the page.
304
     *
305
     * @private
306
     * @method _refreshGradingPanel
307
     * @param {Event} event
308
     * @param {Number} userid
309
     * @param {String} submissiondata serialised submission data.
310
     * @param {Integer} attemptnumber
1441 ariadna 311
     * @param {Boolean} unresolvederror
1 efrain 312
     */
1441 ariadna 313
    GradingPanel.prototype._refreshGradingPanel = function(event, userid, submissiondata, attemptnumber, unresolvederror) {
1 efrain 314
        var contextid = this._region.attr('data-contextid');
315
        if (typeof submissiondata === 'undefined') {
316
            submissiondata = '';
317
        }
318
        if (typeof attemptnumber === 'undefined') {
319
            attemptnumber = -1;
320
        }
1441 ariadna 321
        if (typeof unresolvederror === 'undefined') {
322
            unresolvederror = false;
323
        }
1 efrain 324
        // Skip reloading if it is the same user.
325
        if (this._lastUserId == userid && this._lastAttemptNumber == attemptnumber && submissiondata === '') {
326
            return;
327
        }
328
        this._lastUserId = userid;
329
        this._lastAttemptNumber = attemptnumber;
330
        $(document).trigger('start-loading-user');
331
        // Tell behat to back off too.
332
        window.M.util.js_pending('mod-assign-loading-user');
333
        // First insert the loading template.
334
        templates.render('mod_assign/loading', {}).done(function(html, js) {
335
            // Update the page.
336
            this._niceReplaceNodeContents(this._region, html, js).done(function() {
337
                if (userid > 0) {
338
                    this._region.show();
339
                    // Reload the grading form "fragment" for this user.
340
                    var params = {userid: userid, attemptnumber: attemptnumber, jsonformdata: JSON.stringify(submissiondata)};
341
                    fragment.loadFragment('mod_assign', 'gradingpanel', contextid, params).done(function(html, js) {
1441 ariadna 342
 
343
                        // Reset whole grading page when there is a failure in retrieving the html
344
                        // i.e. user no longer under "requires grading" filter when graded
345
                        if (html === '') {
346
                            $(document).trigger('reset-table', true);
347
                        }
348
 
1 efrain 349
                        this._niceReplaceNodeContents(this._region, html, js)
350
                        .done(function() {
351
                            checker.saveFormState('[data-region="grade-panel"] .gradeform');
352
                            $(document).on('editor-content-restored', function() {
353
                                // If the editor has some content that has been restored
354
                                // then save the form state again for comparison.
355
                                checker.saveFormState('[data-region="grade-panel"] .gradeform');
356
                            });
357
                            $('[data-region="attempt-chooser"]').on('click', this._chooseAttempt.bind(this));
358
                            this._addPopoutButtons('[data-region="grade-panel"] .gradeform');
1441 ariadna 359
                            if (unresolvederror) {
360
                                $('[data-region="grade-panel"] .gradeform').data('unresolved-error', true);
361
                            }
1 efrain 362
                            $(document).trigger('finish-loading-user');
363
                            // Tell behat we are friends again.
364
                            window.M.util.js_complete('mod-assign-loading-user');
365
                        }.bind(this))
366
                        .fail(notification.exception);
367
                    }.bind(this)).fail(notification.exception);
368
                    $('[data-region="review-panel"]').show();
369
                } else {
370
                    this._region.hide();
371
                    $('[data-region="review-panel"]').hide();
372
                    $(document).trigger('finish-loading-user');
373
                    // Tell behat we are friends again.
374
                    window.M.util.js_complete('mod-assign-loading-user');
375
                }
376
            }.bind(this));
377
        }.bind(this)).fail(notification.exception);
378
    };
379
 
380
    /**
381
     * Get next user data and store it in global variables
382
     *
383
     * @private
384
     * @method _getNextUser
385
     * @param {Event} event
386
     * @param {Object} data Next user's data
387
     */
388
    GradingPanel.prototype._getNextUser = function(event, data) {
389
        this.nextUserId = data.nextUserId;
390
        this.nextUser = data.nextUser;
391
    };
392
 
393
    /**
394
     * Handle the save-and-show-next event
395
     *
396
     * @private
397
     * @method _handleSaveAndShowNext
398
     */
399
    GradingPanel.prototype._handleSaveAndShowNext = function() {
400
        this._submitForm(null, this.nextUserId, this.nextUser);
401
    };
402
 
403
    /**
404
     * Get the grade panel element.
405
     *
406
     * @method getPanelElement
407
     * @return {jQuery}
408
     */
409
    GradingPanel.prototype.getPanelElement = function() {
410
        return $('[data-region="grade-panel"]');
411
    };
412
 
413
    /**
414
     * Hide the grade panel.
415
     *
416
     * @method collapsePanel
417
     */
418
    GradingPanel.prototype.collapsePanel = function() {
419
        this.getPanelElement().addClass('collapsed');
420
    };
421
 
422
    /**
423
     * Show the grade panel.
424
     *
425
     * @method expandPanel
426
     */
427
    GradingPanel.prototype.expandPanel = function() {
428
        this.getPanelElement().removeClass('collapsed');
429
    };
430
 
431
    /**
432
     * Register event listeners for the grade panel.
433
     *
434
     * @method registerEventListeners
435
     */
436
    GradingPanel.prototype.registerEventListeners = function() {
437
        var docElement = $(document);
438
        var region = $(this._region);
439
        // Add an event listener to prevent form submission when pressing enter key.
440
        region.on('submit', 'form', function(e) {
441
            e.preventDefault();
442
        });
443
 
444
        docElement.on('next-user', this._getNextUser.bind(this));
445
        docElement.on('user-changed', this._refreshGradingPanel.bind(this));
446
        docElement.on('save-changes', this._submitForm.bind(this));
447
        docElement.on('save-and-show-next', this._handleSaveAndShowNext.bind(this));
448
        docElement.on('reset', this._resetForm.bind(this));
449
 
450
        docElement.on('save-form-state', this._saveFormState.bind(this));
451
 
452
        docElement.on(GradingEvents.COLLAPSE_GRADE_PANEL, function() {
453
            this.collapsePanel();
454
        }.bind(this));
455
 
456
        // We should expand if the review panel is collapsed.
457
        docElement.on(GradingEvents.COLLAPSE_REVIEW_PANEL, function() {
458
            this.expandPanel();
459
        }.bind(this));
460
 
461
        docElement.on(GradingEvents.EXPAND_GRADE_PANEL, function() {
462
            this.expandPanel();
463
        }.bind(this));
464
    };
465
 
466
    return GradingPanel;
467
});