Skip to content

Commit ad255e8

Browse files
Mamadukaramonjd
andauthored
Paragraph: Refactor replacement logic in 'useOnEnter' hook (#77383)
Co-authored-by: Mamaduka <mamaduka@git.wordpress.org> Co-authored-by: ramonjd <ramonopoly@git.wordpress.org>
1 parent 7e459b1 commit ad255e8

1 file changed

Lines changed: 18 additions & 24 deletions

File tree

packages/block-library/src/paragraph/use-enter.js

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -9,24 +9,20 @@ import { store as blockEditorStore } from '@wordpress/block-editor';
99
import {
1010
hasBlockSupport,
1111
createBlock,
12+
cloneBlock,
1213
getDefaultBlockName,
1314
} from '@wordpress/blocks';
1415

1516
export function useOnEnter( props ) {
1617
const { batch } = useRegistry();
17-
const {
18-
moveBlocksToPosition,
19-
replaceInnerBlocks,
20-
duplicateBlocks,
21-
insertBlock,
22-
} = useDispatch( blockEditorStore );
18+
const { moveBlocksToPosition, replaceBlocks, selectionChange } =
19+
useDispatch( blockEditorStore );
2320
const {
2421
getBlockRootClientId,
2522
getBlockIndex,
2623
getBlockOrder,
2724
getBlockName,
2825
getBlock,
29-
getNextBlockClientId,
3026
canInsertBlockType,
3127
} = useSelect( blockEditorStore );
3228
const propsRef = useRef( props );
@@ -104,24 +100,22 @@ export function useOnEnter( props ) {
104100

105101
// If it is in the middle, split the block in two.
106102
const wrapperBlock = getBlock( wrapperClientId );
103+
const head = cloneBlock( {
104+
...wrapperBlock,
105+
innerBlocks: wrapperBlock.innerBlocks.slice( 0, position ),
106+
} );
107+
const middle = createBlock( defaultBlockName );
108+
const tail = cloneBlock( {
109+
...wrapperBlock,
110+
innerBlocks: wrapperBlock.innerBlocks.slice( position + 1 ),
111+
} );
112+
107113
batch( () => {
108-
duplicateBlocks( [ wrapperClientId ] );
109-
const blockIndex = getBlockIndex( wrapperClientId );
110-
111-
replaceInnerBlocks(
112-
wrapperClientId,
113-
wrapperBlock.innerBlocks.slice( 0, position )
114-
);
115-
replaceInnerBlocks(
116-
getNextBlockClientId( wrapperClientId ),
117-
wrapperBlock.innerBlocks.slice( position + 1 )
118-
);
119-
insertBlock(
120-
createBlock( defaultBlockName ),
121-
blockIndex + 1,
122-
grandparentClientId,
123-
true
124-
);
114+
replaceBlocks( wrapperClientId, [ head, middle, tail ] );
115+
// The selected paragraph is a descendant of the replaced
116+
// wrapper, so `replaceBlocks` leaves the selection stale.
117+
// Move it to the new default block explicitly.
118+
selectionChange( middle.clientId );
125119
} );
126120
}
127121

0 commit comments

Comments
 (0)