hometown/app/javascript/mastodon/features/ui/components/bundle.js
Sorin Davidoi 348d6f5e75 Lazy load components (#3879)
* feat: Lazy-load routes

* feat: Lazy-load modals

* feat: Lazy-load columns

* refactor: Simplify Bundle API

* feat: Optimize bundles

* feat: Prevent flashing the waiting state

* feat: Preload commonly used bundles

* feat: Lazy load Compose reducers

* feat: Lazy load Notifications reducer

* refactor: Move all dynamic imports into one file

* fix: Minor bugs

* fix: Manually hydrate the lazy-loaded reducers

* refactor: Move all dynamic imports to async-components

* fix: Loading modal style

* refactor: Avoid converting the raw state for each lazy hydration

* refactor: Remove unused component

* refactor: Maintain modal name

* fix: Add as=script to preload link

* chore: Fix lint error

* fix(components/bundle): Check if timestamp is set when computing elapsed

* fix: Load compose reducers for the onboarding modal
2017-07-08 00:06:02 +02:00

97 lines
2.1 KiB
JavaScript

import React from 'react';
import PropTypes from 'prop-types';
const emptyComponent = () => null;
const noop = () => { };
class Bundle extends React.Component {
static propTypes = {
fetchComponent: PropTypes.func.isRequired,
loading: PropTypes.func,
error: PropTypes.func,
children: PropTypes.func.isRequired,
renderDelay: PropTypes.number,
onRender: PropTypes.func,
onFetch: PropTypes.func,
onFetchSuccess: PropTypes.func,
onFetchFail: PropTypes.func,
}
static defaultProps = {
loading: emptyComponent,
error: emptyComponent,
renderDelay: 0,
onRender: noop,
onFetch: noop,
onFetchSuccess: noop,
onFetchFail: noop,
}
state = {
mod: undefined,
forceRender: false,
}
componentWillMount() {
this.load(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.fetchComponent !== this.props.fetchComponent) {
this.load(nextProps);
}
}
componentDidUpdate () {
this.props.onRender();
}
componentWillUnmount () {
if (this.timeout) {
clearTimeout(this.timeout);
}
}
load = (props) => {
const { fetchComponent, onFetch, onFetchSuccess, onFetchFail, renderDelay } = props || this.props;
this.setState({ mod: undefined });
onFetch();
if (renderDelay !== 0) {
this.timestamp = new Date();
this.timeout = setTimeout(() => this.setState({ forceRender: true }), renderDelay);
}
return fetchComponent()
.then((mod) => {
this.setState({ mod: mod.default });
onFetchSuccess();
})
.catch((error) => {
this.setState({ mod: null });
onFetchFail(error);
});
}
render() {
const { loading: Loading, error: Error, children, renderDelay } = this.props;
const { mod, forceRender } = this.state;
const elapsed = this.timestamp ? (new Date() - this.timestamp) : renderDelay;
if (mod === undefined) {
return (elapsed >= renderDelay || forceRender) ? <Loading /> : null;
}
if (mod === null) {
return <Error onRetry={this.load} />;
}
return children(mod);
}
}
export default Bundle;