Gutenberg editor scroll block into view Gutenberg editor scroll block into view wordpress wordpress

Gutenberg editor scroll block into view


dom-scroll-into-view is an NPM package by itself at https://github.com/yiminghe/dom-scroll-into-view

They have a demo available at http://yiminghe.me/dom-scroll-into-view/examples/demo.html

And their main source code is https://github.com/yiminghe/dom-scroll-into-view/blob/master/src/dom-scroll-into-view.js


Short answer:

  • source is the HTML element you want to be brought into view.

  • container is its container element, or you can simply put it to be window if you don't have a particular container wrapping your element.

  • Finally config is an optional object that lets you configurate some fine tuning like a little bit of margin to top of left if you don't want this to hit the exact top border of the browser. You can start by passing {} to it for now.


in my case, how to get the source and container DOM elements?

It's actually quite easy.. just use document.querySelector() to get the block node and then wp.dom.getScrollContainer() to get that node's container:

const nextBlock = wp.blocks.createBlock( 'core/paragraph' );wp.data.dispatch( 'core/editor' ).insertBlock( nextBlock );const source = document.querySelector( '[data-block="' + nextBlock.clientId + '"]' );const container = wp.dom.getScrollContainer( source );

References: One Two

And here's my code:

/** * External dependencies */import scrollIntoView from 'dom-scroll-into-view';/** * WordPress dependencies */import { createBlock } from '@wordpress/blocks';     // wp.blocks.createBlockimport { dispatch } from '@wordpress/data';          // wp.data.dispatchimport { getScrollContainer } from '@wordpress/dom'; // wp.dom.getScrollContainerfunction getBlockDOMNode( clientId ) {    return document.querySelector( '[data-block="' + clientId + '"]' );}const nextBlock = createBlock( 'core/paragraph' );dispatch( 'core/editor' ).insertBlock( nextBlock );const source = getBlockDOMNode( nextBlock.clientId );const container = source ? getScrollContainer( source ) : null;if ( source && container ) {    scrollIntoView( source, container );}

UPDATE

For testing the imported scrollIntoView(), try this:

function scrollBlockIntoView( block ) {    const source = getBlockDOMNode( block.clientId );    const container = source ? getScrollContainer( source ) : null;    if ( source && container ) {        console.log( source, container );        scrollIntoView( source, container );    }}window.scrollBlockIntoView = function( block ) {    scrollBlockIntoView( block || {} );};

And then from the browser console, run this:

scrollBlockIntoView( wp.data.select('core/editor').getBlocks()[1] )

But make sure that you have at least two blocks in the editor — e.g. a paragraph with a lengthy content and an image block.

Tried and tested working on Chrome (Windows 10).