UNPKG

@carbon/react

Version:

React components for the Carbon Design System

81 lines (77 loc) 2.49 kB
/** * 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 React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { usePrefix } from '../../internal/usePrefix.js'; import { LayerContext } from './LayerContext.js'; import { levels, MAX_LEVEL, MIN_LEVEL } from './LayerLevel.js'; import { clamp } from '../../internal/clamp.js'; /** * A custom hook that will return information about the current layer. A common * field to pull from this is the `level` for the layer that the component that * calls this hook is currently in */ function useLayer() { const level = React.useContext(LayerContext); return { level }; } const Layer = /*#__PURE__*/React.forwardRef((props, ref) => { const { as, className: customClassName, children, level: overrideLevel, withBackground = false, ...rest } = props; const contextLevel = React.useContext(LayerContext); const level = overrideLevel ?? contextLevel; const prefix = usePrefix(); const className = cx(`${prefix}--layer-${levels[level]}`, { [`${prefix}--layer__with-background`]: withBackground }, customClassName); // The level should be between MIN_LEVEL and MAX_LEVEL const value = clamp(level + 1, MIN_LEVEL, MAX_LEVEL); const BaseComponent = as || 'div'; return /*#__PURE__*/React.createElement(LayerContext.Provider, { value: value }, /*#__PURE__*/React.createElement(BaseComponent, _extends({ ref: ref }, rest, { className: className }), children)); }); Layer.displayName = 'Layer'; Layer.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 layer level and override any existing levels based on hierarchy */ level: PropTypes.oneOf([0, 1, 2]), /** * Applies a css background-color set to $layer-background */ withBackground: PropTypes.bool }; export { Layer, useLayer };