fanyucomponents
Version:
一款以 純邏輯為核心、無樣式綁定 的 React 元件套件
63 lines (62 loc) • 2.81 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { flexAlignMap } from "../utils/flex";
import { onEventHandlerKeys, } from "../types";
import { StateStylesComponent } from "./StateStylesComponent";
export const useModal = (initOption) => {
var _a;
const [isShow, setIsShow] = useState((_a = initOption === null || initOption === void 0 ? void 0 : initOption.isShow) !== null && _a !== void 0 ? _a : false);
const Toggle = () => setIsShow((prev) => !prev);
const Open = () => setIsShow(true);
const Close = () => setIsShow(false);
const Container = (props) => {
if (!isShow)
return null;
const { direction = "vertical", mainAlign = "center", crossAlign = "center", stopPropagation = true, children, style, clickOutsideToClose = true, onClick, ...rest } = props;
const Component = (_jsx(StateStylesComponent, { as: "div", style: {
zIndex: 6987,
position: "fixed",
inset: 0,
width: "100vw",
height: "100vh",
backgroundColor: "rgba(0, 0, 0, 0.5)",
display: "flex",
flexDirection: direction === "horizon" ? "row" : "column",
alignItems: flexAlignMap.cross[crossAlign],
justifyContent: flexAlignMap.main[mainAlign],
...style,
}, onClick: (...args) => {
if (clickOutsideToClose)
Close();
if (onClick)
onClick(...args);
}, ...rest, children: stopPropagation
? React.Children.map(children, (child) => React.isValidElement(child)
? React.cloneElement(child, {
...onEventHandlerKeys.reduce((newProps, key) => {
var _a;
const original = (_a = child.props) === null || _a === void 0 ? void 0 : _a[key];
newProps[key] = (...args) => {
const Event = args[0];
if (stopPropagation && Event.stopPropagation)
Event.stopPropagation();
if (typeof original === "function")
original(...args);
};
return newProps;
}, {}),
})
: child)
: children }));
return ReactDOM.createPortal(Component, document.body);
};
Container.displayName = "Modal.Container";
return {
isShow,
Open,
Close,
Toggle,
Container,
};
};