summaryrefslogtreecommitdiffstats
path: root/toolkit/components/microformats/test/lib/domutils.js
blob: 57269de9788c889dbccfdfbabc4459384fbd29ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
   dom utilities
   The purpose of this module is to abstract DOM functions away from the main parsing modules of the library.
   It was created so the file can be replaced in node.js environment to make use of different types of light weight node.js DOM's
   such as 'cherrio.js'. It also contains a number of DOM utilities which are used throughout the parser such as: 'getDescendant'

   Copyright (C) 2010 - 2015 Glenn Jones. All Rights Reserved.
   MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
   Dependencies  utilities.js

*/


var Modules = (function (modules) {

    modules.domUtils = {

        // blank objects for DOM
        document: null,
        rootNode: null,


        /**
         * gets DOMParser object
         *
         * @return {Object || undefined}
         */
        getDOMParser: function () {
            if (typeof DOMParser === undefined) {
                try {
                    return Components.classes["@mozilla.org/xmlextras/domparser;1"]
                        .createInstance(Components.interfaces.nsIDOMParser);
                } catch (e) {
                    return undefined;
                }
            } else {
                return new DOMParser();
            }
        },


        /**
         * configures what are the base DOM objects for parsing
         *
         * @param  {Object} options
         * @return {DOM Node} node
         */
        getDOMContext: function( options ){

            // if a node is passed
            if(options.node){
                this.rootNode = options.node;
            }


            // if a html string is passed
            if(options.html){
                //var domParser = new DOMParser();
                var domParser = this.getDOMParser();
                this.rootNode = domParser.parseFromString( options.html, 'text/html' );
            }


            // find top level document from rootnode
            if(this.rootNode !== null){
                if(this.rootNode.nodeType === 9){
                    this.document = this.rootNode;
                    this.rootNode = modules.domUtils.querySelector(this.rootNode, 'html');
                }else{
                    // if it's DOM node get parent DOM Document
                    this.document = modules.domUtils.ownerDocument(this.rootNode);
                }
            }


            // use global document object
            if(!this.rootNode && document){
                this.rootNode = modules.domUtils.querySelector(document, 'html');
                this.document = document;
            }


            if(this.rootNode && this.document){
                return {document: this.document, rootNode: this.rootNode};
            }

            return {document: null, rootNode: null};
        },



       /**
        * gets the first DOM node
        *
        * @param  {Dom Document}
        * @return {DOM Node} node
        */
        getTopMostNode: function( node ){
            //var doc = this.ownerDocument(node);
            //if(doc && doc.nodeType && doc.nodeType === 9 && doc.documentElement){
            //  return doc.documentElement;
            //}
            return node;
        },



        /**
         * abstracts DOM ownerDocument
         *
         * @param  {DOM Node} node
         * @return {Dom Document}
         */
        ownerDocument: function(node){
            return node.ownerDocument;
        },


        /**
         * abstracts DOM textContent
         *
         * @param  {DOM Node} node
         * @return {String}
         */
        textContent: function(node){
            if(node.textContent){
                return node.textContent;
            }else if(node.innerText){
                return node.innerText;
            }
            return '';
        },


        /**
         * abstracts DOM innerHTML
         *
         * @param  {DOM Node} node
         * @return {String}
         */
        innerHTML: function(node){
            return node.innerHTML;
        },


        /**
         * abstracts DOM hasAttribute
         *
         * @param  {DOM Node} node
         * @param  {String} attributeName
         * @return {Boolean}
         */
        hasAttribute: function(node, attributeName) {
            return node.hasAttribute(attributeName);
        },


        /**
         * does an attribute contain a value
         *
         * @param  {DOM Node} node
         * @param  {String} attributeName
         * @param  {String} value
         * @return {Boolean}
         */
        hasAttributeValue: function(node, attributeName, value) {
            return (this.getAttributeList(node, attributeName).indexOf(value) > -1);
        },


        /**
         * abstracts DOM getAttribute
         *
         * @param  {DOM Node} node
         * @param  {String} attributeName
         * @return {String || null}
         */
        getAttribute: function(node, attributeName) {
            return node.getAttribute(attributeName);
        },


        /**
         * abstracts DOM setAttribute
         *
         * @param  {DOM Node} node
         * @param  {String} attributeName
         * @param  {String} attributeValue
         */
        setAttribute: function(node, attributeName, attributeValue){
            node.setAttribute(attributeName, attributeValue);
        },


        /**
         * abstracts DOM removeAttribute
         *
         * @param  {DOM Node} node
         * @param  {String} attributeName
         */
        removeAttribute: function(node, attributeName) {
            node.removeAttribute(attributeName);
        },


        /**
         * abstracts DOM getElementById
         *
         * @param  {DOM Node || DOM Document} node
         * @param  {String} id
         * @return {DOM Node}
         */
        getElementById: function(docNode, id) {
            return docNode.querySelector( '#' + id );
        },


        /**
         * abstracts DOM querySelector
         *
         * @param  {DOM Node || DOM Document} node
         * @param  {String} selector
         * @return {DOM Node}
         */
        querySelector: function(docNode, selector) {
            return docNode.querySelector( selector );
        },


        /**
         * get value of a Node attribute as an array
         *
         * @param  {DOM Node} node
         * @param  {String} attributeName
         * @return {Array}
         */
        getAttributeList: function(node, attributeName) {
            var out = [],
                attList;

            attList = node.getAttribute(attributeName);
            if(attList && attList !== '') {
                if(attList.indexOf(' ') > -1) {
                    out = attList.split(' ');
                } else {
                    out.push(attList);
                }
            }
            return out;
        },


        /**
         * gets all child nodes with a given attribute
         *
         * @param  {DOM Node} node
         * @param  {String} attributeName
         * @return {NodeList}
         */
        getNodesByAttribute: function(node, attributeName) {
            var selector = '[' + attributeName + ']';
            return node.querySelectorAll(selector);
        },


        /**
         * gets all child nodes with a given attribute containing a given value
         *
         * @param  {DOM Node} node
         * @param  {String} attributeName
         * @return {DOM NodeList}
         */
        getNodesByAttributeValue: function(rootNode, name, value) {
            var arr = [],
                x = 0,
                i,
                out = [];

            arr = this.getNodesByAttribute(rootNode, name);
            if(arr) {
                i = arr.length;
                while(x < i) {
                    if(this.hasAttributeValue(arr[x], name, value)) {
                        out.push(arr[x]);
                    }
                    x++;
                }
            }
            return out;
        },


        /**
         * gets attribute value from controlled list of tags
         *
         * @param  {Array} tagNames
         * @param  {String} attributeName
         * @return {String || null}
         */
        getAttrValFromTagList: function(node, tagNames, attributeName) {
            var i = tagNames.length;

            while(i--) {
                if(node.tagName.toLowerCase() === tagNames[i]) {
                    var attrValue = this.getAttribute(node, attributeName);
                    if(attrValue && attrValue !== '') {
                        return attrValue;
                    }
                }
            }
            return null;
        },


        /**
         * get node if it has no siblings. CSS equivalent is :only-child
         *
         * @param  {DOM Node} rootNode
         * @param  {Array} tagNames
         * @return {DOM Node || null}
         */
        getSingleDescendant: function(node){
            return this.getDescendant( node, null, false );
        },


        /**
         * get node if it has no siblings of the same type. CSS equivalent is :only-of-type
         *
         * @param  {DOM Node} rootNode
         * @param  {Array} tagNames
         * @return {DOM Node || null}
         */
        getSingleDescendantOfType: function(node, tagNames){
            return this.getDescendant( node, tagNames, true );
        },


        /**
         * get child node limited by presence of siblings - either CSS :only-of-type or :only-child
         *
         * @param  {DOM Node} rootNode
         * @param  {Array} tagNames
         * @return {DOM Node || null}
         */
        getDescendant: function( node, tagNames, onlyOfType ){
            var i = node.children.length,
                countAll = 0,
                countOfType = 0,
                child,
                out = null;

            while(i--) {
                child = node.children[i];
                if(child.nodeType === 1) {
                    if(tagNames){
                        // count just only-of-type
                        if(this.hasTagName(child, tagNames)){
                            out = child;
                            countOfType++;
                        }
                    }else{
                        // count all elements
                        out = child;
                        countAll++;
                    }
                }
            }
            if(onlyOfType === true){
                return (countOfType === 1)? out : null;
            }else{
                return (countAll === 1)? out : null;
            }
        },


        /**
         * is a node one of a list of tags
         *
         * @param  {DOM Node} rootNode
         * @param  {Array} tagNames
         * @return {Boolean}
         */
        hasTagName: function(node, tagNames){
            var i = tagNames.length;
            while(i--) {
                if(node.tagName.toLowerCase() === tagNames[i]) {
                    return true;
                }
            }
            return false;
        },


        /**
         * abstracts DOM appendChild
         *
         * @param  {DOM Node} node
         * @param  {DOM Node} childNode
         * @return {DOM Node}
         */
        appendChild: function(node, childNode){
            return node.appendChild(childNode);
        },


        /**
         * abstracts DOM removeChild
         *
         * @param  {DOM Node} childNode
         * @return {DOM Node || null}
         */
        removeChild: function(childNode){
            if (childNode.parentNode) {
                return childNode.parentNode.removeChild(childNode);
            }else{
                return null;
            }
        },


        /**
         * abstracts DOM cloneNode
         *
         * @param  {DOM Node} node
         * @return {DOM Node}
         */
        clone: function(node) {
            var newNode = node.cloneNode(true);
            newNode.removeAttribute('id');
            return newNode;
        },


        /**
         * gets the text of a node
         *
         * @param  {DOM Node} node
         * @return {String}
         */
        getElementText: function( node ){
            if(node && node.data){
                return node.data;
            }else{
                return '';
            }
        },


        /**
         * gets the attributes of a node - ordered by sequence in html
         *
         * @param  {DOM Node} node
         * @return {Array}
         */
        getOrderedAttributes: function( node ){
            var nodeStr = node.outerHTML,
                attrs = [];

            for (var i = 0; i < node.attributes.length; i++) {
                var attr = node.attributes[i];
                    attr.indexNum = nodeStr.indexOf(attr.name);

                attrs.push( attr );
            }
            return attrs.sort( modules.utils.sortObjects( 'indexNum' ) );
        },


        /**
         * decodes html entities in given text
         *
         * @param  {DOM Document} doc
         * @param  String} text
         * @return {String}
         */
        decodeEntities: function( doc, text ){
            //return text;
            return doc.createTextNode( text ).nodeValue;
        },


        /**
         * clones a DOM document
         *
         * @param  {DOM Document} document
         * @return {DOM Document}
         */
        cloneDocument: function( document ){
            var newNode,
                newDocument = null;

            if( this.canCloneDocument( document )){
                newDocument = document.implementation.createHTMLDocument('');
                newNode = newDocument.importNode( document.documentElement, true );
                newDocument.replaceChild(newNode, newDocument.querySelector('html'));
            }
            return (newNode && newNode.nodeType && newNode.nodeType === 1)? newDocument : document;
        },


        /**
         * can environment clone a DOM document
         *
         * @param  {DOM Document} document
         * @return {Boolean}
         */
        canCloneDocument: function( document ){
            return (document && document.importNode && document.implementation && document.implementation.createHTMLDocument);
        },


        /**
         * get the child index of a node. Used to create a node path
         *
         *   @param  {DOM Node} node
         *   @return {Int}
         */
        getChildIndex: function (node) {
            var parent = node.parentNode,
                i = -1,
                child;
            while (parent && (child = parent.childNodes[++i])){
                 if (child === node){
                     return i;
                 }
            }
            return -1;
        },


        /**
         * get a node's path
         *
         *   @param  {DOM Node} node
         *   @return {Array}
         */
        getNodePath: function  (node) {
            var parent = node.parentNode,
                path = [],
                index = this.getChildIndex(node);

          if(parent && (path = this.getNodePath(parent))){
               if(index > -1){
                   path.push(index);
               }
          }
          return path;
        },


        /**
         * get a node from a path.
         *
         *   @param  {DOM document} document
         *   @param  {Array} path
         *   @return {DOM Node}
         */
        getNodeByPath: function (document, path) {
            var node = document.documentElement,
                i = 0,
                index;
          while ((index = path[++i]) > -1){
              node = node.childNodes[index];
          }
          return node;
        },


        /**
         * get an array/nodeList of child nodes
         *
         *   @param  {DOM node} node
         *   @return {Array}
         */
        getChildren: function( node ){
            return node.children;
        },


        /**
         * create a node
         *
         *   @param  {String} tagName
         *   @return {DOM node}
         */
        createNode: function( tagName ){
            return this.document.createElement(tagName);
        },


        /**
         * create a node with text content
         *
         *   @param  {String} tagName
         *   @param  {String} text
         *   @return {DOM node}
         */
        createNodeWithText: function( tagName, text ){
            var node = this.document.createElement(tagName);
            node.innerHTML = text;
            return node;
        }



    };

    return modules;

} (Modules || {}));