@carbon/react
Version:
React components for the Carbon Design System
98 lines (96 loc) • 2.59 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2026
*
* 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 { usePrefix } from "../../internal/usePrefix.js";
import { LayerContext } from "../Layer/LayerContext.js";
import { useMatchMedia } from "../../internal/useMatchMedia.js";
import classNames from "classnames";
import React, { useMemo } from "react";
import PropTypes from "prop-types";
import { jsx } from "react/jsx-runtime";
//#region src/components/Theme/index.tsx
/**
* 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.
*/
const ThemeContext = React.createContext({ theme: "white" });
const GlobalTheme = React.forwardRef(({ children, theme }, ref) => {
const value = useMemo(() => {
return { theme };
}, [theme]);
const childrenWithProps = React.cloneElement(children, { ref });
return /* @__PURE__ */ jsx(ThemeContext.Provider, {
value,
children: childrenWithProps
});
});
GlobalTheme.propTypes = {
children: PropTypes.node,
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 = classNames(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(() => {
return {
theme,
isDark: theme && ["g90", "g100"].includes(theme)
};
}, [theme]);
const BaseComponentAsAny = BaseComponent;
return /* @__PURE__ */ jsx(ThemeContext.Provider, {
value,
children: /* @__PURE__ */ jsx(LayerContext.Provider, {
value: 1,
children: /* @__PURE__ */ jsx(BaseComponentAsAny, {
...rest,
className
})
})
});
}
Theme.propTypes = {
as: PropTypes.oneOfType([
PropTypes.func,
PropTypes.string,
PropTypes.elementType
]),
children: PropTypes.node,
className: PropTypes.string,
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)");
}
//#endregion
export { GlobalTheme, Theme, ThemeContext, usePrefersDarkScheme, useTheme };