| 1 |
/** |
| 2 |
* Remove field blocks with a snackbar Undo (global undo stays off; attribute |
| 3 |
* edits are mirrored server-side). Re-insert on Undo in ascending index order. |
| 4 |
* |
| 5 |
* @param {string[]|string} clientIds |
| 6 |
* @param {Object} [options] |
| 7 |
* @param {string} [options.message] |
| 8 |
* @param {Function} [options.select] |
| 9 |
* @param {Function} [options.dispatch] |
| 10 |
*/ |
| 11 |
|
| 12 |
import { select as defaultSelect, dispatch as defaultDispatch } from '@wordpress/data'; |
| 13 |
import { __ } from '@wordpress/i18n'; |
| 14 |
|
| 15 |
export function removeBlocksWithUndo( clientIds, options = {} ) { |
| 16 |
const select = options.select || defaultSelect; |
| 17 |
const dispatch = options.dispatch || defaultDispatch; |
| 18 |
|
| 19 |
const ids = ( Array.isArray( clientIds ) ? clientIds : [ clientIds ] ).filter( Boolean ); |
| 20 |
if ( ! ids.length ) return; |
| 21 |
|
| 22 |
const editor = select( 'core/block-editor' ); |
| 23 |
const { removeBlocks, insertBlock } = dispatch( 'core/block-editor' ); |
| 24 |
if ( ! editor ) return; |
| 25 |
|
| 26 |
const snapshots = ids |
| 27 |
.map( ( clientId ) => ( { |
| 28 |
block: editor.getBlock( clientId ), |
| 29 |
rootClientId: editor.getBlockRootClientId( clientId ) || '', |
| 30 |
index: editor.getBlockIndex( clientId ), |
| 31 |
} ) ) |
| 32 |
.filter( ( snapshot ) => !! snapshot.block ) |
| 33 |
.sort( ( a, b ) => a.index - b.index ); |
| 34 |
|
| 35 |
removeBlocks( ids ); |
| 36 |
|
| 37 |
const notices = dispatch( 'core/notices' ); |
| 38 |
if ( ! notices || ! snapshots.length ) { |
| 39 |
return; |
| 40 |
} |
| 41 |
|
| 42 |
const message = options.message || __( 'Field removed from this form.', 'profile-builder' ); |
| 43 |
|
| 44 |
notices.createInfoNotice( message, { |
| 45 |
type: 'snackbar', |
| 46 |
actions: [ |
| 47 |
{ |
| 48 |
label: __( 'Undo', 'profile-builder' ), |
| 49 |
onClick: () => { |
| 50 |
snapshots.forEach( ( { block, index, rootClientId } ) => { |
| 51 |
insertBlock( block, index, rootClientId || undefined ); |
| 52 |
} ); |
| 53 |
}, |
| 54 |
}, |
| 55 |
], |
| 56 |
} ); |
| 57 |
} |
| 58 |
|