2019-09-09 13:25:22 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { render } from 'react-dom';
|
2019-11-21 08:08:47 +00:00
|
|
|
import BlockErrorBoundary from '@woocommerce/base-components/block-error-boundary';
|
2019-09-09 13:25:22 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Renders a block component in the place of a specified set of selectors.
|
|
|
|
*
|
2020-03-06 11:43:40 +00:00
|
|
|
* @param {string} selector CSS selector to match the elements
|
|
|
|
* to replace.
|
|
|
|
* @param {Function} Block React block to use as a replacement.
|
|
|
|
* @param {Function} [getProps] Function to generate the props
|
|
|
|
* object for the block.
|
|
|
|
* @param {Function} [getErrorBoundaryProps] Function to generate the props
|
|
|
|
* object for the error boundary.
|
2019-09-09 13:25:22 +00:00
|
|
|
*/
|
2020-03-06 11:43:40 +00:00
|
|
|
export default (
|
|
|
|
selector,
|
|
|
|
Block,
|
|
|
|
getProps = () => {},
|
|
|
|
getErrorBoundaryProps = () => {}
|
|
|
|
) => {
|
2019-09-09 13:25:22 +00:00
|
|
|
const containers = document.querySelectorAll( selector );
|
|
|
|
|
|
|
|
if ( containers.length ) {
|
2019-11-23 16:29:35 +00:00
|
|
|
// Use Array.forEach for IE11 compatibility.
|
2019-10-28 13:53:09 +00:00
|
|
|
Array.prototype.forEach.call( containers, ( el, i ) => {
|
|
|
|
const props = getProps( el, i );
|
2020-03-06 11:43:40 +00:00
|
|
|
const errorBoundaryProps = getErrorBoundaryProps( el, i );
|
2019-09-09 13:25:22 +00:00
|
|
|
const attributes = {
|
|
|
|
...el.dataset,
|
|
|
|
...props.attributes,
|
|
|
|
};
|
|
|
|
|
|
|
|
el.classList.remove( 'is-loading' );
|
|
|
|
|
2019-11-21 08:08:47 +00:00
|
|
|
render(
|
2020-03-06 11:43:40 +00:00
|
|
|
<BlockErrorBoundary { ...errorBoundaryProps }>
|
2019-11-21 08:08:47 +00:00
|
|
|
<Block { ...props } attributes={ attributes } />
|
|
|
|
</BlockErrorBoundary>,
|
|
|
|
el
|
|
|
|
);
|
2019-09-09 13:25:22 +00:00
|
|
|
} );
|
|
|
|
}
|
|
|
|
};
|