UNPKG

@elastic/eui

Version:

Elastic UI Component Library

250 lines (246 loc) 15.9 kB
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); } import { css as _css } from "@emotion/react"; var _excluded = ["cloneElement", "className"]; var _templateObject; 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. */ import React, { useContext, useEffect, useRef, useMemo, useState, useCallback, Fragment } from 'react'; import { Global } from '@emotion/react'; import isEqual from 'lodash/isEqual'; import { cloneElementWithCss } from '../emotion'; import { css, cx } from '../emotion/css'; import { CurrentEuiBreakpointProvider } from '../breakpoint/current_breakpoint'; import { EuiSystemContext, EuiThemeContext, EuiNestedThemeContext, EuiModificationsContext, EuiColorModeContext, EuiHighContrastModeContext, DEFAULTS } from './context'; import { EuiEmotionThemeProvider } from './emotion'; import { EuiThemeMemoizedStylesProvider } from './style_memoization'; import { useHighContrastModifications } from './high_contrast_overrides'; import { buildTheme, getColorMode, getComputed, mergeDeep } from './utils'; import { EUI_VIS_COLOR_STORE } from '../color'; import { jsx as ___EmotionJSX } from "@emotion/react"; export var 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 = useContext(EuiNestedThemeContext), isGlobalTheme = _useContext.isGlobalTheme, bodyColor = _useContext.bodyColor, globalCSSVariables = _useContext.globalCSSVariables, setGlobalCSSVariables = _useContext.setGlobalCSSVariables; var parentSystem = useContext(EuiSystemContext); var parentModifications = useContext(EuiModificationsContext); var parentColorMode = useContext(EuiColorModeContext); var parentHighContrastMode = useContext(EuiHighContrastModeContext); var parentTheme = useContext(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 = useMemo(function () { return isGlobalTheme || _modifications !== null && _modifications !== void 0 && _modifications.breakpoint ? CurrentEuiBreakpointProvider : Fragment; }, [isGlobalTheme, _modifications]); var _useState = useState(_system || parentSystem), _useState2 = _slicedToArray(_useState, 2), system = _useState2[0], setSystem = _useState2[1]; var prevSystemKey = useRef(system.key); var _useState3 = useState(mergeDeep(parentModifications, _modifications)), _useState4 = _slicedToArray(_useState3, 2), modifications = _useState4[0], setModifications = _useState4[1]; var prevModifications = useRef(modifications); var _useState5 = useState(getColorMode(_colorMode, parentColorMode, isForced)), _useState6 = _slicedToArray(_useState5, 2), colorMode = _useState6[0], setColorMode = _useState6[1]; var prevColorMode = useRef(colorMode); var highContrastMode = 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 = useRef(highContrastMode); var modificationsWithHighContrast = useHighContrastModifications({ highContrastMode: highContrastMode, colorMode: colorMode, system: system, modifications: modifications }); var isParentTheme = useRef(isGlobalTheme ? prevSystemKey.current === DEFAULTS.system.key && colorMode === DEFAULTS.colorMode && highContrastMode === DEFAULTS.highContrastMode && !_modifications : prevSystemKey.current === parentSystem.key && colorMode === parentColorMode && highContrastMode === parentHighContrastMode && isEqual(parentModifications, modifications)); var updateVisColorStore = useCallback(function (theme, isGlobalTheme) { if (isGlobalTheme) { EUI_VIS_COLOR_STORE.setVisColors(theme.colors.vis); } }, []); var getInitialTheme = function getInitialTheme() { var theme = getComputed(system, buildTheme(modificationsWithHighContrast, "_".concat(system.key)), colorMode, highContrastMode); setTimeout(function () { updateVisColorStore(theme, isGlobalTheme); }); return theme; }; var _useState7 = 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]; useEffect(function () { var newSystem = _system || parentSystem; if (prevSystemKey.current !== newSystem.key) { setSystem(newSystem); prevSystemKey.current = newSystem.key; isParentTheme.current = false; } }, [_system, parentSystem, theme, updateVisColorStore]); useEffect(function () { updateVisColorStore(theme, isGlobalTheme); }, [theme, colorMode, isGlobalTheme, updateVisColorStore]); useEffect(function () { var newModifications = mergeDeep(parentModifications, _modifications); if (!isEqual(prevModifications.current, newModifications)) { setModifications(newModifications); prevModifications.current = newModifications; isParentTheme.current = false; } }, [_modifications, parentModifications]); useEffect(function () { var newColorMode = getColorMode(_colorMode, parentColorMode, isForced); if (!isEqual(newColorMode, prevColorMode.current)) { setColorMode(newColorMode); prevColorMode.current = newColorMode; isParentTheme.current = false; } }, [_colorMode, parentColorMode, isForced]); useEffect(function () { if (prevHighContrastMode.current !== highContrastMode) { isParentTheme.current = false; } }, [highContrastMode]); 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 = getComputed(system, buildTheme(enhancedModifications, "_".concat(system.key)), colorMode, highContrastMode); setTheme(rebuiltTheme); } }, [colorMode, highContrastMode, system, modificationsWithHighContrast, modifications]); var _useState9 = useState(), _useState10 = _slicedToArray(_useState9, 2), themeCSSVariables = _useState10[0], _setThemeCSSVariables = _useState10[1]; var setThemeCSSVariables = 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 = 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: 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 = 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: 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 cloneElementWithCss(children, _objectSpread(_objectSpread({}, props), {}, { className: cx(children.props.className, props.className) })); } else { return ___EmotionJSX("span", _extends({}, props, { className: cx('euiThemeProvider', props.className) }), children); } }, [isGlobalTheme, themeCSSVariables, nestedThemeContext, wrapperProps, children]); return ___EmotionJSX(React.Fragment, null, isGlobalTheme && themeCSSVariables && ___EmotionJSX(Global, { styles: /*#__PURE__*/_css({ ':root': themeCSSVariables }, ";label:EuiThemeProvider;") }), ___EmotionJSX(EuiColorModeContext.Provider, { value: colorMode }, ___EmotionJSX(EuiHighContrastModeContext.Provider, { value: highContrastMode }, ___EmotionJSX(EuiSystemContext.Provider, { value: system }, ___EmotionJSX(EuiModificationsContext.Provider, { value: modifications }, ___EmotionJSX(EuiThemeContext.Provider, { value: theme }, ___EmotionJSX(EuiNestedThemeContext.Provider, { value: nestedThemeContext }, ___EmotionJSX(EuiThemeMemoizedStylesProvider, null, ___EmotionJSX(EuiEmotionThemeProvider, null, ___EmotionJSX(EuiConditionalBreakpointProvider, null, renderedChildren)))))))))); };