Skip to content

Commit

Permalink
fix(compiler): skip   when trimming / removing whitespaces (#19310)
Browse files Browse the repository at this point in the history
Fixes #19304
  • Loading branch information
pkozlowski-opensource authored and vicb committed Sep 25, 2017
1 parent 5c99b01 commit c7aa8a1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
13 changes: 10 additions & 3 deletions packages/compiler/src/ml_parser/html_whitespaces.ts
Expand Up @@ -14,6 +14,12 @@ export const PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces';

const SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']);

// Equivalent to \s with \u00a0 (non-breaking space) excluded.
// Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
const WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
const NO_WS_REGEXP = new RegExp(`[^${WS_CHARS}]`);
const WS_REPLACE_REGEXP = new RegExp(`[${WS_CHARS}]{2,}`, 'g');

function hasPreserveWhitespacesAttr(attrs: html.Attribute[]): boolean {
return attrs.some((attr: html.Attribute) => attr.name === PRESERVE_WS_ATTR_NAME);
}
Expand Down Expand Up @@ -63,10 +69,11 @@ class WhitespaceVisitor implements html.Visitor {
}

visitText(text: html.Text, context: any): any {
const isBlank = text.value.trim().length === 0;
const isNotBlank = text.value.match(NO_WS_REGEXP);

if (!isBlank) {
return new html.Text(replaceNgsp(text.value).replace(/\s\s+/g, ' '), text.sourceSpan);
if (isNotBlank) {
return new html.Text(
replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan);
}

return null;
Expand Down
10 changes: 10 additions & 0 deletions packages/compiler/test/ml_parser/html_whitespaces_spec.ts
Expand Up @@ -64,6 +64,16 @@ export function main() {
expect(parseAndRemoveWS(' \n foo \t ')).toEqual([[html.Text, ' foo ', 0]]);
});

it('should not replace  ', () => {
expect(parseAndRemoveWS(' ')).toEqual([[html.Text, '\u00a0', 0]]);
});

it('should not replace sequences of  ', () => {
expect(parseAndRemoveWS('  foo  ')).toEqual([
[html.Text, '\u00a0\u00a0foo\u00a0\u00a0', 0]
]);
});

it('should not replace single tab and newline with spaces', () => {
expect(parseAndRemoveWS('\nfoo')).toEqual([[html.Text, '\nfoo', 0]]);
expect(parseAndRemoveWS('\tfoo')).toEqual([[html.Text, '\tfoo', 0]]);
Expand Down

0 comments on commit c7aa8a1

Please sign in to comment.