Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/components/modules/paste.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
});
Expand Down
25 changes: 25 additions & 0 deletions test/cypress/tests/copy-paste.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,31 @@ describe('Copy pasting from Editor', function () {
cy.get('@block').should('contain.html', '<b>Some text</b>');
});

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]: '<p>First line\nsecond line</p>',
[plainType]: 'First line\nsecond line',
});

cy.get('@block').should('contain', 'First line second line');

cy.get<EditorJS>('@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({});

Expand Down
Loading