2018-09-24 15:36:35 +00:00
|
|
|
/** @format */
|
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import codeBlocks from 'gfm-code-blocks';
|
|
|
|
import { Component } from '@wordpress/element';
|
2018-10-19 20:36:02 +00:00
|
|
|
import { LiveError, LivePreview, LiveProvider } from 'react-live';
|
2018-09-24 15:36:35 +00:00
|
|
|
// Used to provide scope in LivePreview
|
|
|
|
import { addFilter } from '@wordpress/hooks';
|
|
|
|
import { withState } from '@wordpress/compose';
|
|
|
|
import * as wpComponents from '@wordpress/components';
|
|
|
|
import Gridicon from 'gridicons';
|
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
2018-11-15 18:16:23 +00:00
|
|
|
import * as components from 'components';
|
|
|
|
import * as pkgComponents from '@woocommerce/components';
|
2018-09-24 15:36:35 +00:00
|
|
|
|
|
|
|
class Example extends Component {
|
|
|
|
state = {
|
|
|
|
code: null,
|
|
|
|
};
|
|
|
|
|
|
|
|
componentDidMount() {
|
|
|
|
this.getCode();
|
|
|
|
}
|
|
|
|
|
|
|
|
async getCode() {
|
2018-11-15 18:16:23 +00:00
|
|
|
let readme;
|
|
|
|
try {
|
|
|
|
readme = require( `components/src/${ this.props.filePath }/example.md` );
|
|
|
|
} catch ( e ) {
|
|
|
|
readme = require( `components/${ this.props.filePath }/example.md` );
|
|
|
|
}
|
|
|
|
if ( ! readme ) {
|
|
|
|
return;
|
|
|
|
}
|
2018-09-24 15:36:35 +00:00
|
|
|
|
|
|
|
// Example to render is the first jsx code block that appears in the readme
|
|
|
|
let code = codeBlocks( readme ).find( block => 'jsx' === block.lang ).code;
|
|
|
|
|
|
|
|
// react-live cannot resolve imports in real time, so we get rid of them
|
|
|
|
// (dependencies will be injected via the scope property).
|
|
|
|
code = code.replace( /^.*import.*$/gm, '' );
|
|
|
|
|
|
|
|
code = `${ code } render( <${ this.props.render } /> );`;
|
|
|
|
|
|
|
|
this.setState( { code } );
|
|
|
|
}
|
|
|
|
|
|
|
|
render() {
|
|
|
|
const { code } = this.state;
|
|
|
|
const scope = {
|
|
|
|
...wpComponents,
|
|
|
|
...components,
|
2018-11-15 18:16:23 +00:00
|
|
|
...pkgComponents,
|
2018-09-24 15:36:35 +00:00
|
|
|
Component,
|
|
|
|
withState,
|
|
|
|
PropTypes,
|
|
|
|
addFilter,
|
|
|
|
Gridicon,
|
|
|
|
};
|
|
|
|
|
|
|
|
return code ? (
|
|
|
|
<LiveProvider
|
|
|
|
code={ code }
|
|
|
|
scope={ scope }
|
|
|
|
className="woocommerce-devdocs__example"
|
|
|
|
noInline={ true }
|
|
|
|
>
|
|
|
|
<LiveError />
|
|
|
|
<LivePreview />
|
|
|
|
</LiveProvider>
|
|
|
|
) : null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Example;
|