@carbon/ibm-products
Version:
Carbon for IBM Products
80 lines (78 loc) • 2.52 kB
JavaScript
/**
* Copyright IBM Corp. 2020, 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.
*/
const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_useResizeObserver = require("../../../global/js/hooks/useResizeObserver.js");
let react = require("react");
react = require_runtime.__toESM(react);
//#region src/components/Tearsheet/next/StackContext.tsx
/**
* Copyright IBM Corp. 2025, 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.
*/
const StackContext = (0, react.createContext)(void 0);
const StackProvider = ({ children, stackStepSize = "lg" }) => {
const [stack, setStack] = (0, react.useState)([]);
const _containerRef = (0, react.useRef)(null);
const bufferMap = {
sm: .5,
md: .75,
lg: 1
};
const { width } = require_useResizeObserver.useResizeObserver(_containerRef);
const notifyStack = (0, react.useCallback)((id, open, container) => {
_containerRef.current = container;
setStack((prev) => {
if (open) {
if (prev.includes(id)) return [...prev.filter((i) => i !== id), id];
return [...prev, id];
} else return prev.filter((i) => i !== id);
});
}, []);
const getScaleFactor = (id) => {
const depth = getDepth(id);
const buffer = bufferMap[stackStepSize];
const bufferInPx = remToPx(buffer);
return depth > -1 ? (width - bufferInPx * 2 * depth) / width : 1;
};
const remToPx = (rem) => {
return rem * parseFloat(getComputedStyle(document.documentElement).fontSize);
};
const getDepth = (0, react.useCallback)((id) => {
const index = stack.indexOf(id);
if (index === -1) return -1;
return stack.length - 1 - index;
}, [stack]);
const getBlockSizeChange = (id) => {
const depth = getDepth(id);
const buffer = bufferMap[stackStepSize];
return `${remToPx(buffer) * depth}px`;
};
const context = {
stack,
notifyStack,
getScaleFactor,
getBlockSizeChange,
getDepth
};
return /* @__PURE__ */ react.default.createElement(StackContext.Provider, { value: context }, children);
};
const useStackContext = () => {
const context = (0, react.useContext)(StackContext);
if (context === void 0) return {
notifyStack: () => {},
stack: [],
getDepth: () => -1,
getScaleFactor: () => 1,
getBlockSizeChange: () => null
};
return context;
};
//#endregion
exports.StackProvider = StackProvider;
exports.useStackContext = useStackContext;