UNPKG

@carbon/ibm-products

Version:
59 lines (57 loc) 1.74 kB
/** * Copyright IBM Corp. 2020, 2026 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ require("../../../_virtual/_rolldown/runtime.js"); const require_useIsomorphicEffect = require("./useIsomorphicEffect.js"); let react = require("react"); //#region src/global/js/hooks/useWindowResize.js /** * Copyright IBM Corp. 2022, 2023 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ const windowExists = typeof window !== `undefined`; const getWindowSize = () => { if (!windowExists) return { innerHeight: 0, innerWidth: 0, outerHeight: 0, outerWidth: 0 }; const { innerHeight, innerWidth, outerHeight, outerWidth } = { ...window }; return { innerHeight, innerWidth, outerHeight, outerWidth }; }; const useWindowResize = (effect, deps, throttleInterval = 0) => { const windowSize = (0, react.useRef)({}); const throttleTimeout = (0, react.useRef)(null); const doGetWindowSize = () => { const newVal = { previous: windowSize.current, current: getWindowSize() }; effect(newVal); windowSize.current = newVal.current; throttleTimeout.current = null; }; require_useIsomorphicEffect.useIsomorphicEffect(() => { const handleResize = () => { if (throttleInterval) { if (throttleTimeout.current === null) throttleTimeout.current = setTimeout(doGetWindowSize, throttleInterval); } else doGetWindowSize(); }; window.addEventListener("resize", handleResize); doGetWindowSize(); return () => window.removeEventListener("resize", handleResize); }, deps); }; //#endregion exports.useWindowResize = useWindowResize;