Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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