Skip to content

Commit

Permalink
fix: prevent rte from trimming whitespace on delta conversion (#6651)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomivirkki authored Oct 16, 2023
1 parent b1fb1be commit 78aa276
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
19 changes: 19 additions & 0 deletions packages/rich-text-editor/src/vaadin-rich-text-editor-mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -693,7 +693,26 @@ export const RichTextEditorMixin = (superClass) =>
* @param {string} htmlValue
*/
dangerouslySetHtmlValue(htmlValue) {
const whitespaceCharacters = {
'\t': '__VAADIN_RICH_TEXT_EDITOR_TAB',
' ': '__VAADIN_RICH_TEXT_EDITOR_SPACE',
};
// Replace whitespace characters with placeholders before the Delta conversion to prevent Quill from trimming them
Object.entries(whitespaceCharacters).forEach(([character, replacement]) => {
htmlValue = htmlValue.replace(new RegExp(character, 'gu'), replacement);
});

const deltaFromHtml = this._editor.clipboard.convert(htmlValue);

// Restore whitespace characters after the conversion
Object.entries(whitespaceCharacters).forEach(([character, replacement]) => {
deltaFromHtml.ops.forEach((op) => {
if (typeof op.insert === 'string') {
op.insert = op.insert.replace(new RegExp(replacement, 'gu'), character);
}
});
});

this._editor.setContents(deltaFromHtml, SOURCE.API);
}

Expand Down
14 changes: 14 additions & 0 deletions packages/rich-text-editor/test/basic.common.js
Original file line number Diff line number Diff line change
Expand Up @@ -706,6 +706,20 @@ describe('rich text editor', () => {
expect(rte.htmlValue).to.equal('<p><strong>Hello </strong></p><p><strong>world</strong></p>');
});

it('should not lose leading tab characters from the resulting htmlValue', () => {
const htmlWithLeadingTab = '<p>\tTab</p>';
rte.dangerouslySetHtmlValue(htmlWithLeadingTab);
flushValueDebouncer();
expect(rte.htmlValue).to.equal(htmlWithLeadingTab);
});

it('should not lose extra stpace characters from the resulting htmlValue', () => {
const htmlWithExtraSpaces = '<p>Extra spaces</p>';
rte.dangerouslySetHtmlValue(htmlWithExtraSpaces);
flushValueDebouncer();
expect(rte.htmlValue).to.equal(htmlWithExtraSpaces);
});

it('should return the quill editor innerHTML', () => {
expect(rte.htmlValue).to.equal('<p><br></p>');
});
Expand Down

0 comments on commit 78aa276

Please sign in to comment.