summaryrefslogtreecommitdiffstats
path: root/lib/page/html.js
blob: f828d11efb4f44e39d3d53a7aa6067613b662d05 (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
var _ = require('lodash');
var cheerio = require('cheerio');
var domSerializer = require('dom-serializer');
var slug = require('github-slugid');

var Promise = require('../utils/promise');

// Render a cheerio DOM as html
function renderDOM($, dom, options) {
    if (!dom && $._root && $._root.children) {
        dom = $._root.children;
    }
    options = options|| dom.options || $._options;
    return domSerializer(dom, options);
}

function HTMLPipeline(htmlString, opts) {
    _.bindAll(this);

    this.opts = _.defaults(opts || {}, {
        convertImages: true
    });

    this.$ = cheerio.load(htmlString, {
        // We should parse html without trying to normalize too much
        xmlMode: false,

        // SVG need some attributes to use uppercases
        lowerCaseAttributeNames: false,
        lowerCaseTags: false
    });
}

// Add ID to headings
HTMLPipeline.prototype.addHeadingIDs = function() {
    var that = this;

    this.$('h1,h2,h3,h4,h5,h6').each(function() {
        // Already has an ID?
        if (that.$(this).attr('id')) return;

        that.$(this).attr('id', slug(that.$(this).text()));
    });
};

// Write content to the pipeline
HTMLPipeline.prototype.output = function() {
    var that = this;

    return Promise()
    .then(this.addHeadingIDs)
    .then(function() {
        return renderDOM(that.$);
    });
};

module.exports = HTMLPipeline;