Skip to content

Commit

Permalink
Style book: scroll to top at styles root (#67605)
Browse files Browse the repository at this point in the history
Co-authored-by: ramonjd <[email protected]>
Co-authored-by: tellthemachines <[email protected]>
  • Loading branch information
3 people authored Dec 6, 2024
1 parent 63c4d5b commit 34088ef
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions packages/edit-site/src/components/style-book/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,14 @@ function isObjectEmpty( object ) {
* @param {HTMLIFrameElement} iframe The target iframe.
*/
const scrollToSection = ( anchorId, iframe ) => {
if ( ! iframe || ! iframe?.contentDocument ) {
if ( ! anchorId || ! iframe || ! iframe?.contentDocument ) {
return;
}

const element = iframe.contentDocument.getElementById( anchorId );
const element =
anchorId === 'top'
? iframe.contentDocument.body
: iframe.contentDocument.getElementById( anchorId );
if ( element ) {
element.scrollIntoView( {
behavior: 'smooth',
Expand All @@ -89,6 +92,12 @@ const scrollToSection = ( anchorId, iframe ) => {
*/
const getStyleBookNavigationFromPath = ( path ) => {
if ( path && typeof path === 'string' ) {
if ( path === '/' ) {
return {
top: true,
};
}

if ( path.startsWith( '/typography' ) ) {
return {
block: 'typography',
Expand Down Expand Up @@ -365,10 +374,19 @@ const StyleBookBody = ( {

const handleLoad = () => setHasIframeLoaded( true );
useLayoutEffect( () => {
if ( goTo?.block && hasIframeLoaded && iframeRef?.current ) {
scrollToSection( `example-${ goTo?.block }`, iframeRef?.current );
if ( hasIframeLoaded && iframeRef?.current ) {
if ( goTo?.top ) {
scrollToSection( 'top', iframeRef?.current );
return;
}
if ( goTo?.block ) {
scrollToSection(
`example-${ goTo?.block }`,
iframeRef?.current
);
}
}
}, [ iframeRef?.current, goTo?.block, scrollToSection, hasIframeLoaded ] );
}, [ iframeRef?.current, goTo, scrollToSection, hasIframeLoaded ] );

return (
<Iframe
Expand Down

0 comments on commit 34088ef

Please sign in to comment.