import { getScrollBarSize } from "./get-scrollbar-size"; /** * 管理弹窗/抽屉等组件层级 */ let stack: string[] = []; function hasScrollbar() { return document.body.scrollHeight > window.innerHeight; } function setBodyStyle(style: React.CSSProperties): React.CSSProperties { const prevStyle: React.CSSProperties = {}; const styleKeys = Object.keys(style); styleKeys.forEach(key => { prevStyle[key] = document.body.style[key]; }); styleKeys.forEach(key => { document.body.style[key] = style[key]; }); return prevStyle; } let originalStyle: React.CSSProperties = {}; function push(id: string) { stack.push(id); if (stack.length === 1) { originalStyle = setBodyStyle({ overflow: "hidden", overflowX: "hidden", overflowY: "hidden", position: "relative", width: hasScrollbar() ? `calc(100% - ${getScrollBarSize()}px)` : undefined, }); } } function remove(id: string) { stack = stack.filter(i => i !== id); if (!stack.length) { setBodyStyle(originalStyle); originalStyle = {}; } } export const zStack = { push, remove, get top() { return stack[stack.length - 1]; }, get length() { return stack.length; }, };