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