lbry-desktop/ui/effects/use-screensize.js

61 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-02-05 16:34:51 +01:00
// @flow
2020-08-21 17:49:13 +02:00
// Widths are taken from "ui/scss/init/vars.scss"
2022-02-04 19:37:46 +01:00
import React, { useRef } from 'react';
2022-02-05 16:34:51 +01:00
const DEFAULT_SCREEN_SIZE = 1080;
2020-08-21 17:49:13 +02:00
2022-02-05 16:34:51 +01:00
export function useWindowSize() {
2020-08-21 17:49:13 +02:00
const isWindowClient = typeof window === 'object';
2022-02-05 16:34:51 +01:00
const [windowSize, setWindowSize] = React.useState(isWindowClient ? window.innerWidth : DEFAULT_SCREEN_SIZE);
2020-08-21 17:49:13 +02:00
React.useEffect(() => {
function setSize() {
2022-02-05 16:34:51 +01:00
setWindowSize(window.innerWidth);
2020-08-21 17:49:13 +02:00
}
if (isWindowClient) {
window.addEventListener('resize', setSize);
return () => window.removeEventListener('resize', setSize);
}
2022-02-05 16:34:51 +01:00
}, [isWindowClient]);
return windowSize;
}
function useHasWindowWidthChangedEnough(comparisonFn: (windowSize: number) => boolean) {
const isWindowClient = typeof window === 'object';
const initialState = isWindowClient ? comparisonFn(window.innerWidth) : comparisonFn(DEFAULT_SCREEN_SIZE);
const [windowSize, setWindowSize] = React.useState(initialState);
const prev = useRef(window.innerWidth);
React.useEffect(() => {
function setSize() {
const curr = comparisonFn(window.innerWidth);
if (prev !== curr) {
setWindowSize(curr);
prev.current = curr;
}
}
if (isWindowClient) {
window.addEventListener('resize', setSize);
return () => window.removeEventListener('resize', setSize);
}
}, [isWindowClient]);
2020-08-21 17:49:13 +02:00
return windowSize;
}
2020-08-10 22:47:39 +02:00
export function useIsMobile() {
2022-02-05 16:34:51 +01:00
return useHasWindowWidthChangedEnough((windowSize) => windowSize < 901);
2020-08-10 22:47:39 +02:00
}
export function useIsMediumScreen() {
2022-02-05 16:34:51 +01:00
return useHasWindowWidthChangedEnough((windowSize) => windowSize < 1151);
2020-08-21 17:49:13 +02:00
}
export function useIsLargeScreen() {
2022-02-05 16:34:51 +01:00
return useHasWindowWidthChangedEnough((windowSize) => windowSize > 1600);
2020-08-10 22:47:39 +02:00
}