Skip to content

Commit

Permalink
initial attempt
Browse files Browse the repository at this point in the history
  • Loading branch information
xiexr151e committed Sep 12, 2020
1 parent 767775f commit dfe37a4
Show file tree
Hide file tree
Showing 6 changed files with 30,924 additions and 62 deletions.
63 changes: 62 additions & 1 deletion extensions/amp-mustache/0.2/amp-mustache.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,68 @@ export class AmpMustache extends BaseTemplate {
purifyAndSetHtml_(html) {
const body = this.purifier_.purifyHtml(`<div>${html}</div>`);
const div = body.firstElementChild;
return this.tryUnwrap(div);
return tryUnwrap(div);
}

/**
* Iterate through the child nodes of the given root, applying the
* given callback to non-empty text nodes and elements.
* @param {!Element} root
* @param {function((!Element|string))} callback
*/
visitChildren_(root, callback) {
for (let n = root.firstChild; n != null; n = n.nextSibling) {
if (n.nodeType == /* TEXT */ 3) {
const text = n.textContent.trim();
if (text) {
callback(text);
}
} else if (n.nodeType == /* COMMENT */ 8) {
// Ignore comments.
} else if (n.nodeType == /* ELEMENT */ 1) {
callback(dev().assertElement(n));
}
}
}

/**
* Unwraps the root element and returns any children in an array.
* Text node children are normalized inside a <div>.
* @param {!Element} root
* @return {!Array<!Element>}
* @protected @final
*/
unwrapChildren(root) {
const children = [];
visitChildren_(root, (c) => {
if (typeof c == 'string') {
const element = this.win.document.createElement('div');
element.textContent = c;
children.push(element);
} else {
children.push(c);
}
});
return children;
}

/**
* Unwraps the root element. If root has a single element child,
* returns the child. Otherwise, returns root.
* @param {!Element} root
* @return {!Element}
* @protected @final
*/
tryUnwrap(root) {
let onlyChild;
visitChildren_(root, (c) => {
if (onlyChild === undefined && c.nodeType) {
onlyChild = c;
} else {
onlyChild = null;
}
});
return onlyChild || root;
}
}

Expand Down
Loading

0 comments on commit dfe37a4

Please sign in to comment.