-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
75 lines (60 loc) · 1.59 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { useEffect, useRef, useState } from 'react';
// interface Window extends EventTarget {
declare interface Window extends EventTarget {
readonly window: Window & typeof globalThis;
Image: {
prototype: HTMLImageElement;
new (): HTMLImageElement;
};
}
interface SizedTarget {
width: number;
height: number;
}
// type WindowProps = React.HTMLProps<HTMLElement>;
// interface WindowComponent extends React.StatelessComponent<WindowProps> {
// (props: WindowProps): React.ReactElement<HTMLElement>;
// }
const useImage = (src: string) => {
const ready = useRef(true);
const [loaded, setLoaded] = useState(false);
const [failed, setFailed] = useState(false);
const [dimensions, setDimensions] = useState({
width: 0,
height: 0,
});
useEffect(() => {
const win: Window = window;
const { Image } = win;
if (!src || !Image) {
return;
}
const image = new Image();
function isSizedTarget(t: any): t is SizedTarget {
return t && t.width !== undefined && t.height !== undefined;
}
image.onload = event => {
if (ready.current) {
if (isSizedTarget(event.target)) {
const { width, height } = event.target;
setLoaded(true);
setDimensions({ width, height });
}
}
};
image.onerror = () => {
if (ready.current) {
setLoaded(false);
setFailed(true);
}
};
image.src = src;
}, [src]);
useEffect(() => {
return () => {
ready.current = false;
};
}, []);
return { loaded, failed, dimensions };
};
export default useImage;