@elastic/eui
Version:
Elastic UI Component Library
57 lines (53 loc) • 2.53 kB
JavaScript
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
/*
* 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.
*/
import React, { createContext, useState, useEffect, useMemo, useCallback } from 'react';
import { keysOf } from '../../components/common';
import { useEuiTheme } from '../theme/hooks';
import { throttle } from '../throttle';
import { sortMapByLargeToSmallValues } from './_sorting';
import { jsx as ___EmotionJSX } from "@emotion/react";
export var CurrentEuiBreakpointContext = /*#__PURE__*/createContext(undefined);
/**
* Returns the current breakpoint based on window width.
* Typically only called by the top-level `EuiProvider` (to reduce the number
* of window resize listeners on the page). Also conditionally called if a
* nested `EuiThemeProvider` defines a `modify.breakpoint` override
*/
export var CurrentEuiBreakpointProvider = function CurrentEuiBreakpointProvider(_ref) {
var children = _ref.children;
// Obtain the breakpoints map from the EUI theme
var _useEuiTheme = useEuiTheme(),
breakpoints = _useEuiTheme.euiTheme.breakpoint;
// Ensure the breakpoints map is sorted from largest value to smallest
var sortedBreakpoints = useMemo(function () {
return sortMapByLargeToSmallValues(breakpoints);
}, [breakpoints]);
// Find the breakpoint (key) whose value is <= windowWidth starting with largest first
var getBreakpoint = useCallback(function (width) {
return keysOf(sortedBreakpoints).find(function (key) {
return sortedBreakpoints[key] <= width;
});
}, [sortedBreakpoints]);
var _useState = useState(typeof window !== 'undefined' ? getBreakpoint(window.innerWidth) : undefined),
_useState2 = _slicedToArray(_useState, 2),
currentBreakpoint = _useState2[0],
setCurrentBreakpoint = _useState2[1];
useEffect(function () {
var onWindowResize = throttle(function () {
setCurrentBreakpoint(getBreakpoint(window.innerWidth));
}, 50);
window.addEventListener('resize', onWindowResize);
return function () {
return window.removeEventListener('resize', onWindowResize);
};
}, [getBreakpoint]);
return ___EmotionJSX(CurrentEuiBreakpointContext.Provider, {
value: currentBreakpoint
}, children);
};