UNPKG

@carbon/ibm-products

Version:
77 lines (75 loc) 2.32 kB
/** * 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. */ import { useResizeObserver } from "../../../global/js/hooks/useResizeObserver.js"; import React, { createContext, useCallback, useContext, useRef, useState } from "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 = createContext(void 0); const StackProvider = ({ children, stackStepSize = "lg" }) => { const [stack, setStack] = useState([]); const _containerRef = useRef(null); const bufferMap = { sm: .5, md: .75, lg: 1 }; const { width } = useResizeObserver(_containerRef); const notifyStack = 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 = 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.createElement(StackContext.Provider, { value: context }, children); }; const useStackContext = () => { const context = useContext(StackContext); if (context === void 0) return { notifyStack: () => {}, stack: [], getDepth: () => -1, getScaleFactor: () => 1, getBlockSizeChange: () => null }; return context; }; //#endregion export { StackProvider, useStackContext };