1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | var tslib_1 = require("tslib");
|
---|
4 | var react_1 = require("react");
|
---|
5 | var useRafState_1 = tslib_1.__importDefault(require("./useRafState"));
|
---|
6 | var util_1 = require("./misc/util");
|
---|
7 | var useWindowSize = function (_a) {
|
---|
8 | var _b = _a === void 0 ? {} : _a, _c = _b.initialWidth, initialWidth = _c === void 0 ? Infinity : _c, _d = _b.initialHeight, initialHeight = _d === void 0 ? Infinity : _d, onChange = _b.onChange;
|
---|
9 | // Use the useRafState hook to maintain the current window size (width and height)
|
---|
10 | var _e = useRafState_1.default({
|
---|
11 | width: util_1.isBrowser ? window.innerWidth : initialWidth,
|
---|
12 | height: util_1.isBrowser ? window.innerHeight : initialHeight,
|
---|
13 | }), state = _e[0], setState = _e[1];
|
---|
14 | react_1.useEffect(function () {
|
---|
15 | // Only run the effect on the browser (to avoid issues with SSR)
|
---|
16 | if (util_1.isBrowser) {
|
---|
17 | var handler_1 = function () {
|
---|
18 | var width = window.innerWidth;
|
---|
19 | var height = window.innerHeight;
|
---|
20 | // Update the state with the new window size
|
---|
21 | setState({
|
---|
22 | width: width,
|
---|
23 | height: height,
|
---|
24 | });
|
---|
25 | // If an onChange callback is provided, call it with the new dimensions
|
---|
26 | if (onChange)
|
---|
27 | onChange(width, height);
|
---|
28 | };
|
---|
29 | // Add event listener for the resize event
|
---|
30 | util_1.on(window, 'resize', handler_1);
|
---|
31 | // Cleanup function to remove the event listener when the component is unmounted (it's for performance optimization)
|
---|
32 | return function () {
|
---|
33 | util_1.off(window, 'resize', handler_1);
|
---|
34 | };
|
---|
35 | }
|
---|
36 | }, []);
|
---|
37 | // Return the current window size (width and height)
|
---|
38 | return state;
|
---|
39 | };
|
---|
40 | exports.default = useWindowSize;
|
---|