lib/amd/src/modal_registry.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. * A registry for the different types of modal.
  17. *
  18. * @module core/modal_registry
  19. * @class modal_registry
  20. * @copyright 2016 Ryan Wyllie <ryan@moodle.com>
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. import * as Notification from 'core/notification';
  24. import * as Prefetch from 'core/prefetch';
  25. // A singleton registry for all modules to access. Allows types to be
  26. // added at runtime.
  27. const registry = new Map();
  28. /**
  29. * Get a registered type of modal.
  30. *
  31. * @method get
  32. * @param {string} type The type of modal to get
  33. * @return {object} The registered config for the modal
  34. */
  35. export const get = (type) => registry.get(type);
  36. /**
  37. * Register a modal with the registry.
  38. *
  39. * @method register
  40. * @param {string} type The type of modal (must be unique)
  41. * @param {function} module The modal module (must be a constructor function of type core/modal)
  42. * @param {string} template The template name of the modal
  43. */
  44. export const register = (type, module, template) => {
  45. const existing = get(type);
  46. if (existing && existing.module !== module) {
  47. Notification.exception({
  48. message: `Modal of type '${type}' is already registered`,
  49. });
  50. }
  51. if (!module || typeof module !== 'function') {
  52. Notification.exception({message: "You must provide a modal module"});
  53. }
  54. if (!template) {
  55. Notification.exception({message: "You must provide a modal template"});
  56. }
  57. registry.set(type, {module, template});
  58. // Prefetch the template.
  59. Prefetch.prefetchTemplate(template);
  60. };
  61. export default {
  62. register,
  63. get,
  64. };