-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseSize.tsx
108 lines (90 loc) Β· 2.51 KB
/
useSize.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import * as React from 'react';
import { isBrowser, off, on } from './misc/util';
const { useState, useEffect, useRef } = React;
const DRAF = (callback: () => void) => setTimeout(callback, 35);
export type Element = ((state: State) => React.ReactElement<any>) | React.ReactElement<any>;
export interface State {
width: number;
height: number;
}
const useSize = (
element: Element,
{ width = Infinity, height = Infinity }: Partial<State> = {}
): [React.ReactElement<any>, State] => {
if (!isBrowser) {
return [
typeof element === 'function' ? element({ width, height }) : element,
{ width, height },
];
}
// eslint-disable-next-line react-hooks/rules-of-hooks
const [state, setState] = useState<State>({ width, height });
if (typeof element === 'function') {
element = element(state);
}
const style = element.props.style || {};
// eslint-disable-next-line react-hooks/rules-of-hooks
const ref = useRef<HTMLIFrameElement | null>(null);
let window: Window | null = null;
const setSize = () => {
const iframe = ref.current;
const size = iframe
? {
width: iframe.offsetWidth,
height: iframe.offsetHeight,
}
: { width, height };
setState(size);
};
const onWindow = (windowToListenOn: Window) => {
on(windowToListenOn, 'resize', setSize);
DRAF(setSize);
};
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
const iframe: HTMLIFrameElement | null = ref.current;
if (!iframe) {
// iframe will be undefined if component is already unmounted
return;
}
if (iframe.contentWindow) {
window = iframe.contentWindow!;
onWindow(window);
} else {
const onLoad = () => {
on(iframe, 'load', onLoad);
window = iframe.contentWindow!;
onWindow(window);
};
off(iframe, 'load', onLoad);
}
return () => {
if (window && window.removeEventListener) {
off(window, 'resize', setSize);
}
};
}, []);
style.position = 'relative';
const sized = React.cloneElement(
element,
{ style },
...[
React.createElement('iframe', {
ref,
style: {
background: 'transparent',
border: 'none',
height: '100%',
left: 0,
position: 'absolute',
top: 0,
width: '100%',
zIndex: -1,
},
}),
...React.Children.toArray(element.props.children),
]
);
return [sized, state];
};
export default useSize;