"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiThemeProvider = void 0;
var _react = require("@emotion/react");
var _react2 = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _css2 = require("@emotion/css");
var _isEqual = _interopRequireDefault(require("lodash/isEqual"));
var _emotion = require("../emotion");
var _context = require("./context");
var _emotion2 = require("./emotion");
var _utils = require("./utils");
var _excluded = ["cloneElement", "className"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /*
                                                                       * 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 EuiThemeProvider = function EuiThemeProvider(_ref) {
  var _system = _ref.theme,
    _colorMode = _ref.colorMode,
    _modifications = _ref.modify,
    children = _ref.children,
    wrapperProps = _ref.wrapperProps;
  var _useContext = (0, _react2.useContext)(_context.EuiNestedThemeContext),
    isGlobalTheme = _useContext.isGlobalTheme,
    bodyColor = _useContext.bodyColor,
    globalCSSVariables = _useContext.globalCSSVariables,
    setGlobalCSSVariables = _useContext.setGlobalCSSVariables;
  var parentSystem = (0, _react2.useContext)(_context.EuiSystemContext);
  var parentModifications = (0, _react2.useContext)(_context.EuiModificationsContext);
  var parentColorMode = (0, _react2.useContext)(_context.EuiColorModeContext);
  var parentTheme = (0, _react2.useContext)(_context.EuiThemeContext);
  var _useState = (0, _react2.useState)(_system || parentSystem),
    _useState2 = _slicedToArray(_useState, 2),
    system = _useState2[0],
    setSystem = _useState2[1];
  var prevSystemKey = (0, _react2.useRef)(system.key);
  var _useState3 = (0, _react2.useState)((0, _utils.mergeDeep)(parentModifications, _modifications)),
    _useState4 = _slicedToArray(_useState3, 2),
    modifications = _useState4[0],
    setModifications = _useState4[1];
  var prevModifications = (0, _react2.useRef)(modifications);
  var _useState5 = (0, _react2.useState)((0, _utils.getColorMode)(_colorMode, parentColorMode)),
    _useState6 = _slicedToArray(_useState5, 2),
    colorMode = _useState6[0],
    setColorMode = _useState6[1];
  var prevColorMode = (0, _react2.useRef)(colorMode);
  var isParentTheme = (0, _react2.useRef)(prevSystemKey.current === parentSystem.key && colorMode === parentColorMode && (0, _isEqual.default)(parentModifications, modifications));
  var _useState7 = (0, _react2.useState)(isParentTheme.current && Object.keys(parentTheme).length ? _objectSpread({}, parentTheme) // Intentionally create a new object to break referential equality
    : (0, _utils.getComputed)(system, (0, _utils.buildTheme)(modifications, "_".concat(system.key)), colorMode)),
    _useState8 = _slicedToArray(_useState7, 2),
    theme = _useState8[0],
    setTheme = _useState8[1];
  (0, _react2.useEffect)(function () {
    var newSystem = _system || parentSystem;
    if (prevSystemKey.current !== newSystem.key) {
      setSystem(newSystem);
      prevSystemKey.current = newSystem.key;
      isParentTheme.current = false;
    }
  }, [_system, parentSystem]);
  (0, _react2.useEffect)(function () {
    var newModifications = (0, _utils.mergeDeep)(parentModifications, _modifications);
    if (!(0, _isEqual.default)(prevModifications.current, newModifications)) {
      setModifications(newModifications);
      prevModifications.current = newModifications;
      isParentTheme.current = false;
    }
  }, [_modifications, parentModifications]);
  (0, _react2.useEffect)(function () {
    var newColorMode = (0, _utils.getColorMode)(_colorMode, parentColorMode);
    if (!(0, _isEqual.default)(newColorMode, prevColorMode.current)) {
      setColorMode(newColorMode);
      prevColorMode.current = newColorMode;
      isParentTheme.current = false;
    }
  }, [_colorMode, parentColorMode]);
  (0, _react2.useEffect)(function () {
    if (!isParentTheme.current) {
      setTheme((0, _utils.getComputed)(system, (0, _utils.buildTheme)(modifications, "_".concat(system.key)), colorMode));
    }
  }, [colorMode, system, modifications]);
  var _useState9 = (0, _react2.useState)(),
    _useState10 = _slicedToArray(_useState9, 2),
    themeCSSVariables = _useState10[0],
    _setThemeCSSVariables = _useState10[1];
  var setThemeCSSVariables = (0, _react2.useCallback)(function (variables) {
    return _setThemeCSSVariables(function (previous) {
      return _objectSpread(_objectSpread({}, previous), variables);
    });
  }, []);
  var nestedThemeContext = (0, _react2.useMemo)(function () {
    return {
      isGlobalTheme: false,
      // The theme that determines the global body styles
      bodyColor: isGlobalTheme ? theme.colors.text : bodyColor,
      hasDifferentColorFromGlobalTheme: isGlobalTheme ? false : bodyColor !== theme.colors.text,
      colorClassName: /*#__PURE__*/(0, _css2.css)("label:euiColorMode-", _colorMode, ";color:", theme.colors.text, ";;label:colorClassName;"),
      setGlobalCSSVariables: isGlobalTheme ? setThemeCSSVariables : setGlobalCSSVariables,
      globalCSSVariables: isGlobalTheme ? themeCSSVariables : globalCSSVariables,
      setNearestThemeCSSVariables: setThemeCSSVariables,
      themeCSSVariables: themeCSSVariables
    };
  }, [theme, isGlobalTheme, bodyColor, _colorMode, setGlobalCSSVariables, globalCSSVariables, setThemeCSSVariables, themeCSSVariables]);
  var renderedChildren = (0, _react2.useMemo)(function () {
    if (isGlobalTheme) {
      return children; // No wrapper
    }

    var _ref2 = wrapperProps || {},
      cloneElement = _ref2.cloneElement,
      className = _ref2.className,
      rest = _objectWithoutProperties(_ref2, _excluded);
    var props = _objectSpread(_objectSpread({}, rest), {}, {
      className: (0, _classnames.default)(className, nestedThemeContext.colorClassName)
    });
    // Condition avoids rendering an empty Emotion selector if no
    // theme-specific CSS variables have been set by child components
    if (themeCSSVariables) {
      props.css = _objectSpread({
        label: 'euiCSSVariables'
      }, themeCSSVariables);
    }
    if (cloneElement) {
      return (0, _emotion.cloneElementWithCss)(children, _objectSpread(_objectSpread({}, props), {}, {
        className: (0, _classnames.default)(children.props.className, props.className)
      }));
    } else {
      return (0, _react.jsx)("span", _extends({}, props, {
        className: (0, _classnames.default)('euiThemeProvider', props.className)
      }), children);
    }
  }, [isGlobalTheme, themeCSSVariables, nestedThemeContext, wrapperProps, children]);
  return (0, _react.jsx)(_react2.default.Fragment, null, isGlobalTheme && themeCSSVariables && (0, _react.jsx)(_react.Global, {
    styles: /*#__PURE__*/(0, _react.css)({
      ':root': themeCSSVariables
    }, ";label:EuiThemeProvider;")
  }), (0, _react.jsx)(_context.EuiColorModeContext.Provider, {
    value: colorMode
  }, (0, _react.jsx)(_context.EuiSystemContext.Provider, {
    value: system
  }, (0, _react.jsx)(_context.EuiModificationsContext.Provider, {
    value: modifications
  }, (0, _react.jsx)(_context.EuiThemeContext.Provider, {
    value: theme
  }, (0, _react.jsx)(_context.EuiNestedThemeContext.Provider, {
    value: nestedThemeContext
  }, (0, _react.jsx)(_emotion2.EuiEmotionThemeProvider, null, renderedChildren)))))));
};
exports.EuiThemeProvider = EuiThemeProvider;