-
Notifications
You must be signed in to change notification settings - Fork 799
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Button Block: Add parent-child syncing mechanism (#15931)
- Loading branch information
Showing
3 changed files
with
47 additions
and
0 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
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
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 |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** | ||
* External dependencies | ||
*/ | ||
import { isEmpty, mapValues, pickBy } from 'lodash'; | ||
|
||
/** | ||
* WordPress dependencies | ||
*/ | ||
import { useSelect } from '@wordpress/data'; | ||
import { useEffect } from '@wordpress/element'; | ||
|
||
export default function usePassthroughAttributes( { attributes, clientId, setAttributes } ) { | ||
// `passthroughAttributes` is a map of child/parent attribute names, | ||
// to indicate which parent attribute values will be injected into which child attributes. | ||
// E.g. { childAttribute: 'parentAttribute' } | ||
const { passthroughAttributes } = attributes; | ||
|
||
const { attributesToSync } = useSelect( select => { | ||
const { getBlockAttributes, getBlockHierarchyRootClientId } = select( 'core/block-editor' ); | ||
const parentAttributes = getBlockAttributes( getBlockHierarchyRootClientId( clientId ) ); | ||
|
||
// Here we actually map the parent attribute value to the child attribute. | ||
// E.g. { childAttribute: 'foobar' } | ||
const mappedAttributes = mapValues( passthroughAttributes, key => parentAttributes[ key ] ); | ||
|
||
// Discard all equals attributes | ||
const validAttributes = pickBy( | ||
mappedAttributes, | ||
( value, key ) => value !== attributes[ key ] | ||
); | ||
|
||
return { attributesToSync: validAttributes }; | ||
} ); | ||
|
||
useEffect( () => { | ||
if ( ! isEmpty( attributesToSync ) ) { | ||
setAttributes( attributesToSync ); | ||
} | ||
}, [ attributesToSync, setAttributes ] ); | ||
} |