@elastic/eui
Version:
Elastic UI Component Library
45 lines (40 loc) • 2.81 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useWindowMediaMatcher = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
var useWindowMediaMatcher = exports.useWindowMediaMatcher = function useWindowMediaMatcher(mediaQuery) {
// Check typeof and use optional chaining for SSR or test environments
var _useState = (0, _react.useState)(function () {
var _window$matchMedia$ma, _window, _window$matchMedia;
return typeof window !== 'undefined' && ((_window$matchMedia$ma = (_window = window) === null || _window === void 0 || (_window$matchMedia = _window.matchMedia) === null || _window$matchMedia === void 0 || (_window$matchMedia = _window$matchMedia.call(_window, mediaQuery)) === null || _window$matchMedia === void 0 ? void 0 : _window$matchMedia.matches) !== null && _window$matchMedia$ma !== void 0 ? _window$matchMedia$ma : false);
}),
_useState2 = (0, _slicedToArray2.default)(_useState, 2),
mediaMatches = _useState2[0],
setMediaMatches = _useState2[1];
// Listen for system changes
(0, _react.useEffect)(function () {
var _window$matchMedia2, _window2, _window$matchMedia2$c, _window$matchMedia2$c2;
var eventListener = function eventListener(event) {
setMediaMatches(event.matches);
};
// Optional chaining here is for test environments - SSR should not run useEffect
(_window$matchMedia2 = (_window2 = window).matchMedia) === null || _window$matchMedia2 === void 0 || (_window$matchMedia2$c = (_window$matchMedia2$c2 = _window$matchMedia2.call(_window2, mediaQuery)).addEventListener) === null || _window$matchMedia2$c === void 0 || _window$matchMedia2$c.call(_window$matchMedia2$c2, 'change', eventListener);
// Clean up the listener on unmount
return function () {
var _window$matchMedia3, _window3, _window$matchMedia3$c, _window$matchMedia3$c2;
(_window$matchMedia3 = (_window3 = window).matchMedia) === null || _window$matchMedia3 === void 0 || (_window$matchMedia3$c = (_window$matchMedia3$c2 = _window$matchMedia3.call(_window3, mediaQuery)).removeEventListener) === null || _window$matchMedia3$c === void 0 || _window$matchMedia3$c.call(_window$matchMedia3$c2, 'change', eventListener);
};
}, [mediaQuery]);
return mediaMatches;
};