11import React from 'react' ;
2+ import PropTypes from 'prop-types' ;
3+ import omit from 'lodash.omit' ;
4+ import { connect } from 'react-redux' ;
5+ import { setFontsLoaded } from '../reducers/fonts-loaded' ;
26
37/* Higher Order Component to provide behavior for loading fonts.
48 * @param {React.Component } WrappedComponent component to receive fontsLoaded prop
59 * @returns {React.Component } component with font loading behavior
610 */
711const FontLoaderHOC = function ( WrappedComponent ) {
812 class FontLoaderComponent extends React . Component {
9- constructor ( props ) {
10- super ( props ) ;
11- this . state = {
12- fontsLoaded : false
13- } ;
14- }
1513 componentDidMount ( ) {
14+ if ( this . props . fontsLoaded ) return ;
15+
1616 const getFontPromises = ( ) => {
1717 const fontPromises = [ ] ;
1818 // Browsers that support the font loader interface have an iterable document.fonts.values()
@@ -32,28 +32,43 @@ const FontLoaderHOC = function (WrappedComponent) {
3232 // objects get replaced and the old ones never resolve.
3333 if ( document . readyState === 'complete' ) {
3434 Promise . all ( getFontPromises ( ) ) . then ( ( ) => {
35- this . setState ( { fontsLoaded : true } ) ;
35+ this . props . onSetFontsLoaded ( ) ;
3636 } ) ;
3737 } else {
3838 document . onreadystatechange = ( ) => {
3939 if ( document . readyState !== 'complete' ) return ;
4040 document . onreadystatechange = null ;
4141 Promise . all ( getFontPromises ( ) ) . then ( ( ) => {
42- this . setState ( { fontsLoaded : true } ) ;
42+ this . props . onSetFontsLoaded ( ) ;
4343 } ) ;
4444 } ;
4545 }
4646 }
4747 render ( ) {
48+ const componentProps = omit ( this . props , [ 'onSetFontsLoaded' ] ) ;
4849 return (
4950 < WrappedComponent
50- fontsLoaded = { this . state . fontsLoaded }
51- { ...this . props }
51+ { ...componentProps }
5252 />
5353 ) ;
5454 }
5555 }
56- return FontLoaderComponent ;
56+
57+
58+ FontLoaderComponent . propTypes = {
59+ fontsLoaded : PropTypes . bool . isRequired ,
60+ onSetFontsLoaded : PropTypes . func . isRequired
61+ } ;
62+ const mapStateToProps = state => ( {
63+ fontsLoaded : state . scratchGui . fontsLoaded
64+ } ) ;
65+ const mapDispatchToProps = dispatch => ( {
66+ onSetFontsLoaded : ( ) => dispatch ( setFontsLoaded ( ) )
67+ } ) ;
68+ return connect (
69+ mapStateToProps ,
70+ mapDispatchToProps
71+ ) ( FontLoaderComponent ) ;
5772} ;
5873
5974export {
0 commit comments