|
| 1 | +/** |
| 2 | + * WordPress dependencies |
| 3 | + */ |
| 4 | +import { useRegistry, useDispatch, useSelect } from '@wordpress/data'; |
| 5 | +import { store as blockEditorStore } from '@wordpress/block-editor'; |
| 6 | + |
| 7 | +export default function useMerge( clientId ) { |
| 8 | + const registry = useRegistry(); |
| 9 | + const { |
| 10 | + getPreviousBlockClientId, |
| 11 | + getNextBlockClientId, |
| 12 | + getBlockOrder, |
| 13 | + getBlockRootClientId, |
| 14 | + } = useSelect( blockEditorStore ); |
| 15 | + const { mergeBlocks, moveBlocksToPosition } = |
| 16 | + useDispatch( blockEditorStore ); |
| 17 | + |
| 18 | + function getTrailing( id ) { |
| 19 | + const order = getBlockOrder( id ); |
| 20 | + |
| 21 | + if ( ! order.length ) { |
| 22 | + return id; |
| 23 | + } |
| 24 | + |
| 25 | + return getTrailing( order[ order.length - 1 ] ); |
| 26 | + } |
| 27 | + |
| 28 | + function getNext( id ) { |
| 29 | + return ( |
| 30 | + getNextBlockClientId( id ) || getNext( getBlockRootClientId( id ) ) |
| 31 | + ); |
| 32 | + } |
| 33 | + |
| 34 | + return ( forward ) => { |
| 35 | + if ( forward ) { |
| 36 | + // Forward "merging" (forward delete) should be equal pressing |
| 37 | + // Backspace from the next item. If the next item is not at the top |
| 38 | + // level, the item should be outdented instead of merged. |
| 39 | + if ( getBlockOrder( clientId ).length ) { |
| 40 | + // Should be implemented in `./use-backspace`. |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + const nextBlockClientId = getNext( clientId ); |
| 45 | + if ( nextBlockClientId ) { |
| 46 | + registry.batch( () => { |
| 47 | + moveBlocksToPosition( |
| 48 | + getBlockOrder( nextBlockClientId ), |
| 49 | + nextBlockClientId, |
| 50 | + getPreviousBlockClientId( nextBlockClientId ) |
| 51 | + ); |
| 52 | + mergeBlocks( clientId, nextBlockClientId ); |
| 53 | + } ); |
| 54 | + } |
| 55 | + } else { |
| 56 | + // Merging is only done from the top level. For lowel levels, the |
| 57 | + // list item is outdented instead. |
| 58 | + const previousBlockClientId = getPreviousBlockClientId( clientId ); |
| 59 | + if ( previousBlockClientId ) { |
| 60 | + const trailingClientId = getTrailing( previousBlockClientId ); |
| 61 | + registry.batch( () => { |
| 62 | + moveBlocksToPosition( |
| 63 | + getBlockOrder( clientId ), |
| 64 | + clientId, |
| 65 | + previousBlockClientId |
| 66 | + ); |
| 67 | + mergeBlocks( trailingClientId, clientId ); |
| 68 | + } ); |
| 69 | + } |
| 70 | + } |
| 71 | + }; |
| 72 | +} |
0 commit comments