diff --git a/lib/main/build-site.js b/lib/main/build-site.js index e8b9da4f6..f1ea66a3e 100644 --- a/lib/main/build-site.js +++ b/lib/main/build-site.js @@ -3,6 +3,7 @@ const _ = require('lodash'); const fs = require('fs'); const marky = require('marky-markdown'); +const minify = require('html-minifier').minify; const path = require('path'); const util = require('../common/util'); @@ -14,24 +15,33 @@ const highlights = [ 'comment', 'constant', 'delimiter', - 'html', - 'js', 'method', 'modifier', 'numeric', - 'shell', - 'source', 'string', - 'text', 'type' ]; +const hlTypes = [ + 'html', + 'js', + 'shell' +]; + +const hlSources = [ + 'highlight', + 'source', + 'text' +]; + function build(type) { const markdown = fs // Load markdown. .readFileSync(readmePath, 'utf8') // Uncomment docdown HTML hints. - .replace(/(<)!--\s*|\s*--(>)/g, '$1$2'); + .replace(/(<)!--\s*|\s*--(>)/g, '$1$2') + // Escape HTML markup in usage examples. + .replace(/```js[\s\S]+?```/g, m => m.replace(//g, '>')); const $ = marky(markdown, { 'sanitize': false }); const $header = $('h1').first().remove(); @@ -74,9 +84,47 @@ function build(type) { // Cleanup highlights class names. $('.highlight [class]').each(function() { const $el = $(this); - const className = _.intersection($el.attr('class').split(/\s+/), highlights).join(' '); + const names = $el.attr('class').split(/\s+/); + const attr = _.intersection(names, highlights).join(' '); - $el.attr('class', className || null); + if (!_.isEmpty(_.intersection(names, hlSources)) && + !_.isEmpty(_.intersection(names, hlTypes))) { + return; + } + $el.attr('class', attr || null); + }); + + // Unwrap elements containing only text. + $('.highlight :not([class])').each(function() { + const $el = $(this); + if (_.every($(el).children(), ['type', 'text'])) { + $el.replaceWith($el.text()); + } + }); + + // Consolidate hightlights comments. + $('.highlight [class~="comment"] > [class~="comment"]').each(function() { + const $parent = $(this).parent(); + $parent.text($parent.text()); + }); + + // Minify hightlights snippets. + $('.highlight').each(function() { + const $div = $(this); + $div.html(minify($div.html(), { + 'collapseBooleanAttributes': true, + 'collapseInlineTagWhitespace': true, + 'collapseWhitespace': true, + 'removeAttributeQuotes': true, + 'removeComments': true, + 'removeEmptyAttributes': true, + 'removeEmptyElements': true, + 'removeOptionalTags': true, + 'removeRedundantAttributes': true + }) + .replace(/(?:[^<]+<\/span>){2,}/g, match => + match.replace(/<\/?span>/g, '') + )); }); const html = [ diff --git a/package.json b/package.json index 9cc09e303..997ed51f8 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "ecstatic": "^2.1.0", "fs-extra": "~0.30.0", "glob": "^7.0.6", + "html-minifier": "^3.0.2", "istanbul": "0.4.5", "jquery": "^3.1.0", "jscs": "^3.0.7",