2019-09-09 13:25:22 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2020-07-22 12:20:54 +00:00
|
|
|
import { render, Suspense } from '@wordpress/element';
|
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-05-27 10:11:30 +00:00
|
|
|
* @param {Object} props Render props.
|
|
|
|
* @param {Function} props.Block React component to use as a replacement.
|
2020-06-05 12:18:16 +00:00
|
|
|
* @param {string} props.selector CSS selector to match the elements to replace.
|
2020-05-27 10:11:30 +00:00
|
|
|
* @param {Function} [props.getProps ] Function to generate the props object for the block.
|
|
|
|
* @param {Function} [props.getErrorBoundaryProps] Function to generate the props object for the error boundary.
|
2019-09-09 13:25:22 +00:00
|
|
|
*/
|
2020-05-27 10:11:30 +00:00
|
|
|
export const renderFrontend = ( {
|
2020-03-06 11:43:40 +00:00
|
|
|
Block,
|
2020-06-05 12:18:16 +00:00
|
|
|
selector,
|
2020-03-06 11:43:40 +00:00
|
|
|
getProps = () => {},
|
2020-05-27 10:11:30 +00:00
|
|
|
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 }>
|
2020-07-22 12:20:54 +00:00
|
|
|
<Suspense
|
|
|
|
fallback={ <div className="wc-block-placeholder" /> }
|
|
|
|
>
|
|
|
|
<Block { ...props } attributes={ attributes } />
|
|
|
|
</Suspense>
|
2019-11-21 08:08:47 +00:00
|
|
|
</BlockErrorBoundary>,
|
|
|
|
el
|
|
|
|
);
|
2019-09-09 13:25:22 +00:00
|
|
|
} );
|
|
|
|
}
|
|
|
|
};
|
2020-04-27 16:06:58 +00:00
|
|
|
|
|
|
|
export default renderFrontend;
|