Skip to content
This repository has been archived by the owner on Dec 23, 2023. It is now read-only.

Commit

Permalink
wip! Strip whitespace
Browse files Browse the repository at this point in the history
  • Loading branch information
nathan-muir committed Mar 15, 2021
1 parent dd31a69 commit e779b79
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions packages/spacebars-compiler/optimizer.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,65 @@ TreeTransformer.def({
}
});

function compactRaw(array){
var result = [];
for (var i = 0; i < array.length; i++) {
var item = array[i];
if (item instanceof HTML.Raw) {
if (!item.value) {
continue;
}
if (result.length &&
(result[result.length - 1] instanceof HTML.Raw)){
result[result.length - 1] = HTML.Raw(
result[result.length - 1].value + item.value);
continue
}
}
result.push(item);
}
return result;
}

function stripWhitespace(array){
var result = [];
for (var i = 0; i < array.length; i++) {
var item = array[i];
// remove nodes that contain only whitespace
if ((item instanceof HTML.Raw) && item.value.indexOf('\n') !== -1 && !/\S/.test(item.value)) {
continue;
}
result.push(item)
}
return result;
}
var PrimalRawVisitor = TreeTransformer.extend();
PrimalRawVisitor.def({
visitNull: toRaw,
visitPrimitive: toRaw,
visitComment: toRaw,
visitCharRef: toRaw,
visitArray: function(array){
// this.super(array)
var result = TreeTransformer.prototype.visitArray.call(this, array);
result = compactRaw(result);
result = stripWhitespace(result);
return result;
},
visitTag: function (tag) {
var tagName = tag.tagName;
// TODO - List tags that we don't want to strip whitespace for.
if (tagName === 'textarea' || tagName === 'script' || tagName === 'pre'
|| !HTML.isKnownElement(tagName) || HTML.isKnownSVGElement(tagName)) {
return tag;
}
return TreeTransformer.prototype.visitTag.call(this, tag)
},
visitAttributes: function (attrs) {
return attrs;
}
});

// Replace parts of the HTMLjs tree that have no template tags (or
// tricky HTML tags) with HTML.Raw objects containing raw HTML.
var OptimizingVisitor = TreeTransformer.extend();
Expand Down Expand Up @@ -184,6 +243,7 @@ RawReplacingVisitor.def({
});

SpacebarsCompiler.optimize = function (tree) {
tree = (new PrimalRawVisitor).visit(tree);
tree = (new OptimizingVisitor).visit(tree);
tree = (new RawCompactingVisitor).visit(tree);
tree = (new RawReplacingVisitor).visit(tree);
Expand Down

0 comments on commit e779b79

Please sign in to comment.