@carbon/react
Version:
React components for the Carbon Design System
111 lines (106 loc) • 3.08 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { extends as _extends } from '../../_virtual/_rollupPluginBabelHelpers.js';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React, { useMemo } from 'react';
import { usePrefix } from '../../internal/usePrefix.js';
import { LayerContext } from '../Layer/LayerContext.js';
import { useMatchMedia } from '../../internal/useMatchMedia.js';
const ThemeContext = /*#__PURE__*/React.createContext({
theme: 'white'
});
const GlobalTheme = /*#__PURE__*/React.forwardRef(function GlobalTheme({
children,
theme
}, ref) {
const value = useMemo(() => {
return {
theme
};
}, [theme]);
const childrenWithProps = /*#__PURE__*/React.cloneElement(children, {
ref: ref
});
return /*#__PURE__*/React.createElement(ThemeContext.Provider, {
value: value
}, childrenWithProps);
});
GlobalTheme.propTypes = {
/**
* Provide child elements to be rendered inside of `GlobalTheme`, this is
* typically the root of your app
*/
children: PropTypes.node,
/**
* Specify the global theme for your app
*/
theme: PropTypes.oneOf(['white', 'g10', 'g90', 'g100'])
};
/**
* Specify the theme to be applied to a page, or a region in a page
*/
function Theme({
as: BaseComponent = 'div',
className: customClassName,
theme,
...rest
}) {
const prefix = usePrefix();
const className = cx(customClassName, {
[`${prefix}--white`]: theme === 'white',
[`${prefix}--g10`]: theme === 'g10',
[`${prefix}--g90`]: theme === 'g90',
[`${prefix}--g100`]: theme === 'g100',
[`${prefix}--layer-one`]: true
});
const value = React.useMemo(() => {
const isDark = theme && ['g90', 'g100'].includes(theme);
return {
theme,
isDark
};
}, [theme]);
const BaseComponentAsAny = BaseComponent;
return /*#__PURE__*/React.createElement(ThemeContext.Provider, {
value: value
}, /*#__PURE__*/React.createElement(LayerContext.Provider, {
value: 1
}, /*#__PURE__*/React.createElement(BaseComponentAsAny, _extends({}, rest, {
className: className
}))));
}
Theme.propTypes = {
/**
* Specify a custom component or element to be rendered as the top-level
* element in the component
*/
as: PropTypes.oneOfType([PropTypes.func, PropTypes.string, PropTypes.elementType]),
/**
* Provide child elements to be rendered inside of `Theme`
*/
children: PropTypes.node,
/**
* Provide a custom class name to be used on the outermost element rendered by
* the component
*/
className: PropTypes.string,
/**
* Specify the theme
*/
theme: PropTypes.oneOf(['white', 'g10', 'g90', 'g100'])
};
/**
* Get access to the current theme
*/
function useTheme() {
return React.useContext(ThemeContext);
}
function usePrefersDarkScheme() {
return useMatchMedia('(prefers-color-scheme: dark)');
}
export { GlobalTheme, Theme, ThemeContext, usePrefersDarkScheme, useTheme };