summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-html/src/dom.js
blob: 9c5e070784960ab7e1555eb58dbf392103c12a37 (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
const cheerio = require('cheerio');

/**
 * Parse an HTML string and return its content.
 * @param {String}
 * @return {cheerio.DOM}
 */
function parse(html) {
    const $ = cheerio.load(html);
    const $el = $('html, body').first();

    return $el.length > 0 ? $el : $;
}

/**
 * Return main element for a DOM.
 * @param {cheerio.DOM}
 * @return {cheerio.Node}
 */
function root($) {
    const $el = $('html, body, > div').first();
    return $el.length > 0 ? $el : $.root();
}

/**
 * Return text node of an element.
 * @param {cheerio.Node}
 * @return {String}
 */
function textNode($el) {
    return $el.children.reduce(
        (text, e) => {
            if (e.type == 'text') text += e.data;
            return text;
        },
        ''
    );
}

/**
 * Cleanup a DOM by removing all useless divs.
 * @param {cheerio.Node}
 * @param {cheerio.DOM}
 * @return {cheerio.Node}
 */
function cleanup($el, $) {
    $el.find('div').each(function() {
        const $div = $(this);
        cleanup($div, $);

        $div.replaceWith($div.html());
    });

    return $el;
}

module.exports = {
    parse,
    textNode,
    root,
    cleanup
};