Skip to content

Commit

Permalink
Add useState and an effect so that we only perform the calculation once
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewserong committed Mar 21, 2023
1 parent a56b54f commit ffc76f7
Showing 1 changed file with 17 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
__experimentalUseSlotFills as useSlotFills,
} from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
Expand All @@ -16,23 +17,30 @@ import { default as InspectorControls } from '../inspector-controls';
import { store as blockEditorStore } from '../../store';

const PositionControlsPanel = () => {
const [ initialOpen, setInitialOpen ] = useState();

// Determine whether the panel should be expanded.
const { initialOpen } = useSelect( ( select ) => {
const { multiSelectedBlocks } = useSelect( ( select ) => {
const { getBlocksByClientId, getSelectedBlockClientIds } =
select( blockEditorStore );

// If any selected block has a position set, open the panel by default.
// The first block's value will still be used within the control though.
const clientIds = getSelectedBlockClientIds();
const multiSelectedBlocks = getBlocksByClientId( clientIds );

return {
initialOpen: multiSelectedBlocks.some(
( { attributes } ) => !! attributes?.style?.position?.type
),
multiSelectedBlocks: getBlocksByClientId( clientIds ),
};
}, [] );

useEffect( () => {
// If any selected block has a position set, open the panel by default.
// The first block's value will still be used within the control though.
if ( initialOpen === undefined ) {
setInitialOpen(
multiSelectedBlocks.some(
( { attributes } ) => !! attributes?.style?.position?.type
)
);
}
}, [ initialOpen, multiSelectedBlocks, setInitialOpen ] );

return (
<PanelBody
className="block-editor-block-inspector__position"
Expand Down

0 comments on commit ffc76f7

Please sign in to comment.