Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Refactor update on block move to a different effect to reduce event b…
…inding
  • Loading branch information
talldan committed Aug 22, 2022
commit bc43d196f56b6b4ddf6151773d7d007b5f0ed7a7
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/
import { useRefEffect } from '@wordpress/compose';
import { useSelect } from '@wordpress/data';
import { useEffect, useState } from '@wordpress/element';
import { useCallback, useEffect, useState } from '@wordpress/element';

/**
* Internal dependencies
Expand Down Expand Up @@ -76,18 +76,24 @@ export default function useBlockToolbarPopoverProps( {
setToolbarHeight( popoverNode.offsetHeight );
}, [] );

const updateProps = useCallback(
() =>
setProps(
getProps( contentElement, selectedBlockElement, toolbarHeight )
),
[ contentElement, selectedBlockElement, toolbarHeight ]
);

// Update props when the block is moved. This also ensures the props are
// correct on initial mount.
useEffect( updateProps, [ blockIndex ] );

// Update props when the viewport is resized or the block is resized.
useEffect( () => {
if ( ! contentElement || ! selectedBlockElement ) {
return;
}

const updateProps = () =>
setProps(
getProps( contentElement, selectedBlockElement, toolbarHeight )
);

updateProps();

// Update the toolbar props on viewport resize.
const contentView = contentElement?.ownerDocument?.defaultView;
contentView?.addEventHandler?.( 'resize', updateProps );
Expand All @@ -107,12 +113,7 @@ export default function useBlockToolbarPopoverProps( {
resizeObserver.disconnect();
}
};

// The deps will update the toolbar props if:
// - The content or the selected block element changes.
// - The block is moved (its index changes).
// - The height of the toolbar changes.
}, [ contentElement, selectedBlockElement, blockIndex, toolbarHeight ] );
}, [ updateProps, contentElement, selectedBlockElement ] );

return {
...props,
Expand Down