@atlaskit/editor-common
Version:
A package that contains common classes and components for editor and renderer
68 lines • 1.75 kB
JavaScript
import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import React, { Component } from 'react';
export const withImageLoader = Wrapped => class WithImageLoader extends Component {
constructor(...args) {
super(...args);
_defineProperty(this, "state", {
imageStatus: 'loading'
});
_defineProperty(this, "onLoad", () => {
this.setState({
imageStatus: 'complete'
});
const {
onExternalImageLoaded
} = this.props;
if (onExternalImageLoaded && this.img) {
onExternalImageLoaded({
width: this.img.naturalWidth,
height: this.img.naturalHeight
});
}
});
_defineProperty(this, "onError", () => {
this.setState({
imageStatus: 'error'
});
});
}
componentDidMount() {
this.fetchImage(this.props);
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.url !== this.props.url) {
this.setState({
imageStatus: 'loading'
});
this.fetchImage(nextProps);
}
}
componentWillUnmount() {
if (this.img) {
this.img.removeEventListener('load', this.onLoad);
this.img.removeEventListener('error', this.onError);
this.img = null;
}
}
fetchImage({
url
}) {
if (url) {
if (!this.img) {
this.img = new Image();
this.img.addEventListener('load', this.onLoad);
this.img.addEventListener('error', this.onError);
}
this.img.src = url;
}
}
render() {
const {
imageStatus
} = this.state;
return /*#__PURE__*/React.createElement(Wrapped, _extends({}, this.props, {
imageStatus: imageStatus
}));
}
};