Skip to content
Merged
Show file tree
Hide file tree
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
13 changes: 10 additions & 3 deletions packages/compiler/src/ml_parser/html_whitespaces.ts
Original file line number Diff line number Diff line change
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';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If not sure how useful the \u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff part is but it shouldn't hurt either

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept it for consistency with \s

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
Original file line number Diff line number Diff line change
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