MCPcopy Create free account
hub / github.com/adobe/react-spectrum / useViewportSize

Function useViewportSize

packages/react-aria/src/utils/useViewportSize.ts:26–98  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

24let visualViewport = typeof document !== 'undefined' && window.visualViewport;
25
26export function useViewportSize(): ViewportSize {
27 let isSSR = useIsSSR();
28 let [size, setSize] = useState(() => (isSSR ? {width: 0, height: 0} : getViewportSize()));
29
30 useEffect(() => {
31 let updateSize = (newSize: ViewportSize) => {
32 setSize(size => {
33 if (newSize.width === size.width && newSize.height === size.height) {
34 return size;
35 }
36 return newSize;
37 });
38 };
39
40 // Use visualViewport api to track available height even on iOS virtual keyboard opening
41 let onResize = () => {
42 // Ignore updates when zoomed.
43 if (visualViewport && visualViewport.scale > 1) {
44 return;
45 }
46
47 updateSize(getViewportSize());
48 };
49
50 // When closing the keyboard, WebKit on iOS does not fire the visual viewport resize event until the animation is complete.
51 // We can anticipate this and resize early by handling the blur event and using the layout size.
52 let frame: number;
53 let onBlur = (e: FocusEvent) => {
54 if (visualViewport && visualViewport.scale > 1) {
55 return;
56 }
57
58 if (willOpenKeyboard(getEventTarget(e) as Element)) {
59 // Wait one frame to see if a new element gets focused.
60 frame = requestAnimationFrame(() => {
61 let activeElement = getActiveElement();
62 if (!activeElement || !willOpenKeyboard(activeElement)) {
63 updateSize({
64 width: document.documentElement.clientWidth,
65 height: document.documentElement.clientHeight
66 });
67 }
68 });
69 }
70 };
71
72 updateSize(getViewportSize());
73
74 if (isIOS() && isWebKit()) {
75 window.addEventListener('blur', onBlur, true);
76 }
77
78 if (!visualViewport) {
79 window.addEventListener('resize', onResize);
80 } else {
81 visualViewport.addEventListener('resize', onResize);
82 }
83

Callers 5

ExampleFunction · 0.90
ModalOverlayInnerFunction · 0.90
Modal.tsxFile · 0.90
Tray.tsxFile · 0.90
FullWidthFunction · 0.90

Calls 5

useIsSSRFunction · 0.90
getViewportSizeFunction · 0.85
updateSizeFunction · 0.85
addEventListenerMethod · 0.80
removeEventListenerMethod · 0.80

Tested by

no test coverage detected