| 1 |
import { select } from '@wordpress/data'; |
| 2 |
|
| 3 |
const scrollBlockToView = () => { |
| 4 |
|
| 5 |
// Scroll the view to the selected block after device type change in editor. |
| 6 |
const { getSelectedBlock } = select( 'core/block-editor' ); |
| 7 |
const selectedBlockID = getSelectedBlock()?.clientId ? `block-${getSelectedBlock()?.clientId}` : false; |
| 8 |
|
| 9 |
if ( ! selectedBlockID ) { |
| 10 |
return; |
| 11 |
} |
| 12 |
|
| 13 |
setTimeout( ()=> { |
| 14 |
const currentDocument = getCurrentDocument(); |
| 15 |
const selectedBlockElementToScroll = currentDocument.getElementById ( selectedBlockID ); |
| 16 |
|
| 17 |
if ( selectedBlockElementToScroll ) { |
| 18 |
selectedBlockElementToScroll.scrollIntoView( {behavior: 'smooth'} ); |
| 19 |
} |
| 20 |
}, 500 ) |
| 21 |
} |
| 22 |
|
| 23 |
const getCurrentDocument = () => { |
| 24 |
|
| 25 |
const tabletPreview = document.getElementsByClassName( 'is-tablet-preview' ); |
| 26 |
const mobilePreview = document.getElementsByClassName( 'is-mobile-preview' ); |
| 27 |
if ( 0 !== tabletPreview.length || 0 !== mobilePreview.length ) { |
| 28 |
|
| 29 |
const preview = tabletPreview[0] || mobilePreview[0]; |
| 30 |
|
| 31 |
let iframe = false; |
| 32 |
|
| 33 |
if ( preview ) { |
| 34 |
iframe = preview.getElementsByTagName( 'iframe' )[0]; |
| 35 |
} |
| 36 |
|
| 37 |
const iframeDocument = iframe?.contentWindow.document || iframe?.contentDocument; |
| 38 |
|
| 39 |
if ( iframeDocument ) { |
| 40 |
return iframeDocument; |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
return document; |
| 45 |
}; |
| 46 |
|
| 47 |
export default scrollBlockToView; |
| 48 |
|