customfield/field/number/amd/src/recalculate.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. * Allows to recalculate a single value on demand
  17. *
  18. * @module customfield_number/recalculate
  19. * @author 2024 Marina Glancy
  20. * @copyright 2024 Moodle Pty Ltd <support@moodle.com>
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. import Ajax from 'core/ajax';
  24. import Notification from 'core/notification';
  25. import {addIconToContainer} from 'core/loadingicon';
  26. import Pending from 'core/pending';
  27. const SELECTORS = {
  28. wrapper: '[data-fieldtype="wrapper"]',
  29. value: '[data-fieldtype="value"]',
  30. link: '[data-fieldtype="link"]',
  31. };
  32. let initialised = false;
  33. /**
  34. * Init
  35. */
  36. export function init() {
  37. if (initialised) {
  38. return;
  39. }
  40. document.addEventListener('click', (e) => {
  41. const target = e.target.closest(SELECTORS.wrapper + " " + SELECTORS.link);
  42. if (!target) {
  43. return;
  44. }
  45. const el = target.closest(SELECTORS.wrapper).querySelector(SELECTORS.value);
  46. if (!el) {
  47. return;
  48. }
  49. e.preventDefault();
  50. const {fieldid, instanceid} = target.dataset;
  51. const pendingPromise = new Pending('recalculate_customfield_number');
  52. addIconToContainer(el).then(() => {
  53. return Ajax.call([{
  54. methodname: 'customfield_number_recalculate_value',
  55. args: {fieldid, instanceid}
  56. }])[0];
  57. }).then((data) => {
  58. el.innerHTML = data.value;
  59. return pendingPromise.resolve();
  60. }).catch(Notification.exception);
  61. });
  62. initialised = true;
  63. }