Skip to content

Commit 78aa276

Browse files
authored
fix: prevent rte from trimming whitespace on delta conversion (#6651)
1 parent b1fb1be commit 78aa276

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

packages/rich-text-editor/src/vaadin-rich-text-editor-mixin.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -693,7 +693,26 @@ export const RichTextEditorMixin = (superClass) =>
693693
* @param {string} htmlValue
694694
*/
695695
dangerouslySetHtmlValue(htmlValue) {
696+
const whitespaceCharacters = {
697+
'\t': '__VAADIN_RICH_TEXT_EDITOR_TAB',
698+
' ': '__VAADIN_RICH_TEXT_EDITOR_SPACE',
699+
};
700+
// Replace whitespace characters with placeholders before the Delta conversion to prevent Quill from trimming them
701+
Object.entries(whitespaceCharacters).forEach(([character, replacement]) => {
702+
htmlValue = htmlValue.replace(new RegExp(character, 'gu'), replacement);
703+
});
704+
696705
const deltaFromHtml = this._editor.clipboard.convert(htmlValue);
706+
707+
// Restore whitespace characters after the conversion
708+
Object.entries(whitespaceCharacters).forEach(([character, replacement]) => {
709+
deltaFromHtml.ops.forEach((op) => {
710+
if (typeof op.insert === 'string') {
711+
op.insert = op.insert.replace(new RegExp(replacement, 'gu'), character);
712+
}
713+
});
714+
});
715+
697716
this._editor.setContents(deltaFromHtml, SOURCE.API);
698717
}
699718

packages/rich-text-editor/test/basic.common.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,6 +706,20 @@ describe('rich text editor', () => {
706706
expect(rte.htmlValue).to.equal('<p><strong>Hello </strong></p><p><strong>world</strong></p>');
707707
});
708708

709+
it('should not lose leading tab characters from the resulting htmlValue', () => {
710+
const htmlWithLeadingTab = '<p>\tTab</p>';
711+
rte.dangerouslySetHtmlValue(htmlWithLeadingTab);
712+
flushValueDebouncer();
713+
expect(rte.htmlValue).to.equal(htmlWithLeadingTab);
714+
});
715+
716+
it('should not lose extra stpace characters from the resulting htmlValue', () => {
717+
const htmlWithExtraSpaces = '<p>Extra spaces</p>';
718+
rte.dangerouslySetHtmlValue(htmlWithExtraSpaces);
719+
flushValueDebouncer();
720+
expect(rte.htmlValue).to.equal(htmlWithExtraSpaces);
721+
});
722+
709723
it('should return the quill editor innerHTML', () => {
710724
expect(rte.htmlValue).to.equal('<p><br></p>');
711725
});

0 commit comments

Comments
 (0)