lib/amd/src/normalise.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. * Normalisation helpers.
  17. *
  18. * @module core/normalise
  19. * @copyright 2020 Andrew Nicols <andrew@nicols.co.uk>
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. */
  22. import jQuery from 'jquery';
  23. /**
  24. * Normalise a list of Nodes into an Array of Nodes.
  25. *
  26. * @method getList
  27. * @param {(Array|jQuery|NodeList|HTMLElement)} nodes
  28. * @returns {HTMLElement[]}
  29. */
  30. export const getList = nodes => {
  31. if (nodes instanceof HTMLElement) {
  32. // A single record to conver to a NodeList.
  33. return [nodes];
  34. }
  35. if (nodes instanceof Array) {
  36. // A single record to conver to a NodeList.
  37. return nodes;
  38. }
  39. if (nodes instanceof NodeList) {
  40. // Already a NodeList.
  41. return Array.from(nodes);
  42. }
  43. if (nodes instanceof jQuery) {
  44. // A jQuery object to a NodeList.
  45. return nodes.get();
  46. }
  47. // Fallback to just having a go.
  48. return Array.from(nodes);
  49. };
  50. /**
  51. * Return the first element in a list of normalised Nodes.
  52. *
  53. * @param {Array|jQuery|NodeList|HTMLElement} nodes the unmormalised list of nodes
  54. * @returns {HTMLElement|undefined} the first list element
  55. */
  56. export const getFirst = nodes => {
  57. const list = getList(nodes);
  58. return list[0];
  59. };
  60. /**
  61. * Normalise a single node into an HTMLElement.
  62. *
  63. * @param {jQuery|Y.Node|HTMLElement} node The node to normalise
  64. * @returns {HTMLElement}
  65. */
  66. export const getElement = (node) => {
  67. if (node instanceof HTMLElement) {
  68. return node;
  69. }
  70. if (node?._node) {
  71. // This is likely a YUI Node.
  72. // We can use (node instanceof Y.Node) but we would have to load YUI to do some.
  73. return node._node;
  74. }
  75. if (node instanceof jQuery && node.length > 0) {
  76. return node.get(0);
  77. }
  78. return null;
  79. };