Skip to content

Commit

Permalink
Merge pull request #9 from 10up/feature/update-has-selected-inner-blocks
Browse files Browse the repository at this point in the history
refactor useHasSelectedInnerBlock to use core function
  • Loading branch information
tlovett1 authored Feb 3, 2021
2 parents 56d9654 + 1cdb4fa commit d5e0a50
Showing 1 changed file with 4 additions and 39 deletions.
43 changes: 4 additions & 39 deletions hooks/use-has-selected-inner-block.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,12 @@
import { useSelect } from '@wordpress/data';

/**
* check whether the block to check has any children that match the clientID of the selected block
*
* @param {WPBlock} selectedBlock Block object of the currently selected block
* @param {string} clientId Client ID of the block to check
* @return {boolean} Whether or not a child block is selected
*/
function hasSelectedInnerBlock(selectedBlock, clientId) {
const { innerBlocks } = useSelect((select) =>
select('core/block-editor').getBlock(clientId),
);

let isChildSelected = false;

innerBlocks.forEach((innerBlock) => {
if (selectedBlock.clientId === innerBlock.clientId) {
isChildSelected = true;
}

if (innerBlock.innerBlocks.length) {
isChildSelected = hasSelectedInnerBlock(selectedBlock, innerBlock.clientId);
}
});

return isChildSelected;
}

/**
* useHasSelectedInnerBlock
* Determine whether one of the inner blocks currently is selected
*
* @param {WPBlock} block Block object to with children
* @return {boolean} whether or not any children are selected.
* @param {Object} {clientId} block props containing the client id
* @returns {boolean} wether the block is the ancestor of selected blocks
*/
export function useHasSelectedInnerBlock(block) {
try {
const selectedBlock = useSelect((innerSelect) =>
innerSelect('core/block-editor').getSelectionStart(),
);

return hasSelectedInnerBlock(selectedBlock, block.clientId);
} catch (error) {
return false;
}
export function useHasSelectedInnerBlock({clientId}) {
return useSelect((select) => select('core/block-editor').hasSelectedInnerBlock(clientId, true));
}

0 comments on commit d5e0a50

Please sign in to comment.