@lani.ground/react-modal
Version:
Modal components used in reactjs
72 lines (71 loc) • 3.29 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
import { jsx as _jsx } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
export default function Modal(_a) {
var name = _a.name, closeModal = _a.closeModal, dim = _a.dim, centerMode = _a.centerMode, animation = _a.animation, containerPadding = _a.containerPadding, disabledOutsideClose = _a.disabledOutsideClose, _b = _a.isClosing, isClosing = _b === void 0 ? false : _b, children = _a.children;
var $modalContents = useRef(null);
var _c = useState(false), isEntered = _c[0], setIsEntered = _c[1];
var timerRef = useRef();
var classes = useMemo(function () {
var _a, _b, _c;
return (animation === null || animation === void 0 ? void 0 : animation.duration)
? isClosing
? "react-modal__container__exit ".concat((_a = animation.className) !== null && _a !== void 0 ? _a : '')
: isEntered
? "react-modal__container__enter ".concat((_b = animation.className) !== null && _b !== void 0 ? _b : '')
: "react-modal__container__exit ".concat((_c = animation.className) !== null && _c !== void 0 ? _c : '')
: '';
}, [animation === null || animation === void 0 ? void 0 : animation.className, animation === null || animation === void 0 ? void 0 : animation.duration, isEntered, isClosing]);
useEffect(function () {
if (!isClosing) {
timerRef.current = window.setTimeout(function () {
setIsEntered(true);
}, 10);
}
return function () {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
};
}, [isClosing]);
var outsideClickHandler = useCallback(function (e) {
var $modal = e.target.closest('[data-type="modal"]');
if (!$modal)
return;
if (!$modalContents.current ||
$modalContents.current.contains(e.target))
return;
if ($modal.dataset.name &&
$modal.dataset.name === name) {
closeModal();
}
}, [closeModal, name]);
useEffect(function () {
if (disabledOutsideClose)
return;
var handler = outsideClickHandler;
document.addEventListener('click', handler, {
capture: true,
});
return function () {
document.removeEventListener('click', handler, {
capture: true,
});
};
}, [disabledOutsideClose, outsideClickHandler]);
var styles = {
backgroundColor: dim,
padding: containerPadding,
};
return (_jsx("div", { "data-type": "modal", "data-name": name, className: "react-modal__container ".concat(classes, " ").concat(centerMode ? 'center-mode' : ''), style: __assign({}, styles), children: _jsx("div", { ref: $modalContents, children: children }) }));
}