diff --git a/blots/block.ts b/blots/block.ts index 33cb25c618..8ac10bf370 100644 --- a/blots/block.ts +++ b/blots/block.ts @@ -45,7 +45,7 @@ class Block extends BlockBlot { this.cache = {}; } - insertAt(index, value, def?: unknown) { + insertAt(index: number, value: string, def?: unknown) { if (def != null) { super.insertAt(index, value, def); this.cache = {}; @@ -156,12 +156,23 @@ class BlockEmbed extends EmbedBlot { } insertAt(index: number, value: string, def?: unknown) { - if (typeof value === 'string' && value.endsWith('\n')) { - const block = this.scroll.create(Block.blotName); - this.parent.insertBefore(block, index === 0 ? this : this.next); - block.insertAt(0, value.slice(0, -1)); - } else { + if (def != null) { super.insertAt(index, value, def); + return; + } + const lines = value.split('\n'); + const text = lines.pop(); + const blocks = lines.map(line => { + const block = this.scroll.create(Block.blotName); + block.insertAt(0, line); + return block; + }); + const ref = this.split(index); + blocks.forEach(block => { + this.parent.insertBefore(block, ref); + }); + if (text) { + this.parent.insertBefore(this.scroll.create('text', text), ref); } } } diff --git a/test/unit/blots/block-embed.js b/test/unit/blots/block-embed.js index 8bd7fee7eb..5ebeaddfe4 100644 --- a/test/unit/blots/block-embed.js +++ b/test/unit/blots/block-embed.js @@ -115,6 +115,21 @@ describe('Block Embed', function () { `); }); + it('insert multiple newlines before', function () { + const scroll = this.initialize( + Scroll, + '', + ); + scroll.insertAt(0, '\n\n\n'); + scroll.optimize(); + expect(scroll.domNode).toEqualHTML(` +


+


+


+ + `); + }); + it('insert newline after', function () { const scroll = this.initialize( Scroll, diff --git a/test/unit/core/editor.js b/test/unit/core/editor.js index 542c896063..db784ada37 100644 --- a/test/unit/core/editor.js +++ b/test/unit/core/editor.js @@ -387,6 +387,19 @@ describe('Editor', function () { ); }); + it('insert formatted lines before block embed', function () { + const editor = this.initialize( + Editor, + '

0123

', + ); + editor.applyDelta( + new Delta().retain(5).insert('a\nb').insert('\n', { header: 1 }), + ); + expect(this.container).toEqualHTML( + '

0123

a

b

', + ); + }); + it('insert attributed text with newline before block embed', function () { const editor = this.initialize( Editor,