question/amd/src/refresh_ui.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. * Question bank UI refresh utility
  17. *
  18. * @module core_question/refresh_ui
  19. * @copyright 2023 Catalyst IT Europe Ltd.
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. */
  22. import Fragment from 'core/fragment';
  23. import Templates from 'core/templates';
  24. export default {
  25. /**
  26. * Reload the question bank UI, retaining the current filters and sort data.
  27. *
  28. * @param {Element} uiRoot The root element of the UI to be refreshed. Must contain "component", "callback" and "contextid" in
  29. * its data attributes, to be passed to the Fragment API.
  30. * @param {URL} returnUrl The url of the current page, containing filter and sort parameters.
  31. * @return {Promise} Resolved when the refresh is complete.
  32. */
  33. refresh: (uiRoot, returnUrl) => {
  34. return new Promise((resolve, reject) => {
  35. const fragmentData = uiRoot.dataset;
  36. const viewData = {};
  37. const sortData = {};
  38. if (returnUrl) {
  39. returnUrl.searchParams.forEach((value, key) => {
  40. // Match keys like 'sortdata[fieldname]' and convert them to an array,
  41. // because the fragment API doesn't like non-alphanum argument keys.
  42. const sortItem = key.match(/sortdata\[([^\]]+)\]/);
  43. if (sortItem) {
  44. // The item returned by sortItem.pop() is the contents of the matching group, the field name.
  45. sortData[sortItem.pop()] = value;
  46. } else {
  47. viewData[key] = value;
  48. }
  49. });
  50. }
  51. viewData.sortdata = JSON.stringify(sortData);
  52. // We have to use then() there, as loadFragment doesn't appear to work with await.
  53. Fragment.loadFragment(fragmentData.component, fragmentData.callback, fragmentData.contextid, viewData)
  54. .then((html, js) => {
  55. Templates.replaceNode(uiRoot, html, js);
  56. resolve();
  57. return html;
  58. })
  59. .catch(reject);
  60. });
  61. }
  62. };