@jy95/material-ui-image
Version:
Material style image with loading animation
242 lines (240 loc) • 13.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _react = require("react");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _CircularProgress = _interopRequireDefault(require("@mui/material/CircularProgress"));
var _colors = require("@mui/material/colors");
var _BrokenImage = _interopRequireDefault(require("@mui/icons-material/BrokenImage"));
var _excluded = ["animationDuration", "aspectRatio", "color", "cover", "disableError", "disableSpinner", "disableTransition", "errorIcon", "iconContainerStyle", "imageStyle", "loading", "onClick", "style"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
/**
* Images are ugly until they're loaded. Materialize it with material image! It will fade in like the material image loading pattern suggests.
* @see [Image loading patterns](https://material.io/guidelines/patterns/loading-images.html)
*/
var Image = /*#__PURE__*/function (_Component) {
_inherits(Image, _Component);
var _super = _createSuper(Image);
function Image(props) {
var _this;
_classCallCheck(this, Image);
_this = _super.call(this, props);
_defineProperty(_assertThisInitialized(_this), "handleLoadImage", function (e) {
_this.setState({
imageLoaded: true,
imageError: false
});
if (_this.props.onLoad) {
_this.props.onLoad(e);
}
});
_defineProperty(_assertThisInitialized(_this), "handleImageError", function (e) {
if (_this.props.src) {
_this.setState({
imageError: true
});
if (_this.props.onError) {
_this.props.onError(e);
}
}
});
_this.state = {
imageError: false,
imageLoaded: false,
src: _this.props.src
};
_this.image = /*#__PURE__*/(0, _react.createRef)();
return _this;
}
_createClass(Image, [{
key: "componentDidMount",
value: function componentDidMount() {
var img = this.image.current;
if (img && img.complete) {
// image loaded before the component rendered (e.g. SSR), see #43 and #51
if (img.naturalWidth === 0) {
this.handleImageError();
} else {
this.handleLoadImage();
}
}
}
}, {
key: "getStyles",
value: function getStyles() {
var _this$props = this.props,
animationDuration = _this$props.animationDuration,
aspectRatio = _this$props.aspectRatio,
cover = _this$props.cover,
color = _this$props.color,
imageStyle = _this$props.imageStyle,
disableTransition = _this$props.disableTransition,
iconContainerStyle = _this$props.iconContainerStyle,
style = _this$props.style;
var imageTransition = !disableTransition && {
opacity: this.state.imageLoaded ? 1 : 0,
filterBrightness: this.state.imageLoaded ? 100 : 0,
filterSaturate: this.state.imageLoaded ? 100 : 20,
transition: "\n filterBrightness ".concat(animationDuration * 0.75, "ms cubic-bezier(0.4, 0.0, 0.2, 1),\n filterSaturate ").concat(animationDuration, "ms cubic-bezier(0.4, 0.0, 0.2, 1),\n opacity ").concat(animationDuration / 2, "ms cubic-bezier(0.4, 0.0, 0.2, 1)")
};
var styles = {
root: _objectSpread({
backgroundColor: color,
paddingTop: "calc(1 / ".concat(aspectRatio, " * 100%)"),
position: 'relative'
}, style),
image: _objectSpread(_objectSpread({
width: '100%',
height: '100%',
position: 'absolute',
objectFit: cover ? 'cover' : 'inherit',
top: 0,
left: 0
}, imageTransition), imageStyle),
iconContainer: _objectSpread({
width: '100%',
height: '100%',
position: 'absolute',
top: 0,
left: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
pointerEvents: 'none'
}, iconContainerStyle)
};
return styles;
}
}, {
key: "render",
value: function render() {
var styles = this.getStyles();
var _this$props2 = this.props,
animationDuration = _this$props2.animationDuration,
aspectRatio = _this$props2.aspectRatio,
color = _this$props2.color,
cover = _this$props2.cover,
disableError = _this$props2.disableError,
disableSpinner = _this$props2.disableSpinner,
disableTransition = _this$props2.disableTransition,
errorIcon = _this$props2.errorIcon,
iconContainerStyle = _this$props2.iconContainerStyle,
imageStyle = _this$props2.imageStyle,
loading = _this$props2.loading,
onClick = _this$props2.onClick,
style = _this$props2.style,
image = _objectWithoutProperties(_this$props2, _excluded);
return /*#__PURE__*/(0, _react.createElement)("div", {
style: styles.root,
onClick: onClick
}, image.src && /*#__PURE__*/(0, _react.createElement)("img", _extends({}, image, {
ref: this.image,
style: styles.image,
onLoad: this.handleLoadImage,
onError: this.handleImageError
})), /*#__PURE__*/(0, _react.createElement)("div", {
style: styles.iconContainer
}, !disableSpinner && !this.state.imageLoaded && !this.state.imageError && loading, !disableError && this.state.imageError && errorIcon));
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(props, state) {
if (state.src !== props.src) {
return {
imageError: false,
imageLoaded: false,
src: props.src
};
}
return null;
}
}]);
return Image;
}(_react.Component);
exports["default"] = Image;
Image.defaultProps = {
animationDuration: 3000,
aspectRatio: 1,
color: _colors.common.white,
disableError: false,
disableSpinner: false,
disableTransition: false,
errorIcon: /*#__PURE__*/(0, _react.createElement)(_BrokenImage["default"], {
style: {
width: 48,
height: 48,
color: '#e0e0e0'
}
}),
loading: /*#__PURE__*/(0, _react.createElement)(_CircularProgress["default"], {
size: 48
})
};
Image.propTypes = {
/** Duration of the fading animation, in milliseconds. */
animationDuration: _propTypes["default"].number,
/** Override aspect ratio. */
aspectRatio: _propTypes["default"].number,
/** Override the object fit to cover. */
cover: _propTypes["default"].bool,
/** Override the background color. */
color: _propTypes["default"].string,
/** Disables the error icon if set to true. */
disableError: _propTypes["default"].bool,
/** Disables the loading spinner if set to true. */
disableSpinner: _propTypes["default"].bool,
/** Disables the transition after load if set to true. */
disableTransition: _propTypes["default"].bool,
/** Override the error icon. */
errorIcon: _propTypes["default"].node,
/** Override the inline-styles of the container that contains the loading spinner and the error icon. */
iconContainerStyle: _propTypes["default"].object,
/** Override the inline-styles of the image. */
imageStyle: _propTypes["default"].object,
/** Override the loading component. */
loading: _propTypes["default"].node,
/** Fired when the user clicks on the image happened. */
onClick: _propTypes["default"].func,
/** Fired when the image failed to load. */
onError: _propTypes["default"].func,
/** Fired when the image finished loading. */
onLoad: _propTypes["default"].func,
/** Specifies the URL of an image. */
src: _propTypes["default"].string.isRequired,
/** Override the inline-styles of the root element. */
style: _propTypes["default"].object
};