Skip to content

Commit

Permalink
Avoid removing meaningful whitespaces. Fixes #5984
Browse files Browse the repository at this point in the history
  • Loading branch information
artf committed Jul 5, 2024
1 parent cca8dda commit 7ba2035
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/parser/model/ParserHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ const ParserHtml = (em?: EditorModel, config: ParserConfig & { returnArray?: boo
if (typeof obj !== 'object') {
obj = { type: compType.id };
}
result = obj
result = obj;
break;
}
}
Expand Down Expand Up @@ -280,10 +280,13 @@ const ParserHtml = (em?: EditorModel, config: ParserConfig & { returnArray?: boo
continue;
}

// Throw away empty nodes (keep spaces)
// Try to keep meaningful whitespaces when possible (#5984)
// Ref: https://github.com/GrapesJS/grapesjs/pull/5719#discussion_r1518531999
if (!opts.keepEmptyTextNodes) {
const content = node.nodeValue;
if (content != ' ' && !content!.trim()) {
const content = node.nodeValue || '';
const isFirstOrLast = i === 0 || i === nodesLen - 1;
const hasNewLive = content.includes('\n');
if (content != ' ' && !content.trim() && (isFirstOrLast || hasNewLive)) {
continue;
}
}
Expand Down
57 changes: 57 additions & 0 deletions test/specs/parser/model/ParserHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,63 @@ describe('ParserHtml', () => {
expect(obj.parse(str).html).toEqual(result);
});

test('Cleanup useless empty whitespaces', () => {
const str = `<div>
<p>TestText</p>
</div>`;
const result = [
{
tagName: 'div',
components: [
{
tagName: 'p',
components: { type: 'textnode', content: 'TestText' },
type: 'text',
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});

test('Keep meaningful whitespaces', () => {
const str = `<div>
<p>A</p> <p>B</p> <p>C</p>&nbsp;<p>D</p>
</div>`;
const result = [
{
tagName: 'div',
type: 'text',
components: [
{
tagName: 'p',
components: { type: 'textnode', content: 'A' },
type: 'text',
},
{ type: 'textnode', content: ' ', tagName: '' },
{
tagName: 'p',
components: { type: 'textnode', content: 'B' },
type: 'text',
},
{ type: 'textnode', content: ' ', tagName: '' },
{
tagName: 'p',
components: { type: 'textnode', content: 'C' },
type: 'text',
},
{ type: 'textnode', content: ' ', tagName: '' },
{
tagName: 'p',
components: { type: 'textnode', content: 'D' },
type: 'text',
},
],
},
];
expect(obj.parse(str).html).toEqual(result);
});

test('Parse node with model attributes to fetch', () => {
const str =
'<div id="test1" data-test="test-value" data-gjs-draggable=".myselector" data-gjs-stuff="test">test2 </div>';
Expand Down

0 comments on commit 7ba2035

Please sign in to comment.