diff --git a/src/components/modules/paste.ts b/src/components/modules/paste.ts index 7dfe312fe..c98f16040 100644 --- a/src/components/modules/paste.ts +++ b/src/components/modules/paste.ts @@ -108,6 +108,24 @@ interface PasteData { isBlock: boolean; } +const PREFORMATTED_TAGS = 'pre, code, textarea'; + +const collapseLineBreaks = (root: HTMLElement): void => { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + let node = walker.nextNode(); + + while (node !== null) { + const parent = node.parentElement; + const isPreformatted = parent !== null && parent.closest(PREFORMATTED_TAGS) !== null; + + if (!isPreformatted) { + node.nodeValue = (node.nodeValue ?? '').replace(/(?:[ \t]*\r?\n)+[ \t]*/g, ' '); + } + + node = walker.nextNode(); + } +}; + /** * @class Paste * @classdesc Contains methods to handle paste on editor @@ -721,6 +739,8 @@ export default class Paste extends Module { content.innerHTML = clean(content.innerHTML, customConfig); } + collapseLineBreaks(content); + const event = this.composePasteEvent('tag', { data: content, }); diff --git a/test/cypress/tests/copy-paste.cy.ts b/test/cypress/tests/copy-paste.cy.ts index e44d6d7b8..b916ed4c6 100644 --- a/test/cypress/tests/copy-paste.cy.ts +++ b/test/cypress/tests/copy-paste.cy.ts @@ -38,6 +38,31 @@ describe('Copy pasting from Editor', function () { cy.get('@block').should('contain.html', 'Some text'); }); + it('should replace line breaks in pasted html with spaces', function () { + cy.createEditor({}).as('editorInstance'); + + const htmlType = 'text/html'; + const plainType = 'text/plain'; + + cy.get('[data-cy=editorjs]') + .get('div.ce-block') + .as('block') + .click() + .paste({ + [htmlType]: '

First line\nsecond line

', + [plainType]: 'First line\nsecond line', + }); + + cy.get('@block').should('contain', 'First line second line'); + + cy.get('@editorInstance').then(async (editor) => { + const { blocks } = await editor.save(); + + expect(blocks).to.have.length(1); + expect(blocks[0].data.text).to.eq('First line second line'); + }); + }); + it('should paste several blocks if plain text contains new lines', function () { cy.createEditor({});