Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for AMPHTML. #59

Merged
merged 1 commit into from
Sep 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,17 @@ Minified:

Collapses boolean attributes (like `disabled`) to the minimized form.

##### Options

If your document uses [AMP](https://www.ampproject.org/), set the `amphtml` flag
to collapse additonal, AMP-specific boolean attributes:

```Json
"collapseBooleanAttributes": {
"amphtml": true
}
```

##### Side effects

This module could break your styles or JS if you use selectors with attributes:
Expand Down
18 changes: 18 additions & 0 deletions lib/helpers.es6
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
const ampBoilerplateAttributes = [
'amp-boilerplate',
'amp4ads-boilerplate',
'amp4email-boilerplate'
];

export function isAmpBoilerplate(node) {
if (!node.attrs) {
return false;
}
for (let attr of ampBoilerplateAttributes) {
if (attr in node.attrs) {
return true;
}
}
return false;
}

export function isComment(content) {
return (content || '').trim().search('<!--') === 0;
}
Expand Down
4 changes: 3 additions & 1 deletion lib/htmlnano.es6
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ const defaultOptions = {
removeEmptyAttributes: true,
removeRedundantAttributes: false,
collapseWhitespace: 'conservative',
collapseBooleanAttributes: true,
collapseBooleanAttributes: {
amphtml: false,
},
mergeStyles: true,
mergeScripts: true,
minifyCss: {
Expand Down
68 changes: 65 additions & 3 deletions lib/modules/collapseBooleanAttributes.es6
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Source: https://github.com/kangax/html-minifier/issues/63
const booleanAttributes = new Set([
const htmlBooleanAttributes = new Set([
'allowfullscreen',
'allowpaymentrequest',
'allowtransparency',
'async',
'autofocus',
'autoplay',
Expand Down Expand Up @@ -43,11 +45,71 @@ const booleanAttributes = new Set([
'visible'
]);

const amphtmlBooleanAttributes = new Set([
'⚡',
'amp',
'⚡4ads',
'amp4ads',
'⚡4email',
'amp4email',

export default function collapseBooleanAttributes(tree) {
'amp-custom',
'amp-boilerplate',
'amp4ads-boilerplate',
'amp4email-boilerplate',

'allow-blocked-ranges',
'amp-access-hide',
'amp-access-template',
'amp-keyframes',
'animate',
'arrows',
'data-block-on-consent',
'data-enable-refresh',
'data-multi-size',
'date-template',
'disable-double-tap',
'disable-session-states',
'disableremoteplayback',
'dots',
'expand-single-section',
'expanded',
'fallback',
'first',
'fullscreen',
'inline',
'lightbox',
'noaudio',
'noautoplay',
'noloading',
'once',
'open-after-clear',
'open-after-select',
'open-button',
'placeholder',
'preload',
'reset-on-refresh',
'reset-on-resize',
'resizable',
'rotate-to-fullscreen',
'second',
'standalone',
'stereo',
'submit-error',
'submit-success',
'submitting',
'subscriptions-actions',
'subscriptions-dialog'
]);


export default function collapseBooleanAttributes(tree, options, moduleOptions) {
tree.match({attrs: true}, node => {
for (let attrName of Object.keys(node.attrs)) {
if (booleanAttributes.has(attrName)) {
if (htmlBooleanAttributes.has(attrName)) {
node.attrs[attrName] = true;
}
if (moduleOptions.amphtml && node.attrs[attrName] === '' && amphtmlBooleanAttributes.has(attrName)) {
node.attrs[attrName] = true;
}
}
Expand Down
6 changes: 6 additions & 0 deletions lib/modules/mergeStyles.es6
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isAmpBoilerplate } from '../helpers';

/* Merge multiple <style> into one */
export default function mergeStyles(tree) {
const styleNodes = {};
Expand All @@ -10,6 +12,10 @@ export default function mergeStyles(tree) {
return node;
}

if (isAmpBoilerplate(node)) {
return node;
}

const styleType = nodeAttrs.type || 'text/css';
const styleMedia = nodeAttrs.media || 'all';
const styleKey = styleType + '_' + styleMedia;
Expand Down
8 changes: 7 additions & 1 deletion lib/modules/minifyCss.es6
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { isAmpBoilerplate } from '../helpers';
import cssnano from 'cssnano';

/** Minify CSS with cssnano */
export default function minifyCss(tree, options, cssnanoOptions) {
let promises = [];
tree.walk(node => {
if (node.tag === 'style' && node.content && node.content.length) {
if (isStyleNode(node)) {
promises.push(processStyleNode(node, cssnanoOptions));
} else if (node.attrs && node.attrs.style) {
promises.push(processStyleAttr(node, cssnanoOptions));
Expand All @@ -17,6 +18,11 @@ export default function minifyCss(tree, options, cssnanoOptions) {
}


function isStyleNode(node) {
return node.tag === 'style' && !isAmpBoilerplate(node) && node.content && node.content.length;
}


function processStyleNode(styleNode, cssnanoOptions) {
return cssnano
.process(Array.isArray(styleNode.content) ? styleNode.content.join(' ') : styleNode.content, cssnanoOptions)
Expand Down
14 changes: 13 additions & 1 deletion test/helpers.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
import expect from 'expect';
import { isComment, isConditionalComment } from '../lib/helpers';
import { isAmpBoilerplate, isComment, isConditionalComment } from '../lib/helpers';

describe('[helpers]', () => {
context('isAmpBoilerplate()', () => {
it('should detect AMP boilerplate', () => {
expect(isAmpBoilerplate({
tag: 'style',
attrs: {
'amp-boilerplate': ''
},
})).toBe(true);
expect(isAmpBoilerplate({ tag: 'style' })).toBe(false);
});
});

context('isComment()', () => {
it('should detect HTML comments', () => {
expect(isComment(' <!-- comment --> ')).toBe(true);
Expand Down
18 changes: 17 additions & 1 deletion test/modules/collapseBooleanAttributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { init } from '../htmlnano';


describe('collapseBooleanAttributes', () => {
const options = {collapseBooleanAttributes: true};
const options = {collapseBooleanAttributes: {}};
const optionsWithAmp = {collapseBooleanAttributes: { amphtml: true }};

it('should collapse a boolean attribute with value', () => {
return init(
Expand All @@ -29,4 +30,19 @@ describe('collapseBooleanAttributes', () => {
options
);
});


it('should collapse AMP boolean attributes with empty value', () => {
return init(
'<script defer=""></script>' +
'<style amp-custom=""></style>' +
'<amp-video preload="metadata"></amp-video>',

'<script defer></script>' +
'<style amp-custom></style>' +
'<amp-video preload="metadata"></amp-video>',

optionsWithAmp
);
});
});
24 changes: 24 additions & 0 deletions test/modules/mergeStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,28 @@ describe('mergeStyles', () => {
html, html, options
);
});


it('should preserve amp-custom', () => {
return init(
'<style amp-custom>h1 { color: red }</style>' +
'<div>hello</div>' +
'<style amp-custom>div { color: blue }</style>',

'<style amp-custom="">h1 { color: red } div { color: blue }</style>' +
'<div>hello</div>',

options
);
});


it('should ignore AMP boilerplate', () => {
const html = `<style>h1 { color: red }</style>
<div></div>
<style amp-boilerplate="">div { color: blue }</style>`;
return init(
html, html, options
);
});
});
10 changes: 10 additions & 0 deletions test/modules/minifyCss.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,14 @@ describe('minifyCss', () => {
options
);
});


it('should ignore AMP boilerplate', () => {
const amphtml = '<style amp-boilerplate="">\nh1{color:red}</style>';
return init(
amphtml,
amphtml,
options
);
});
});