@carbon/react
Version:
React components for the Carbon Design System
67 lines (65 loc) • 2.05 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 "./LayerContext.js";
import { MAX_LEVEL, MIN_LEVEL, levels } from "./LayerLevel.js";
import { clamp } from "../../internal/clamp.js";
import classNames from "classnames";
import React from "react";
import PropTypes from "prop-types";
import { jsx } from "react/jsx-runtime";
//#region src/components/Layer/index.tsx
/**
* Copyright IBM Corp. 2016, 2025
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* 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() {
return { level: React.useContext(LayerContext) };
}
const Layer = 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 = classNames(`${prefix}--layer-${levels[level]}`, { [`${prefix}--layer__with-background`]: withBackground }, customClassName);
const value = clamp(level + 1, MIN_LEVEL, MAX_LEVEL);
const BaseComponent = as || "div";
return /* @__PURE__ */ jsx(LayerContext.Provider, {
value,
children: /* @__PURE__ */ jsx(BaseComponent, {
ref,
...rest,
className,
children
})
});
});
Layer.displayName = "Layer";
Layer.propTypes = {
as: PropTypes.oneOfType([
PropTypes.func,
PropTypes.string,
PropTypes.elementType
]),
children: PropTypes.node,
className: PropTypes.string,
level: PropTypes.oneOf([
0,
1,
2
]),
withBackground: PropTypes.bool
};
//#endregion
export { Layer, useLayer };