@@ -4,13 +4,21 @@ var parseTag = require('./parse-tag');
44// re-used obj for quick lookups of components
55var empty = Object . create ? Object . create ( null ) : { } ;
66// common logic for pushing a child node onto a list
7- function pushTextNode ( list , html , start ) {
7+ function pushTextNode ( list , html , level , start , ignoreWhitespace ) {
88 // calculate correct end of the content slice in case there's
99 // no tag after the text node.
1010 var end = html . indexOf ( '<' , start ) ;
1111 var content = html . slice ( start , end === - 1 ? undefined : end ) ;
12- // if a node is nothing but whitespace, no need to add it.
13- if ( ! / ^ \s * $ / . test ( content ) ) {
12+ // if a node is nothing but whitespace, collapse it as the spec states:
13+ // https://www.w3.org/TR/html4/struct/text.html#h-9.1
14+ if ( / ^ \s * $ / . test ( content ) ) {
15+ content = ' ' ;
16+ }
17+ // don't add whitespace-only text nodes if they would be trailing text nodes
18+ // or if they would be leading whitespace-only text nodes:
19+ // * end > -1 indicates this is not a trailing text node
20+ // * leading node is when level is -1 and list has length 0
21+ if ( ( ! ignoreWhitespace && end > - 1 && level + list . length >= 0 ) || content !== ' ' ) {
1422 list . push ( {
1523 type : 'text' ,
1624 content : content
@@ -53,7 +61,7 @@ module.exports = function parse(html, options) {
5361 }
5462
5563 if ( ! current . voidElement && ! inComponent && nextChar && nextChar !== '<' ) {
56- pushTextNode ( current . children , html , start ) ;
64+ pushTextNode ( current . children , html , level , start , options . ignoreWhitespace ) ;
5765 }
5866
5967 byTag [ current . tagName ] = current ;
@@ -81,10 +89,15 @@ module.exports = function parse(html, options) {
8189 // if we're at the root, push a base text node. otherwise add as
8290 // a child to the current node.
8391 parent = level === - 1 ? result : arr [ level ] . children ;
84- pushTextNode ( parent , html , start ) ;
92+ pushTextNode ( parent , html , level , start , options . ignoreWhitespace ) ;
8593 }
8694 }
8795 } ) ;
8896
97+ // If the "html" passed isn't actually html, add it as a text node.
98+ if ( ! result . length && html . length ) {
99+ pushTextNode ( result , html , 0 , 0 , options . ignoreWhitespace ) ;
100+ }
101+
89102 return result ;
90103} ;
0 commit comments