UNPKG

@ozen-ui/kit

Version:

React component library

78 lines (77 loc) 3.37 kB
import { __read, __spreadArray } from "tslib"; import { useEffect, useMemo, useState } from 'react'; import { isServer } from '../../../constants/environment'; import { useEventListener } from '../../../hooks/useEventListener'; import { useMultipleResizeObserver } from '../../../hooks/useMultipleResizeObserver'; import { isFunction } from '../../../utils/isFunction'; import { isNumber } from '../../../utils/number'; export var useBottomSheetBaseHeight = function (_a) { var contentRef = _a.contentRef, blocksRefs = _a.blocksRefs, customMaxHeightProp = _a.customMaxHeight, registerReady = _a.registerReady; var setReadyContentHeight = useMemo(function () { return registerReady('contentHeight'); }, [registerReady]); var setReadyMaxHeight = useMemo(function () { return registerReady('maxHeight'); }, [registerReady]); var getElementHeight = function (element) { var _a; var rect = element === null || element === void 0 ? void 0 : element.getBoundingClientRect(); return (_a = rect === null || rect === void 0 ? void 0 : rect.height) !== null && _a !== void 0 ? _a : 0; }; var getRawMaxHeight = function () { if (isServer) { return 0; } return window.innerHeight; }; var _b = __read(useState(0), 2), minHeight = _b[0], setMinHeight = _b[1]; var getCustomMaxHeight = function () { if (isFunction(customMaxHeightProp)) { return customMaxHeightProp({ maxHeight: getRawMaxHeight(), minHeight: minHeight, }); } return customMaxHeightProp; }; var checkHasCustomMaxHeight = function (customMaxHeight) { return isNumber(customMaxHeight); }; var calculateMaxHeight = function () { var customMaxHeight = getCustomMaxHeight(); if (checkHasCustomMaxHeight(customMaxHeight)) { return customMaxHeight; } return getRawMaxHeight(); }; var _c = __read(useState(function () { return calculateMaxHeight(); }), 2), maxHeight = _c[0], setMaxHeightState = _c[1]; var calculateMinHeight = function (maxHeight) { var contentHeight = getElementHeight(contentRef.current); var notContentBlocksHeight = 0; Object.values(blocksRefs.current).forEach(function (element) { notContentBlocksHeight += getElementHeight(element); }); return Math.max(0, Math.min(maxHeight - notContentBlocksHeight, contentHeight) + notContentBlocksHeight); }; var recalculateHeight = function () { var newMaxHeight = calculateMaxHeight(); setMaxHeightState(newMaxHeight); setMinHeight(calculateMinHeight(newMaxHeight)); }; useMultipleResizeObserver(__spreadArray(__spreadArray([], __read(Object.values(blocksRefs.current)), false), [contentRef.current], false), function () { recalculateHeight(); }); useEffect(function () { setReadyContentHeight(); }, []); useEventListener({ eventName: 'resize', handler: function () { recalculateHeight(); }, }); useEffect(function () { recalculateHeight(); setReadyMaxHeight(); }, [getCustomMaxHeight()]); return { minHeight: minHeight, maxHeight: maxHeight, recalculateHeight: recalculateHeight, }; };