Skip to content

Commit

Permalink
Add useScrollUponInsertion hook
Browse files Browse the repository at this point in the history
  • Loading branch information
fluiddot committed Dec 19, 2023
1 parent d9cbde9 commit bbe30e3
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
17 changes: 16 additions & 1 deletion packages/block-editor/src/components/block-list/block.native.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { useCallback, useMemo, useState } from '@wordpress/element';
import { useCallback, useMemo, useState, useRef } from '@wordpress/element';
import {
GlobalStylesContext,
getMergedGlobalStyles,
Expand Down Expand Up @@ -40,6 +40,7 @@ import BlockInvalidWarning from './block-invalid-warning';
import BlockOutline from './block-outline';
import { store as blockEditorStore } from '../../store';
import { useLayout } from './layout';
import useScrollUponInsertion from './use-scroll-upon-insertion';
import { useSettings } from '../use-settings';

const EMPTY_ARRAY = [];
Expand Down Expand Up @@ -103,6 +104,18 @@ function BlockWrapper( {
];
const accessible = ! ( isSelected || isDescendentBlockSelected );

const ref = useRef();
const [ isLayoutCalculated, setIsLayoutCalculated ] = useState();
useScrollUponInsertion( {
clientId,
isSelected,
isLayoutCalculated,
elementRef: ref,
} );
const onLayout = useCallback( () => {
setIsLayoutCalculated( true );
}, [] );

return (
<Pressable
accessibilityLabel={ accessibilityLabel }
Expand All @@ -111,6 +124,8 @@ function BlockWrapper( {
disabled={ ! isTouchable }
onPress={ onFocus }
style={ blockWrapperStyle }
ref={ ref }
onLayout={ onLayout }
>
<BlockOutline
blockCategory={ blockCategory }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* WordPress dependencies
*/
import { useEffect, useRef } from '@wordpress/element';
import { useSelect } from '@wordpress/data';

/**
* Internal dependencies
*/
import { useBlockListContext } from './block-list-context';
import { store as blockEditorStore } from '../../store';

const useScrollUponInsertion = ( {
clientId,
isSelected,
isLayoutCalculated,
elementRef,
} ) => {
const isAlreadyInserted = useRef( false );
const { scrollRef } = useBlockListContext();
const wasBlockJustInserted = useSelect(
( select ) =>
!! select( blockEditorStore ).wasBlockJustInserted(
clientId,
'inserter_menu'
),
[ clientId ]
);
useEffect( () => {
const blockJustInserted =
! isAlreadyInserted.current && wasBlockJustInserted;
if (
! isSelected ||
! scrollRef ||
! blockJustInserted ||
! isLayoutCalculated
) {
return;
}
scrollRef.scrollToElement( elementRef );
isAlreadyInserted.current = wasBlockJustInserted;
}, [
isSelected,
scrollRef,
wasBlockJustInserted,
elementRef,
isLayoutCalculated,
] );
};

export default useScrollUponInsertion;

0 comments on commit bbe30e3

Please sign in to comment.