-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #9 from 10up/feature/update-has-selected-inner-blocks
refactor useHasSelectedInnerBlock to use core function
- Loading branch information
Showing
1 changed file
with
4 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | ||
} |