Skip to content

Commit

Permalink
Block editor: scroll block into view on insert (#61418)
Browse files Browse the repository at this point in the history
Co-authored-by: ellatrix <[email protected]>
Co-authored-by: draganescu <[email protected]>
Co-authored-by: scruffian <[email protected]>
  • Loading branch information
4 people authored May 8, 2024
1 parent 4c28ed3 commit 6a0188b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { useEventHandlers } from './use-selected-block-event-handlers';
import { useNavModeExit } from './use-nav-mode-exit';
import { useBlockRefProvider } from './use-block-refs';
import { useIntersectionObserver } from './use-intersection-observer';
import { useScrollIntoView } from './use-scroll-into-view';
import { useFlashEditableBlocks } from '../../use-flash-editable-blocks';
import { canBindBlock } from '../../../hooks/use-bindings-attributes';

Expand Down Expand Up @@ -122,6 +123,7 @@ export function useBlockProps( props = {}, { __unstableIsHtml } = {} ) {
clientId,
isEnabled: name === 'core/block' || templateLock === 'contentOnly',
} ),
useScrollIntoView( { isSelected } ),
] );

const blockEditContext = useBlockEditContext();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* WordPress dependencies
*/
import { useReducedMotion, useRefEffect } from '@wordpress/compose';

export function useScrollIntoView( { isSelected } ) {
const prefersReducedMotion = useReducedMotion();
return useRefEffect(
( node ) => {
if ( isSelected ) {
const { ownerDocument } = node;
const { defaultView } = ownerDocument;
if ( ! defaultView.IntersectionObserver ) {
return;
}
const observer = new defaultView.IntersectionObserver(
( entries ) => {
// Once observing starts, we always get an initial
// entry with the intersecting state.
if ( ! entries[ 0 ].isIntersecting ) {
node.scrollIntoView( {
behavior: prefersReducedMotion
? 'instant'
: 'smooth',
} );
}
observer.disconnect();
}
);
observer.observe( node );
return () => {
observer.disconnect();
};
}
},
[ isSelected ]
);
}

0 comments on commit 6a0188b

Please sign in to comment.