Skip to content

Commit

Permalink
Fix paste to empty node losing structure of first block (#4489)
Browse files Browse the repository at this point in the history
  • Loading branch information
nemanja-tosic committed Sep 6, 2021
1 parent 29473b0 commit 1b560de
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/cool-rings-help.md
@@ -0,0 +1,5 @@
---
'slate': minor
---

Fix paste to empty node losing structure of first block
18 changes: 17 additions & 1 deletion packages/slate/src/transforms/text.ts
Expand Up @@ -302,13 +302,23 @@ export const TextTransforms: TextTransforms = {
const [, blockPath] = blockMatch
const isBlockStart = Editor.isStart(editor, at, blockPath)
const isBlockEnd = Editor.isEnd(editor, at, blockPath)
const isBlockEmpty = isBlockStart && isBlockEnd
const mergeStart = !isBlockStart || (isBlockStart && isBlockEnd)
const mergeEnd = !isBlockEnd
const [, firstPath] = Node.first({ children: fragment }, [])
const [, lastPath] = Node.last({ children: fragment }, [])

const matches: NodeEntry[] = []
const matcher = ([n, p]: NodeEntry) => {
const isRoot = p.length === 0
if (isRoot) {
return false
}

if (isBlockEmpty) {
return true
}

if (
mergeStart &&
Path.isAncestor(p, firstPath) &&
Expand Down Expand Up @@ -336,7 +346,7 @@ export const TextTransforms: TextTransforms = {
{ children: fragment },
{ pass: matcher }
)) {
if (entry[1].length > 0 && matcher(entry)) {
if (matcher(entry)) {
matches.push(entry)
}
}
Expand Down Expand Up @@ -380,6 +390,8 @@ export const TextTransforms: TextTransforms = {
isInlineEnd ? Path.next(inlinePath) : inlinePath
)

const blockPathRef = Editor.pathRef(editor, blockPath)

Transforms.splitNodes(editor, {
at,
match: n =>
Expand All @@ -404,6 +416,10 @@ export const TextTransforms: TextTransforms = {
voids,
})

if (isBlockEmpty && middles.length) {
Transforms.delete(editor, { at: blockPathRef.unref()!, voids })
}

Transforms.insertNodes(editor, middles, {
at: middleRef.current!,
match: n => Editor.isBlock(editor, n),
Expand Down
@@ -0,0 +1,37 @@
/** @jsx jsx */
import { Transforms } from 'slate'
import { jsx } from '../../..'

export const run = editor => {
Transforms.insertFragment(
editor,
<fragment>
<block>
<block>one</block>
</block>
<block>two</block>
<block>three</block>
</fragment>
)
}
export const input = (
<editor>
<block>word</block>
<block>
<cursor />
</block>
</editor>
)
export const output = (
<editor>
<block>word</block>
<block>
<block>one</block>
</block>
<block>two</block>
<block>
three
<cursor />
</block>
</editor>
)

0 comments on commit 1b560de

Please sign in to comment.