all files / posthtml-parser/ index.js

82.5% Statements 33/40
66.67% Branches 12/18
87.5% Functions 7/8
82.05% Lines 32/39
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                  62×                                   24×   24×   24×   24×     24×   24×     23× 23×     23×     39× 39×     37× 37×             24× 19× 19×        
/*jshint -W082 */
var htmlparser = require('htmlparser2');
 
/**
 * Parse html to PostHTMLTree
 * @param  {String} html
 * @return {Object}
 */
module.exports = function postHTMLParser(html) {
    var bufArray = [],
        results = [];
 
    bufArray.last = function() {
        return this[this.length - 1];
    };
 
    var parser = new htmlparser.Parser({
        onprocessinginstruction: function(name, data) {
            name === '!doctype' && results.push('<' + data + '>');
        },
        oncomment: function(data) {
            var comment = '<!--' + data + '-->',
                last = bufArray.last();
 
            if (!last) {
                results.push(comment);
                return;
            }
 
            last.content || (last.content = []);
            last.content.push(comment);
        },
        onopentag: function(tag, attrs) {
            var buf = {};
 
            buf.tag = tag;
 
            if (!isEmpty(attrs)) buf.attrs = attrs;
 
            bufArray.push(buf);
        },
        onclosetag: function() {
            var buf = bufArray.pop();
 
            if (bufArray.length === 0) {
                results.push(buf);
                return;
            }
 
            var last = bufArray.last();
            Iif (!(last.content instanceof Array)) {
                last.content = [];
            }
            last.content.push(buf);
        },
        ontext: function(text) {
            var last = bufArray.last();
            if (!last) {
                results.push(text);
                return;
            }
 
            last.content || (last.content = []);
            last.content.push(text);
        }
    });
 
    parser.write(html);
    parser.end();
 
    return results;
};
 
function isEmpty(obj) {
    for (var key in obj) {
        Eif (Object.prototype.hasOwnProperty.call(obj, key)) {
            return false;
        }
    }
    return true;
}