UNPKG

@elastic/eui

Version:

Elastic UI Component Library

255 lines (251 loc) 17.4 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports.EuiThemeProvider = void 0; var _react = require("@emotion/react"); var _react2 = _interopRequireWildcard(require("react")); var _isEqual = _interopRequireDefault(require("lodash/isEqual")); var _emotion = require("../emotion"); var _css2 = require("../emotion/css"); var _current_breakpoint = require("../breakpoint/current_breakpoint"); var _context = require("./context"); var _emotion2 = require("./emotion"); var _style_memoization = require("./style_memoization"); var _high_contrast_overrides = require("./high_contrast_overrides"); var _utils = require("./utils"); var _color = require("../color"); var _excluded = ["cloneElement", "className"]; var _templateObject; function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], t.indexOf(o) >= 0 || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.indexOf(n) >= 0) continue; t[n] = r[n]; } return t; } function _taggedTemplateLiteral(e, t) { return t || (t = e.slice(0)), Object.freeze(Object.defineProperties(e, { raw: { value: Object.freeze(t) } })); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } /* * 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 = exports.EuiThemeProvider = function EuiThemeProvider(_ref) { var _system = _ref.theme, _colorMode = _ref.colorMode, _highContrastMode = _ref.highContrastMode, _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 parentHighContrastMode = (0, _react2.useContext)(_context.EuiHighContrastModeContext); var parentTheme = (0, _react2.useContext)(_context.EuiThemeContext); // If the user has an OS-wide high contrast theme applied, it will ignore EUI's // colors and light/dark mode. We should respect the user's system setting var isForced = parentHighContrastMode === 'forced'; // To reduce the number of window resize listeners, only render a // CurrentEuiBreakpointProvider for the top level parent theme, or for // nested themes only if modified breakpoint overrides are passed var EuiConditionalBreakpointProvider = (0, _react2.useMemo)(function () { return isGlobalTheme || _modifications !== null && _modifications !== void 0 && _modifications.breakpoint ? _current_breakpoint.CurrentEuiBreakpointProvider : _react2.Fragment; }, [isGlobalTheme, _modifications]); 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, isForced)), _useState6 = _slicedToArray(_useState5, 2), colorMode = _useState6[0], setColorMode = _useState6[1]; var prevColorMode = (0, _react2.useRef)(colorMode); var highContrastMode = (0, _react2.useMemo)(function () { if (isForced) return 'forced'; // System forced high contrast mode will always supercede application settings if (_highContrastMode === true) return 'preferred'; // Convert the boolean prop to our internal enum if (_highContrastMode === false) return false; // Allow `false` prop to override user/system preference return parentHighContrastMode; // Fall back to the parent/system setting }, [_highContrastMode, parentHighContrastMode, isForced]); var prevHighContrastMode = (0, _react2.useRef)(highContrastMode); var modificationsWithHighContrast = (0, _high_contrast_overrides.useHighContrastModifications)({ highContrastMode: highContrastMode, colorMode: colorMode, system: system, modifications: modifications }); var isParentTheme = (0, _react2.useRef)(isGlobalTheme ? prevSystemKey.current === _context.DEFAULTS.system.key && colorMode === _context.DEFAULTS.colorMode && highContrastMode === _context.DEFAULTS.highContrastMode && !_modifications : prevSystemKey.current === parentSystem.key && colorMode === parentColorMode && highContrastMode === parentHighContrastMode && (0, _isEqual.default)(parentModifications, modifications)); var updateVisColorStore = (0, _react2.useCallback)(function (theme, isGlobalTheme) { if (isGlobalTheme) { _color.EUI_VIS_COLOR_STORE.setVisColors(theme.colors.vis); } }, []); var getInitialTheme = function getInitialTheme() { var theme = (0, _utils.getComputed)(system, (0, _utils.buildTheme)(modificationsWithHighContrast, "_".concat(system.key)), colorMode, highContrastMode); setTimeout(function () { updateVisColorStore(theme, isGlobalTheme); }); return theme; }; var _useState7 = (0, _react2.useState)(isParentTheme.current && Object.keys(parentTheme).length ? _objectSpread({}, parentTheme) // Intentionally create a new object to break referential equality : getInitialTheme()), _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, theme, updateVisColorStore]); (0, _react2.useEffect)(function () { updateVisColorStore(theme, isGlobalTheme); }, [theme, colorMode, isGlobalTheme, updateVisColorStore]); (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, isForced); if (!(0, _isEqual.default)(newColorMode, prevColorMode.current)) { setColorMode(newColorMode); prevColorMode.current = newColorMode; isParentTheme.current = false; } }, [_colorMode, parentColorMode, isForced]); (0, _react2.useEffect)(function () { if (prevHighContrastMode.current !== highContrastMode) { isParentTheme.current = false; } }, [highContrastMode]); (0, _react2.useEffect)(function () { if (!isParentTheme.current) { /* Enables recomputation of component colors when flags are overridden on the provider by adding the respective key to modifications to trigger a recomputation. */ // NOTE: Keeping this as placeholder for potential future usage during Borealis changes // TODO: remove once visual refresh is completed and flags are obsolete var flagsToRecompute = []; var keys = {}; var forceRecomputeComponents = flagsToRecompute.some(function (item) { var _modifications$flags, _modifications$compon; if (!item) return false; if (Object.keys((_modifications$flags = modifications.flags) !== null && _modifications$flags !== void 0 ? _modifications$flags : {}).includes(item.flag) && !Object.keys((_modifications$compon = modifications.components) !== null && _modifications$compon !== void 0 ? _modifications$compon : {}).includes(item.componentKey)) { keys[item.componentKey] = { LIGHT: {}, DARK: {} }; return true; } return false; }); var componentModifications = forceRecomputeComponents ? { components: keys } : {}; // force recomputing of color & component tokens based on flag changes var enhancedModifications = _objectSpread(_objectSpread({}, modificationsWithHighContrast), componentModifications); var rebuiltTheme = (0, _utils.getComputed)(system, (0, _utils.buildTheme)(enhancedModifications, "_".concat(system.key)), colorMode, highContrastMode); setTheme(rebuiltTheme); } }, [colorMode, highContrastMode, system, modificationsWithHighContrast, 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) { var merged = _objectSpread(_objectSpread({}, previous), variables); Object.keys(merged).forEach(function (key) { if (merged[key] === null) { delete merged[key]; } }); return merged; }); }, []); var nestedThemeContext = (0, _react2.useMemo)(function () { return { isGlobalTheme: false, // The theme that determines the global body styles bodyColor: isGlobalTheme ? theme.colors.textParagraph : bodyColor, hasDifferentColorFromGlobalTheme: isGlobalTheme ? false : bodyColor !== theme.colors.textParagraph, colorClassName: (0, _css2.css)(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n label: euiColorMode-", ";\n color: ", ";\n "])), _colorMode || colorMode, theme.colors.textParagraph), setGlobalCSSVariables: isGlobalTheme ? setThemeCSSVariables : setGlobalCSSVariables, globalCSSVariables: isGlobalTheme ? themeCSSVariables : globalCSSVariables, setNearestThemeCSSVariables: setThemeCSSVariables, themeCSSVariables: themeCSSVariables }; }, [theme, isGlobalTheme, bodyColor, _colorMode, 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, _css2.cx)(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, _css2.cx)(children.props.className, props.className) })); } else { return (0, _react.jsx)("span", _extends({}, props, { className: (0, _css2.cx)('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.EuiHighContrastModeContext.Provider, { value: highContrastMode }, (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)(_style_memoization.EuiThemeMemoizedStylesProvider, null, (0, _react.jsx)(_emotion2.EuiEmotionThemeProvider, null, (0, _react.jsx)(EuiConditionalBreakpointProvider, null, renderedChildren)))))))))); };