diff options
author | Samy Pesse <samypesse@gmail.com> | 2016-02-11 22:12:07 +0100 |
---|---|---|
committer | Samy Pesse <samypesse@gmail.com> | 2016-02-11 22:12:07 +0100 |
commit | 756694c029218510592418deb8aaf6f3b36f95c3 (patch) | |
tree | 86d938cbf6360d46845758a7cc9575ca04aa3594 /lib/page/html.js | |
parent | 669f3b39849890c48171d807225cd6eaa3c9086b (diff) | |
download | gitbook-756694c029218510592418deb8aaf6f3b36f95c3.zip gitbook-756694c029218510592418deb8aaf6f3b36f95c3.tar.gz gitbook-756694c029218510592418deb8aaf6f3b36f95c3.tar.bz2 |
Page output a simple html string
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.$); |