zhangjian
2023-06-05 0976d2d0f90cff460cedfdc8bd74e98c2c31a58c
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
'use strict';
 
var htmlparser = require('htmlparser2');
var isObject = require('isobject');
 
/**
 * @see https://github.com/fb55/htmlparser2/wiki/Parser-options
 */
var defaultOptions = {lowerCaseTags: false, lowerCaseAttributeNames: false};
 
/**
 * Parse html to PostHTMLTree
 * @param  {String} html
 * @param  {Object} [options=defaultOptions]
 * @return {PostHTMLTree}
 */
function postHTMLParser(html, options) {
    var bufArray = [],
        results = [];
 
    bufArray.last = function() {
        return this[this.length - 1];
    };
 
    var parser = new htmlparser.Parser({
        onprocessinginstruction: function(name, data) {
            if (name.toLowerCase() === '!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 = { tag: tag };
 
            if (Object.keys(attrs).length) {
                buf.attrs = attrs;
            }
 
            bufArray.push(buf);
        },
        onclosetag: function() {
            var buf = bufArray.pop();
 
            if (!bufArray.length) {
                results.push(buf);
                return;
            }
 
            var last = bufArray.last();
            if (!Array.isArray(last.content)) {
                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);
        }
    }, options || defaultOptions);
 
    parser.write(html);
    parser.end();
 
    return results;
}
 
function parserWrapper() {
    var option;
 
    function parser(html) {
        var opt = option || defaultOptions;
        return postHTMLParser(html, opt);
    }
 
    if (arguments.length === 1 && isObject(arguments[0])) {
        option = arguments[0];
        return parser;
    }
 
    option = arguments[1];
    return parser(arguments[0]);
}
 
module.exports = parserWrapper;
module.exports.defaultOptions = defaultOptions;