Browse Source

Avoid removing meaningful whitespaces. Fixes #5984

pull/6013/head
Artur Arseniev 2 years ago
parent
commit
7ba2035ebf
  1. 11
      src/parser/model/ParserHtml.ts
  2. 57
      test/specs/parser/model/ParserHtml.ts

11
src/parser/model/ParserHtml.ts

@ -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;
}
}
@ -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;
}
}

57
test/specs/parser/model/ParserHtml.ts

@ -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>';

Loading…
Cancel
Save