rax-image
Version:
Image component for Rax.
88 lines (73 loc) • 2.9 kB
JavaScript
var _excluded = ["source", "fallbackSource", "onLoad", "onError", "style", "resizeMode", "loading"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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); }
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; }
import { createElement, useState, useCallback, forwardRef } from 'rax';
import EMPTY_SOURCE from '../utils/emptySource';
var Image = forwardRef(function (_ref, ref) {
var source = _ref.source,
fallbackSource = _ref.fallbackSource,
onLoad = _ref.onLoad,
onError = _ref.onError,
style = _ref.style,
resizeMode = _ref.resizeMode,
loading = _ref.loading,
rest = _objectWithoutPropertiesLoose(_ref, _excluded);
source = source || EMPTY_SOURCE;
fallbackSource = fallbackSource || EMPTY_SOURCE;
var nativeProps = rest;
var _useState = useState({}),
errorState = _useState[0],
setErrorState = _useState[1];
nativeProps.onError = useCallback(function (e) {
if (errorState.uri === undefined) {
setErrorState({
uri: source.uri
});
}
onError && onError(e);
}, [source.uri, onError, errorState]);
nativeProps.onLoad = useCallback(function (e) {
if (e && e.success) {
// weex
onLoad && onLoad(e);
} else if ( // alicdn will return an 1x1 img when img is not loaded successfully
e && e.currentTarget && e.currentTarget.naturalWidth > 1 && e.currentTarget.naturalHeight > 1) {
// web
onLoad && onLoad(e);
} else {
if (errorState.uri === undefined) {
setErrorState({
uri: source.uri
});
}
onError && onError(e);
}
}, [onLoad, onError]);
if (errorState.uri !== undefined) {
if (errorState.uri !== source.uri) {
errorState.uri = undefined;
} else if (fallbackSource.uri != null) {
source = fallbackSource;
}
}
var _source = source,
width = _source.width,
height = _source.height,
uri = _source.uri;
nativeProps.src = uri;
nativeProps.style = _extends({
width: width,
height: height
}, style);
if (loading) {
nativeProps.loading = loading;
} // for cover and contain
resizeMode = resizeMode || nativeProps.style.resizeMode;
if (resizeMode) {
nativeProps.style.objectFit = resizeMode;
}
return createElement("img", _extends({}, nativeProps, {
ref: ref
}));
});
export default Image;