ee0ab1ca005cc172d03c232512009a8dfd6a64a8
[moodle.git] / mod / assign / amd / src / grading_panel.js
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/>.
16 /**
17  * Javascript controller for the "Grading" panel at the right of the page.
18  *
19  * @module     mod_assign/grading_panel
20  * @package    mod_assign
21  * @class      GradingPanel
22  * @copyright  2016 Damyon Wiese <damyon@moodle.com>
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  * @since      3.1
25  */
26 define(['jquery', 'core/yui', 'core/notification', 'core/templates', 'core/fragment',
27         'core/ajax', 'core/str', 'mod_assign/grading_form_change_checker',
28         'mod_assign/grading_events'],
29        function($, Y, notification, templates, fragment, ajax, str, checker, GradingEvents) {
31     /**
32      * GradingPanel class.
33      *
34      * @class GradingPanel
35      * @param {String} selector The selector for the page region containing the user navigation.
36      */
37     var GradingPanel = function(selector) {
38         this._regionSelector = selector;
39         this._region = $(selector);
40         this._userCache = [];
42         this.registerEventListeners();
43     };
45     /** @type {String} Selector for the page region containing the user navigation. */
46     GradingPanel.prototype._regionSelector = null;
48     /** @type {Integer} Remember the last user id to prevent unnessecary reloads. */
49     GradingPanel.prototype._lastUserId = 0;
51     /** @type {Integer} Remember the last attempt number to prevent unnessecary reloads. */
52     GradingPanel.prototype._lastAttemptNumber = -1;
54     /** @type {JQuery} JQuery node for the page region containing the user navigation. */
55     GradingPanel.prototype._region = null;
57     /**
58      * Fade the dom node out, update it, and fade it back.
59      *
60      * @private
61      * @method _niceReplaceNodeContents
62      * @param {JQuery} node
63      * @param {String} html
64      * @param {String} js
65      * @return {Deferred} promise resolved when the animations are complete.
66      */
67     GradingPanel.prototype._niceReplaceNodeContents = function(node, html, js) {
68         var promise = $.Deferred();
70         node.fadeOut("fast", function() {
71             templates.replaceNodeContents(node, html, js);
72             node.fadeIn("fast", function() {
73                 promise.resolve();
74             });
75         });
77         return promise.promise();
78     };
80     /**
81      * Make sure all form fields have the latest saved state.
82      * @private
83      * @method _saveFormState
84      */
85     GradingPanel.prototype._saveFormState = function() {
86         // Grrrrr! TinyMCE you know what you did.
87         if (typeof window.tinyMCE !== 'undefined') {
88             window.tinyMCE.triggerSave();
89         }
91         // Copy data from notify students checkbox which was moved out of the form.
92         var checked = $('[data-region="grading-actions-form"] [name="sendstudentnotifications"]').prop("checked");
93         $('.gradeform [name="sendstudentnotifications"]').val(checked);
94     };
96     /**
97      * Make form submit via ajax.
98      *
99      * @private
100      * @param {Object} event
101      * @param {Integer} nextUserId
102      * @param {Boolean} nextUser optional. Load next user in the grading list.
103      * @method _submitForm
104      */
105     GradingPanel.prototype._submitForm = function(event, nextUserId, nextUser) {
106         // The form was submitted - send it via ajax instead.
107         var form = $(this._region.find('form.gradeform'));
109         $('[data-region="overlay"]').show();
111         // We call this, so other modules can update the form with the latest state.
112         form.trigger('save-form-state');
114         // Now we get all the current values from the form.
115         var data = form.serialize();
116         var assignmentid = this._region.attr('data-assignmentid');
118         // Now we can continue...
119         ajax.call([{
120             methodname: 'mod_assign_submit_grading_form',
121             args: {assignmentid: assignmentid, userid: this._lastUserId, jsonformdata: JSON.stringify(data)},
122             done: this._handleFormSubmissionResponse.bind(this, data, nextUserId, nextUser),
123             fail: notification.exception
124         }]);
125     };
127     /**
128      * Handle form submission response.
129      *
130      * @private
131      * @method _handleFormSubmissionResponse
132      * @param {Array} formdata - submitted values
133      * @param {Integer} nextUserId - optional. The id of the user to load after the form is saved.
134      * @param {Array} response List of errors.
135      * @param {Boolean} nextUser - optional. If true, switch to next user in the grading list.
136      */
137     GradingPanel.prototype._handleFormSubmissionResponse = function(formdata, nextUserId, nextUser, response) {
138         if (typeof nextUserId === "undefined") {
139             nextUserId = this._lastUserId;
140         }
141         if (response.length) {
142             // There was an error saving the grade. Re-render the form using the submitted data so we can show
143             // validation errors.
144             $(document).trigger('reset', [this._lastUserId, formdata]);
145         } else {
146             str.get_strings([
147                 {key: 'changessaved', component: 'core'},
148                 {key: 'gradechangessaveddetail', component: 'mod_assign'},
149             ]).done(function(strs) {
150                 notification.alert(strs[0], strs[1]);
151             }).fail(notification.exception);
152             Y.use('moodle-core-formchangechecker', function() {
153                 M.core_formchangechecker.reset_form_dirty_state();
154             });
155             if (nextUserId == this._lastUserId) {
156                 $(document).trigger('reset', nextUserId);
157             } else if (nextUser) {
158                 $(document).trigger('done-saving-show-next', true);
159             } else {
160                 $(document).trigger('user-changed', nextUserId);
161             }
162         }
163         $('[data-region="overlay"]').hide();
164     };
166     /**
167      * Refresh form with default values.
168      *
169      * @private
170      * @method _resetForm
171      * @param {Event} e
172      * @param {Integer} userid
173      * @param {Array} formdata
174      */
175     GradingPanel.prototype._resetForm = function(e, userid, formdata) {
176         // The form was cancelled - refresh with default values.
177         var event = $.Event("custom");
178         if (typeof userid == "undefined") {
179             userid = this._lastUserId;
180         }
181         this._lastUserId = 0;
182         this._refreshGradingPanel(event, userid, formdata);
183     };
185     /**
186      * Open a picker to choose an older attempt.
187      *
188      * @private
189      * @param {Object} e
190      * @method _chooseAttempt
191      */
192     GradingPanel.prototype._chooseAttempt = function(e) {
193         // Show a dialog.
195         // The form is in the element pointed to by data-submissions.
196         var link = $(e.target);
197         var submissionsId = link.data('submissions');
198         var submissionsform = $(document.getElementById(submissionsId));
199         var formcopy = submissionsform.clone();
200         var formhtml = formcopy.wrap($('<form/>')).html();
202         str.get_strings([
203             {key: 'viewadifferentattempt', component: 'mod_assign'},
204             {key: 'view', component: 'core'},
205             {key: 'cancel', component: 'core'},
206         ]).done(function(strs) {
207             notification.confirm(strs[0], formhtml, strs[1], strs[2], function() {
208                 var attemptnumber = $("input:radio[name='select-attemptnumber']:checked").val();
210                 this._refreshGradingPanel(null, this._lastUserId, '', attemptnumber);
211             }.bind(this));
212         }.bind(this)).fail(notification.exception);
213     };
215     /**
216      * Add popout buttons
217      *
218      * @private
219      * @method _addPopoutButtons
220      * @param {JQuery} selector The region selector to add popout buttons to.
221      */
222     GradingPanel.prototype._addPopoutButtons = function(selector) {
223         var region = $(selector);
225         templates.render('mod_assign/popout_button', {}).done(function(html) {
226             var parents = region.find('[data-fieldtype="filemanager"],[data-fieldtype="editor"],[data-fieldtype="grading"]')
227                     .closest('.fitem');
228             parents.addClass('has-popout').find('label').parent().append(html);
230             region.on('click', '[data-region="popout-button"]', this._togglePopout.bind(this));
231         }.bind(this)).fail(notification.exception);
232     };
234     /**
235      * Make a div "popout" or "popback".
236      *
237      * @private
238      * @method _togglePopout
239      * @param {Event} event
240      */
241     GradingPanel.prototype._togglePopout = function(event) {
242         event.preventDefault();
243         var container = $(event.target).closest('.fitem');
244         if (container.hasClass('popout')) {
245             $('.popout').removeClass('popout');
246         } else {
247             $('.popout').removeClass('popout');
248             container.addClass('popout');
249             container.addClass('moodle-has-zindex');
250         }
251     };
253     /**
254      * Get the user context - re-render the template in the page.
255      *
256      * @private
257      * @method _refreshGradingPanel
258      * @param {Event} event
259      * @param {Number} userid
260      * @param {String} submissiondata serialised submission data.
261      * @param {Integer} attemptnumber
262      */
263     GradingPanel.prototype._refreshGradingPanel = function(event, userid, submissiondata, attemptnumber) {
264         var contextid = this._region.attr('data-contextid');
265         if (typeof submissiondata === 'undefined') {
266             submissiondata = '';
267         }
268         if (typeof attemptnumber === 'undefined') {
269             attemptnumber = -1;
270         }
271         // Skip reloading if it is the same user.
272         if (this._lastUserId == userid && this._lastAttemptNumber == attemptnumber && submissiondata === '') {
273             return;
274         }
275         this._lastUserId = userid;
276         this._lastAttemptNumber = attemptnumber;
277         $(document).trigger('start-loading-user');
278         // Tell behat to back off too.
279         window.M.util.js_pending('mod-assign-loading-user');
280         // First insert the loading template.
281         templates.render('mod_assign/loading', {}).done(function(html, js) {
282             // Update the page.
283             this._niceReplaceNodeContents(this._region, html, js).done(function() {
284                 if (userid > 0) {
285                     this._region.show();
286                     // Reload the grading form "fragment" for this user.
287                     var params = {userid: userid, attemptnumber: attemptnumber, jsonformdata: JSON.stringify(submissiondata)};
288                     fragment.loadFragment('mod_assign', 'gradingpanel', contextid, params).done(function(html, js) {
289                         this._niceReplaceNodeContents(this._region, html, js)
290                         .done(function() {
291                             checker.saveFormState('[data-region="grade-panel"] .gradeform');
292                             $(document).on('editor-content-restored', function() {
293                                 // If the editor has some content that has been restored
294                                 // then save the form state again for comparison.
295                                 checker.saveFormState('[data-region="grade-panel"] .gradeform');
296                             });
297                             $('[data-region="attempt-chooser"]').on('click', this._chooseAttempt.bind(this));
298                             this._addPopoutButtons('[data-region="grade-panel"] .gradeform');
299                             $(document).trigger('finish-loading-user');
300                             // Tell behat we are friends again.
301                             window.M.util.js_complete('mod-assign-loading-user');
302                         }.bind(this))
303                         .fail(notification.exception);
304                     }.bind(this)).fail(notification.exception);
305                     $('[data-region="review-panel"]').show();
306                 } else {
307                     this._region.hide();
308                     $('[data-region="review-panel"]').hide();
309                     $(document).trigger('finish-loading-user');
310                     // Tell behat we are friends again.
311                     window.M.util.js_complete('mod-assign-loading-user');
312                 }
313             }.bind(this));
314         }.bind(this)).fail(notification.exception);
315     };
317     /**
318      * Get the grade panel element.
319      *
320      * @method getPanelElement
321      * @return {jQuery}
322      */
323     GradingPanel.prototype.getPanelElement = function() {
324         return $('[data-region="grade-panel"]');
325     };
327     /**
328      * Hide the grade panel.
329      *
330      * @method collapsePanel
331      */
332     GradingPanel.prototype.collapsePanel = function() {
333         this.getPanelElement().addClass('collapsed');
334     };
336     /**
337      * Show the grade panel.
338      *
339      * @method expandPanel
340      */
341     GradingPanel.prototype.expandPanel = function() {
342         this.getPanelElement().removeClass('collapsed');
343     };
345     /**
346      * Register event listeners for the grade panel.
347      *
348      * @method registerEventListeners
349      */
350     GradingPanel.prototype.registerEventListeners = function() {
351         var docElement = $(document);
352         var region = $(this._region);
353         // Add an event listener to prevent form submission when pressing enter key.
354         region.on('submit', 'form', function(e) {
355             e.preventDefault();
356         });
358         docElement.on('user-changed', this._refreshGradingPanel.bind(this));
359         docElement.on('save-changes', this._submitForm.bind(this));
360         docElement.on('save-and-show-next', this._submitForm.bind(this, null, null, true));
361         docElement.on('reset', this._resetForm.bind(this));
363         docElement.on('save-form-state', this._saveFormState.bind(this));
365         docElement.on(GradingEvents.COLLAPSE_GRADE_PANEL, function() {
366             this.collapsePanel();
367         }.bind(this));
369         // We should expand if the review panel is collapsed.
370         docElement.on(GradingEvents.COLLAPSE_REVIEW_PANEL, function() {
371             this.expandPanel();
372         }.bind(this));
374         docElement.on(GradingEvents.EXPAND_GRADE_PANEL, function() {
375             this.expandPanel();
376         }.bind(this));
377     };
379     return GradingPanel;
380 });