Minify highlights snippets.

This commit is contained in:
John-David Dalton
2016-09-03 09:22:57 -07:00
parent 4a5f8fa974
commit 1344803e7e
2 changed files with 57 additions and 8 deletions

View File

@@ -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, '&lt;').replace(/>/g, '&gt;'));
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>[^<]+<\/span>){2,}/g, match =>
match.replace(/<\/?span>/g, '')
));
});
const html = [

View File

@@ -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",