diff options
Diffstat (limited to 'lib/page/html.js')
-rw-r--r-- | lib/page/html.js | 36 |
1 files changed, 32 insertions, 4 deletions
diff --git a/lib/page/html.js b/lib/page/html.js index f828d11..b19d5ed 100644 --- a/lib/page/html.js +++ b/lib/page/html.js @@ -4,6 +4,7 @@ var domSerializer = require('dom-serializer'); var slug = require('github-slugid'); var Promise = require('../utils/promise'); +var location = require('../utils/location'); // Render a cheerio DOM as html function renderDOM($, dom, options) { @@ -18,7 +19,10 @@ function HTMLPipeline(htmlString, opts) { _.bindAll(this); this.opts = _.defaults(opts || {}, { - convertImages: true + convertImages: true, + + // Calcul new href for a relative link + onRelativeLink: _.identity }); this.$ = cheerio.load(htmlString, { @@ -31,15 +35,38 @@ function HTMLPipeline(htmlString, opts) { }); } +// Normalize links +HTMLPipeline.prototype.normalizeLinks = function() { + var that = this; + + this.$('a').each(function() { + var $a = that.$(this); + + var href = $a.attr('href'); + if (!href) return; + + if (location.isAnchor(href)) { + // Don't "change" anchor links + } else if (location.isRelative(href)) { + $a.attr('href', that.opts.onRelativeLink(href)); + } else { + // External links + $a.attr('target', '_blank'); + } + + }); +}; + // 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; + var $h = that.$(this); - that.$(this).attr('id', slug(that.$(this).text())); + // Already has an ID? + if ($h.attr('id')) return; + $h.attr('id', slug($h.text())); }); }; @@ -48,6 +75,7 @@ HTMLPipeline.prototype.output = function() { var that = this; return Promise() + .then(this.normalizeLinks) .then(this.addHeadingIDs) .then(function() { return renderDOM(that.$); |