Skip to content

Fix text nodes #9

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

Merged
merged 2 commits into from
Jul 24, 2017
Merged
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
16 changes: 12 additions & 4 deletions lib/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ var parseTag = require('./parse-tag');
// re-used obj for quick lookups of components
var empty = Object.create ? Object.create(null) : {};
// common logic for pushing a child node onto a list
function pushTextNode(list, html, start) {
function pushTextNode(list, html, start, ignoreWhitespace) {
// calculate correct end of the content slice in case there's
// no tag after the text node.
var end = html.indexOf('<', start);
var content = html.slice(start, end === -1 ? undefined : end);
// if a node is nothing but whitespace, no need to add it.
if (!/^\s*$/.test(content)) {
if (!ignoreWhitespace || !/^\s*$/.test(content)) {
list.push({
type: 'text',
content: content
Expand All @@ -21,6 +21,9 @@ function pushTextNode(list, html, start) {
module.exports = function parse(html, options) {
options || (options = {});
options.components || (options.components = empty);
if (options.ignoreWhitespace === void 0) {
options.ignoreWhitespace = true;
}
var result = [];
var current;
var level = -1;
Expand Down Expand Up @@ -53,7 +56,7 @@ module.exports = function parse(html, options) {
}

if (!current.voidElement && !inComponent && nextChar && nextChar !== '<') {
pushTextNode(current.children, html, start);
pushTextNode(current.children, html, start, options.ignoreWhitespace);
}

byTag[current.tagName] = current;
Expand Down Expand Up @@ -81,10 +84,15 @@ module.exports = function parse(html, options) {
// if we're at the root, push a base text node. otherwise add as
// a child to the current node.
parent = level === -1 ? result : arr[level].children;
pushTextNode(parent, html, start);
pushTextNode(parent, html, start, options.ignoreWhitespace);
}
}
});

// If the "html" passed isn't actually html, add it as a text node.
if (!result.length && html.length) {
pushTextNode(result, html, 0, options.ignoreWhitespace);
}

return result;
};