UNPKG

1.92 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.Img = void 0;
4const jsx_runtime_1 = require("react/jsx-runtime");
5const react_1 = require("react");
6const delay_render_1 = require("./delay-render");
7const ImgRefForwarding = ({ onError, ...props }, ref) => {
8 const imageRef = (0, react_1.useRef)(null);
9 (0, react_1.useImperativeHandle)(ref, () => {
10 return imageRef.current;
11 });
12 const didGetError = (0, react_1.useCallback)((e) => {
13 var _a;
14 if (onError) {
15 onError(e);
16 }
17 else {
18 console.error('Error loading image with src:', (_a = imageRef.current) === null || _a === void 0 ? void 0 : _a.src, e, 'Handle the event using the onError() prop to make this message disappear.');
19 }
20 }, [onError]);
21 // If image source switches, make new handle
22 (0, react_1.useLayoutEffect)(() => {
23 const newHandle = (0, delay_render_1.delayRender)('Loading <Img> with src=' + props.src);
24 const { current } = imageRef;
25 const didLoad = () => {
26 (0, delay_render_1.continueRender)(newHandle);
27 };
28 if (current === null || current === void 0 ? void 0 : current.complete) {
29 (0, delay_render_1.continueRender)(newHandle);
30 }
31 else {
32 current === null || current === void 0 ? void 0 : current.addEventListener('load', didLoad, { once: true });
33 }
34 // If tag gets unmounted, clear pending handles because image is not going to load
35 return () => {
36 current === null || current === void 0 ? void 0 : current.removeEventListener('load', didLoad);
37 (0, delay_render_1.continueRender)(newHandle);
38 };
39 }, [props.src]);
40 return (0, jsx_runtime_1.jsx)("img", { ...props, ref: imageRef, onError: didGetError }, void 0);
41};
42exports.Img = (0, react_1.forwardRef)(ImgRefForwarding);