@carbon/react
Version:
React components for the Carbon Design System
84 lines (79 loc) • 2.63 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.
*/
;
var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var PropTypes = require('prop-types');
var cx = require('classnames');
var usePrefix = require('../../internal/usePrefix.js');
var LayerContext = require('./LayerContext.js');
var LayerLevel = require('./LayerLevel.js');
var clamp = require('../../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.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.LayerContext);
const level = overrideLevel ?? contextLevel;
const prefix = usePrefix.usePrefix();
const className = cx(`${prefix}--layer-${LayerLevel.levels[level]}`, {
[`${prefix}--layer__with-background`]: withBackground
}, customClassName);
// The level should be between MIN_LEVEL and MAX_LEVEL
const value = clamp.clamp(level + 1, LayerLevel.MIN_LEVEL, LayerLevel.MAX_LEVEL);
const BaseComponent = as || 'div';
return /*#__PURE__*/React.createElement(LayerContext.LayerContext.Provider, {
value: value
}, /*#__PURE__*/React.createElement(BaseComponent, _rollupPluginBabelHelpers.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
};
exports.Layer = Layer;
exports.useLayer = useLayer;