UNPKG

@carrot-farm/mongsil-ui

Version:
56 lines (55 loc) 2.45 kB
import * as React from 'react'; import { useEffect, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; function Modal(_a) { var className = _a.className, _b = _a.bosyScroll, bosyScroll = _b === void 0 ? true : _b, _c = _a.visible, visible = _c === void 0 ? false : _c, children = _a.children, onVisible = _a.onVisible, onHidden = _a.onHidden, onBackdropClick = _a.onBackdropClick; var ref = useRef(); var _d = useState(false), isMounted = _d[0], setIsMounted = _d[1]; var _e = useState(false), show = _e[0], setShow = _e[1]; useEffect(function () { setIsMounted(true); if (document) { var rootEl = document.getElementById('Mongsil-modal-root'); if (!rootEl) { rootEl = document.createElement('div'); rootEl.setAttribute('id', 'Mongsil-modal-root'); document.body.appendChild(rootEl); } ref.current = rootEl; } return function () { var rootEl = document.getElementById('Mongsil-modal-root'); if (rootEl && !(rootEl === null || rootEl === void 0 ? void 0 : rootEl.innerHTML)) { document.body.removeChild(rootEl); } ref.current = undefined; setIsMounted(null); }; }, []); useEffect(function () { if (!isMounted) { return; } if (visible) { onVisible && onVisible(ref); document.body.classList.add('overflow-hidden'); } else { onHidden && onHidden(); } setTimeout(function () { setShow(!!visible); }); return function () { document.body.classList.remove('overflow-hidden'); setShow(null); }; }, [isMounted, visible, onVisible, onHidden]); if (ref.current && visible === true && isMounted === true) { return createPortal(React.createElement("div", { className: "Mongsil-modal " + (className !== null && className !== void 0 ? className : '') }, React.createElement("div", { className: "Mongsil-modal-backdrop " + (show ? 'show' : ''), onClick: function () { return onBackdropClick && onBackdropClick(); } }), React.createElement("div", { className: "Mongsil-modal-container " + (bosyScroll ? 'body-scroll' : '') }, children)), ref.current); } return null; } export default Modal;