forked from mainmatter/ember-hbs-minifier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhbs-minifier-plugin.js
274 lines (232 loc) · 7.82 KB
/
hbs-minifier-plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
'use strict';
/* eslint-env node */
const leadingWhiteSpace = /^[ \t\r\n]+/;
const trailingWhiteSpace = /[ \t\r\n]+$/;
const WHITESPACE = /^[ \t\r\n]+$/;
function createGlimmerPlugin(config) {
normalizeConfig(config);
// in this stack we track the nodes that cause us to skip the minification
// e.g. `{{#no-minify}} ... {{/no-minify}}` blocks or `<pre></pre>` tags
// depending on the configuration
let skipStack = [];
function insideSkipBlock() {
return skipStack.length !== 0;
}
return {
name: 'hbs-minifier-plugin',
visitor: {
TextNode(node) {
if (!insideSkipBlock()) {
// replace leading and trailing whitespace with a single whitespace character
node.chars = node.chars.replace(leadingWhiteSpace, ' ').replace(trailingWhiteSpace, ' ');
}
},
AttrNode: {
enter(node) {
skipStack.push(node);
if (node.name === 'class') {
if (node.value.type === 'TextNode') {
node.value.chars = node.value.chars
.replace(leadingWhiteSpace, '')
.replace(trailingWhiteSpace, '')
.replace(/[ \t\r\n]+/g, ' ');
} else if (node.value.type === 'ConcatStatement') {
let { parts } = node.value;
parts.forEach((part, i) => {
if (part.type === 'TextNode') {
let isFirst = i === 0;
let isLast = i === parts.length - 1;
part.chars = part.chars
.replace(leadingWhiteSpace, isFirst ? '' : ' ')
.replace(trailingWhiteSpace, isLast ? '' : ' ')
.replace(/[ \t\r\n]+/g, ' ');
}
});
node.value.parts = node.value.parts
.filter(part => part.type !== 'TextNode' || part.chars !== '');
}
}
},
exit(node) {
if (skipStack[skipStack.length - 1] === node) {
skipStack.pop();
}
},
},
BlockStatement: {
enter(node) {
if (shouldSkipBlockStatement(node, config)) {
skipStack.push(node);
}
},
exit(node) {
if (skipStack[skipStack.length - 1] === node) {
skipStack.pop();
}
},
},
Program: {
enter(node) {
if (!insideSkipBlock()) {
removeSurroundingWhitespaceNodes(node.body);
}
},
exit(node) {
node.body = stripNoMinifyBlocks(node.body);
},
},
ElementNode: {
enter(node) {
if (shouldSkipElementNode(node, config) || shouldSkipClass(node, config)) {
skipStack.push(node);
}
if (!insideSkipBlock()) {
removeSurroundingWhitespaceNodes(node.children);
}
},
exit(node) {
node.children = stripNoMinifyBlocks(node.children);
if (skipStack[skipStack.length - 1] === node) {
skipStack.pop();
}
}
},
}
};
}
function createRegistryPlugin(config) {
return class HBSMinifierPlugin {
transform(ast) {
let startLoc = ast.loc ? ast.loc.start : {};
/*
Checking for line and column to avoid registering the plugin for ProgramNode inside a BlockStatement since transform is called for all ProgramNodes in Ember 2.15.X. Removing this would result in minifying all the TextNodes.
*/
if (startLoc.line !== 1 || startLoc.column !== 0) {
return ast;
}
let plugin = createGlimmerPlugin(config);
this.syntax.traverse(ast, plugin.visitor);
return ast;
}
};
}
function isWhitespaceTextNode(node) {
return node && node.type === 'TextNode' && WHITESPACE.test(node.chars);
}
function stripNoMinifyBlocks(nodes) {
return nodes.map(node => {
if (node.type === 'BlockStatement' && node.path.original === 'no-minify') {
return node.program.body;
}
return node;
}).reduce((a, b) => a.concat(b), []);
}
function removeSurroundingWhitespaceNodes(nodes) {
// remove leading text node if it contains only whitespace
if (isWhitespaceTextNode(nodes[0])) {
nodes.shift();
}
// remove trailing text node if it contains only whitespace
if (isWhitespaceTextNode(nodes[nodes.length - 1])) {
nodes.pop();
}
}
function isClassIncluded(chars, classes) {
chars = (chars || '').trim().split(' ');
return chars.some((char) => {
return classes.indexOf(char) !== -1;
});
}
function canTrimWhiteSpaceBasedOnClassNames(value, configClassNames) {
/*
1. If no value is provided for class, the we can minify the content.
2. If all classNames need to be preserved, then we must preserve the whitespace.
3. If a string specified(class) contains a class which needs to be skipped then we must preserve the whitespace.
For instance:
<div class="foo bar">
baz
</div>
4. If a PathExpression is provided as mentioned below, we should preserve the whitespace since the value is known only at runtime.
For instance:
<div class={{foo}}>
bar
<div>
5. If a MustacheStatement is provided as mentioned below. Incase if its a helper if/unless, we need to preserve if any class that needs to be skipped is specified which can be found by following steps 1 to 4.
For instance:
<div class={{if foo 'bar' 'baz'}}>
qux
<div>
6. If a ConcatStatement is provided, for instance,
<div class="foo {{bar}} qux">
bar
<div>
we need to preserve the whitespace if any class that needs to be skipped is specified which can be found by following steps 1 to 4.
*/
if (!value) {
return true;
}
if (configClassNames === 'all') {
return false;
}
let type = value.type;
if (type === 'TextNode') {
return !isClassIncluded(value.chars, configClassNames);
} else if (type === 'StringLiteral') {
return !isClassIncluded(value.value, configClassNames);
} else if (type === 'PathExpression') {
return false;
} else if (type === 'MustacheStatement') {
let canTrim = true;
if (['if', 'unless'].indexOf(value.path.original) !== -1) {
let params = value.params;
for (let i = 1; i < params.length; i++) {
canTrim = canTrimWhiteSpaceBasedOnClassNames(params[i], configClassNames);
if (!canTrim) {
break;
}
}
}
return canTrim;
} else if (type === 'ConcatStatement') {
let parts = value.parts;
return parts.every((part) => {
return canTrimWhiteSpaceBasedOnClassNames(part, configClassNames);
});
}
return true;
}
function shouldSkipBlockStatement(node, config) {
let components = config.skip.components;
if (components === 'all') {
return true;
}
// If a block or all the blocks is/are skiped (or) named as 'no-minify' then we need to preserve the whitespace.
let componentName = node.path.original;
return components.indexOf(componentName) !== -1;
}
function shouldSkipElementNode(node, config) {
let elements = config.skip.elements;
if (elements === 'all') {
return true;
}
// If a element or all the element is/are skiped then we need to preserve the whitespace.
let tag = node.tag;
return elements.indexOf(tag) !== -1;
}
function shouldSkipClass(node, config) {
let classAttrNode = node.attributes.find(attr => attr.name === 'class');
if (!classAttrNode) {
return false;
}
return !canTrimWhiteSpaceBasedOnClassNames(classAttrNode.value, config.skip.classes);
}
function normalizeConfig(config = {}) {
config.skip = config.skip || {};
config.skip.elements = config.skip.elements || ['pre'];
config.skip.classes = config.skip.classes || [];
config.skip.components = config.skip.components || ['no-minify'];
}
module.exports = {
createGlimmerPlugin,
createRegistryPlugin,
};