UNPKG

@acrool/react-modal

Version:
807 lines (806 loc) 23.6 kB
var Ie = Object.defineProperty; var $e = (e, t, n) => t in e ? Ie(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n; var v = (e, t, n) => $e(e, typeof t != "symbol" ? t + "" : t, n); import Y, { useState as ce, useEffect as $, createContext as le, useContext as ue, useId as Ye, useRef as Oe, useCallback as De } from "react"; import de from "react-dom"; import { AnimatePresence as fe, useIsPresent as We, motion as te } from "framer-motion"; var C = { exports: {} }, R = {}; /** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var re; function Xe() { if (re) return R; re = 1; var e = Symbol.for("react.transitional.element"), t = Symbol.for("react.fragment"); function n(o, i, s) { var l = null; if (s !== void 0 && (l = "" + s), i.key !== void 0 && (l = "" + i.key), "key" in i) { s = {}; for (var f in i) f !== "key" && (s[f] = i[f]); } else s = i; return i = s.ref, { $$typeof: e, type: o, key: l, ref: i !== void 0 ? i : null, props: s }; } return R.Fragment = t, R.jsx = n, R.jsxs = n, R; } var P = {}; /** * @license React * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ne; function Fe() { return ne || (ne = 1, process.env.NODE_ENV !== "production" && function() { function e(r) { if (r == null) return null; if (typeof r == "function") return r.$$typeof === Ae ? null : r.displayName || r.name || null; if (typeof r == "string") return r; switch (r) { case W: return "Fragment"; case ge: return "Profiler"; case ve: return "StrictMode"; case je: return "Suspense"; case Se: return "SuspenseList"; case Ne: return "Activity"; } if (typeof r == "object") switch (typeof r.tag == "number" && console.error( "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." ), r.$$typeof) { case D: return "Portal"; case Pe: return (r.displayName || "Context") + ".Provider"; case Re: return (r._context.displayName || "Context") + ".Consumer"; case ke: var a = r.render; return r = r.displayName, r || (r = a.displayName || a.name || "", r = r !== "" ? "ForwardRef(" + r + ")" : "ForwardRef"), r; case Te: return a = r.displayName || null, a !== null ? a : e(r.type) || "Memo"; case G: a = r._payload, r = r._init; try { return e(r(a)); } catch { } } return null; } function t(r) { return "" + r; } function n(r) { try { t(r); var a = !1; } catch { a = !0; } if (a) { a = console; var c = a.error, u = typeof Symbol == "function" && Symbol.toStringTag && r[Symbol.toStringTag] || r.constructor.name || "Object"; return c.call( a, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", u ), t(r); } } function o(r) { if (r === W) return "<>"; if (typeof r == "object" && r !== null && r.$$typeof === G) return "<...>"; try { var a = e(r); return a ? "<" + a + ">" : "<...>"; } catch { return "<...>"; } } function i() { var r = X.A; return r === null ? null : r.getOwner(); } function s() { return Error("react-stack-top-frame"); } function l(r) { if (V.call(r, "key")) { var a = Object.getOwnPropertyDescriptor(r, "key").get; if (a && a.isReactWarning) return !1; } return r.key !== void 0; } function f(r, a) { function c() { z || (z = !0, console.error( "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", a )); } c.isReactWarning = !0, Object.defineProperty(r, "key", { get: c, configurable: !0 }); } function _() { var r = e(this.type); return H[r] || (H[r] = !0, console.error( "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." )), r = this.props.ref, r !== void 0 ? r : null; } function x(r, a, c, u, y, p, L, B) { return c = p.ref, r = { $$typeof: A, type: r, key: a, props: p, _owner: y }, (c !== void 0 ? c : null) !== null ? Object.defineProperty(r, "ref", { enumerable: !1, get: _ }) : Object.defineProperty(r, "ref", { enumerable: !1, value: null }), r._store = {}, Object.defineProperty(r._store, "validated", { configurable: !1, enumerable: !1, writable: !0, value: 0 }), Object.defineProperty(r, "_debugInfo", { configurable: !1, enumerable: !1, writable: !0, value: null }), Object.defineProperty(r, "_debugStack", { configurable: !1, enumerable: !1, writable: !0, value: L }), Object.defineProperty(r, "_debugTask", { configurable: !1, enumerable: !1, writable: !0, value: B }), Object.freeze && (Object.freeze(r.props), Object.freeze(r)), r; } function h(r, a, c, u, y, p, L, B) { var d = a.children; if (d !== void 0) if (u) if (Ce(d)) { for (u = 0; u < d.length; u++) g(d[u]); Object.freeze && Object.freeze(d); } else console.error( "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead." ); else g(d); if (V.call(a, "key")) { d = e(r); var w = Object.keys(a).filter(function(Me) { return Me !== "key"; }); u = 0 < w.length ? "{key: someKey, " + w.join(": ..., ") + ": ...}" : "{key: someKey}", ee[d + u] || (w = 0 < w.length ? "{" + w.join(": ..., ") + ": ...}" : "{}", console.error( `A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`, u, d, w, d ), ee[d + u] = !0); } if (d = null, c !== void 0 && (n(c), d = "" + c), l(a) && (n(a.key), d = "" + a.key), "key" in a) { c = {}; for (var U in a) U !== "key" && (c[U] = a[U]); } else c = a; return d && f( c, typeof r == "function" ? r.displayName || r.name || "Unknown" : r ), x( r, d, p, y, i(), c, L, B ); } function g(r) { typeof r == "object" && r !== null && r.$$typeof === A && r._store && (r._store.validated = 1); } var E = Y, A = Symbol.for("react.transitional.element"), D = Symbol.for("react.portal"), W = Symbol.for("react.fragment"), ve = Symbol.for("react.strict_mode"), ge = Symbol.for("react.profiler"), Re = Symbol.for("react.consumer"), Pe = Symbol.for("react.context"), ke = Symbol.for("react.forward_ref"), je = Symbol.for("react.suspense"), Se = Symbol.for("react.suspense_list"), Te = Symbol.for("react.memo"), G = Symbol.for("react.lazy"), Ne = Symbol.for("react.activity"), Ae = Symbol.for("react.client.reference"), X = E.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, V = Object.prototype.hasOwnProperty, Ce = Array.isArray, F = console.createTask ? console.createTask : function() { return null; }; E = { "react-stack-bottom-frame": function(r) { return r(); } }; var z, H = {}, J = E["react-stack-bottom-frame"].bind( E, s )(), Q = F(o(s)), ee = {}; P.Fragment = W, P.jsx = function(r, a, c, u, y) { var p = 1e4 > X.recentlyCreatedOwnerStacks++; return h( r, a, c, !1, u, y, p ? Error("react-stack-top-frame") : J, p ? F(o(r)) : Q ); }, P.jsxs = function(r, a, c, u, y) { var p = 1e4 > X.recentlyCreatedOwnerStacks++; return h( r, a, c, !0, u, y, p ? Error("react-stack-top-frame") : J, p ? F(o(r)) : Q ); }; }()), P; } var oe; function Le() { return oe || (oe = 1, process.env.NODE_ENV === "production" ? C.exports = Xe() : C.exports = Fe()), C.exports; } var m = Le(), Be = Object.defineProperty, Ue = (e, t, n) => t in e ? Be(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n, q = (e, t, n) => Ue(e, typeof t != "symbol" ? t + "" : t, n); function Ze(e) { return Object.keys(e); } function ae(e) { const t = document.createElement("div"); return t.id = e.id, e.className && (t.className = e.className), e.style && Ze(e.style).forEach((n) => { var o; t.style[n] = (o = e.style) == null ? void 0 : o[n]; }), t; } class me extends Y.Component { constructor(t) { super(t), q(this, "_el", null), q(this, "renderPortal", () => this._el ? de.createPortal( this.props.children, this._el ) : null), !(typeof window > "u") && (this._el = ae(t)); } get typeProps() { return this.props; } componentDidMount() { this._el = this._el ? this._el : ae(this.props); const t = this.typeProps.containerSelector(); t == null || t.appendChild(this._el); } componentWillUnmount() { if (!this._el) return; const t = this.typeProps.containerSelector(); t == null || t.removeChild(this._el); } render() { return this.renderPortal(); } } q(me, "defaultProps", { containerSelector: () => document.body }); const qe = ({ children: e, containerSelector: t = () => document.body }) => { const [n, o] = ce(!1); return $(() => { o(!0); }, []), (() => { const i = t(); return n && i ? de.createPortal(e, i) : null; })(); }, pe = "acrool-react-modal", S = [ "color: #fff", "display: inline-block", "font-size: 11px", "line-height: 20px", "padding-right: 8px", "border-radius: 4px" ], T = { primary: "#0055a9", success: "#009422", info: "#17a2b8", warning: "#d7a000", danger: "#ec2127" }; function N(e, t, ...n) { console.log(`%c ${e}`, t, ...n); } function Ke(e, ...t) { const n = S.concat([ `background-color: ${T.primary}` ]).join(";"); N(e, n, ...t); } function Ge(e, ...t) { const n = S.concat([ `background-color: ${T.success}` ]).join(";"); N(e, n, ...t); } function Ve(e, ...t) { const n = S.concat([ `background-color: ${T.info}` ]).join(";"); N(e, n, ...t); } function ze(e, ...t) { const n = S.concat([ `background-color: ${T.warning}` ]).join(";"); N(e, n, ...t); } function He(e, ...t) { const n = S.concat([ `background-color: ${T.danger}` ]).join(";"); N(e, n, ...t); } const he = { primary: Ke, success: Ge, info: Ve, warning: ze, danger: He }, ye = le({ hide: () => he.warning("No GlobalModal/hide method detected, did you embed your app with Acrool/ModalPortal?") }), $t = () => ue(ye), Je = "acrool-react-modal__root", Qe = { root: Je }, O = le({ hide: async () => he.warning("No Modal/hide method detected, did you embed your app with Acrool/ModalPortal?") }); O.Consumer; const et = () => ue(O); function I(e) { const t = new Error(e); return t.source = "ulid", t; } const K = "0123456789ABCDEFGHJKMNPQRSTVWXYZ", j = K.length, ie = Math.pow(2, 48) - 1, tt = 10, rt = 16; function nt(e) { let t = Math.floor(e() * j); return t === j && (t = j - 1), K.charAt(t); } function ot(e, t) { if (isNaN(e)) throw new Error(e + " must be a number"); if (e > ie) throw I("cannot encode time greater than " + ie); if (e < 0) throw I("time must be positive"); if (Number.isInteger(Number(e)) === !1) throw I("time must be an integer"); let n, o = ""; for (; t > 0; t--) n = e % j, o = K.charAt(n) + o, e = (e - n) / j; return o; } function at(e, t) { let n = ""; for (; e > 0; e--) n = nt(t) + n; return n; } function it(e = !1, t) { t || (t = typeof window < "u" ? window : null); const n = t && (t.crypto || t.msCrypto); if (n) return () => { const o = new Uint8Array(1); return n.getRandomValues(o), o[0] / 255; }; try { const o = require("crypto"); return () => o.randomBytes(1).readUInt8() / 255; } catch { } if (e) { try { console.error("secure crypto unusable, falling back to insecure Math.random()!"); } catch { } return () => Math.random(); } throw I("secure crypto unusable, insecure Math.random not allowed"); } function st(e) { return e || (e = it()), function(n) { return isNaN(n) && (n = Date.now()), ot(n, tt) + at(rt, e); }; } const ct = st(); function lt(e, t) { return t === -1 || t > e.length - 1 ? e : [...e.slice(0, t), ...e.slice(t + 1)]; } function ut(e, t) { return !!e.className.match(new RegExp(`(\\s|^)${t}(\\s|$)`)); } function dt(e, t) { ut(e, t) || e.classList.add(t); } function ft(e, t) { e.classList.remove(t); } function be() { return ct().toLowerCase(); } function mt(e, t) { return e == null || e === !1 || e === "false" || e === 0 || e === "0" || !(e instanceof Date) && typeof e == "object" && Object.keys(e).length === 0 || typeof e == "string" && e.trim().length === 0; } let k; class pt extends Y.Component { constructor(n) { super(n); v(this, "state", { rows: [] }); /** * 顯示 Toaster * (自動 QueueKey) * @param ModalComponent * @param args */ v(this, "show", (n, o) => { const i = be(); this.showWithKey(n, i, o); }); /** * 顯示 Toaster * (手動 QueueKey) * @param ModalComponent * @param queueKey * @param args */ v(this, "showWithKey", (n, o, i) => { this.setState((s) => { this.typeProps._onShow && this.typeProps._onShow(o); const l = s.rows.findIndex((_) => _.queueKey === o); if (l === -1) return { rows: [...s.rows, { queueKey: o, ModalComponent: n, args: i }] }; const f = [...s.rows]; return f[l] = { queueKey: o, ModalComponent: n, args: i }, { rows: f }; }); }); /** * 隱藏 Toaster * @param queueKey */ v(this, "hide", (n) => { this.setState((o) => { const i = o.rows.findIndex((s) => s.queueKey === n); return { rows: lt(o.rows, i) }; }), this.typeProps._onHide && this.typeProps._onHide(n); }); k = { show: this.show, showWithKey: this.showWithKey, hide: this.hide }; } get typeProps() { return this.props; } /** * 渲染項目 */ renderItems() { const { rows: n } = this.state; return n.map((o) => /* @__PURE__ */ m.jsx( O.Provider, { value: { queueKey: o.queueKey, hide: async () => { this.hide(o.queueKey); } }, children: /* @__PURE__ */ m.jsx( o.ModalComponent, { ...o.args }, o.queueKey ) }, o.queueKey )); } render() { return /* @__PURE__ */ m.jsxs( ye.Provider, { value: { hide: this.hide }, children: [ this.props.children, /* @__PURE__ */ m.jsx( me, { id: this.typeProps.id, className: Qe.root, containerSelector: this.typeProps.containerSelector, children: /* @__PURE__ */ m.jsx(fe, { mode: this.typeProps.animatePresenceMode, children: this.renderItems() }) } ) ] } ); } } v(pt, "defaultProps", { id: pe }); const _e = "acrool__modal-open", xe = "acrool__modal-open-fixed"; function ht(e, t = !1) { dt(document.body, t ? `${xe}__${e}` : `${_e}__${e}`); } function yt(e, t = !1) { ft(document.body, t ? `${xe}__${e}` : `${_e}__${e}`); } const Z = { disableBodyScroll: ht, enableBodyScroll: yt }; function Ee(e) { var t, n, o = ""; if (typeof e == "string" || typeof e == "number") o += e; else if (typeof e == "object") if (Array.isArray(e)) { var i = e.length; for (t = 0; t < i; t++) e[t] && (n = Ee(e[t])) && (o && (o += " "), o += n); } else for (n in e) e[n] && (o && (o += " "), o += n); return o; } function se() { for (var e, t, n = 0, o = "", i = arguments.length; n < i; n++) (e = arguments[n]) && (t = Ee(e)) && (o && (o += " "), o += t); return o; } const bt = "acrool-react-modal__motion-drawer", _t = "acrool-react-modal__fixedDisabled", xt = "acrool-react-modal__motion-mask-wrapper", Et = "acrool-react-modal__motion-animation-wrapper", M = { motionDrawer: bt, fixedDisabled: _t, motionMaskWrapper: xt, motionAnimationWrapper: Et }, wt = { animation: { variants: { initial: { opacity: 0, transition: { type: "spring" } }, animate: { opacity: 1 }, exit: { opacity: 0 } }, transition: { duration: 0.2 } } }, vt = ({ modalOptions: e, children: t }, n) => { const { style: o, className: i, isMaskHidden: s, isHideWithMaskClick: l, isBodyScrollEnable: f, isFixedDisabled: _, animation: x } = e ?? { className: "" }, h = Ye(), g = We(), { hide: E } = et(); $(() => { f || (g ? Z.disableBodyScroll(h) : Z.enableBodyScroll(h)); }, [g]), $(() => () => { f || Z.enableBodyScroll(h); }, []); const A = () => mt(x) ? t : /* @__PURE__ */ m.jsx( te.div, { transition: { type: "spring", duration: 0.2 }, className: se(M.motionAnimationWrapper, i), style: o, ...x, initial: "initial", animate: "animate", exit: "exit", children: t } ), D = () => { if (!s) return /* @__PURE__ */ m.jsx( te.div, { className: M.motionMaskWrapper, ...wt.animation, initial: "initial", animate: "animate", exit: "exit", "data-enable-click": l, onClick: l ? E : void 0 } ); }; return /* @__PURE__ */ m.jsxs("div", { className: se(M.motionDrawer, { [M.fixedDisabled]: _ }), ref: n, children: [ D(), A() ] }); }, we = Y.forwardRef(vt); function Yt(e, t) { return (o) => { const [i, s] = ce(!0), l = Oe(null), f = (t == null ? void 0 : t.queueKey) ?? be(); $(() => (t != null && t._onShow && t._onShow(f), () => { t != null && t._onHide && t._onHide(f); }), []); const _ = () => { l.current && l.current(); }, x = De(async () => new Promise((h) => { l.current = h, s(!1); }), []); return /* @__PURE__ */ m.jsx( O.Provider, { value: { hide: x, queueKey: f }, children: /* @__PURE__ */ m.jsx( qe, { containerSelector: () => document.getElementById(pe), children: /* @__PURE__ */ m.jsx( fe, { mode: t == null ? void 0 : t.animatePresenceMode, onExitComplete: _, children: i && /* @__PURE__ */ m.jsx(we, { modalOptions: t, children: /* @__PURE__ */ m.jsx(e, { ...o }) }) } ) } ) } ); }; } function Ot(e, t) { const n = (s) => /* @__PURE__ */ m.jsx(we, { modalOptions: t, children: /* @__PURE__ */ m.jsx(e, { ...s }) }); function o(s) { s ? k.show(n, s) : k.show(n); } function i(s, l) { l ? k.showWithKey(n, s, l) : k.showWithKey(n, s); } return n.show = o, n.showWithKey = i, n; } const b = { initial: "initial", animate: "animate", exit: "exit" }, gt = (e = 20, t = 40) => ({ ...b, variants: { initial: { position: "absolute", left: "50%", opacity: 0, x: "-50%", y: e }, animate: { opacity: 1, y: t, transition: { type: "just", duration: 0.2 } }, exit: { opacity: 0, y: e } } }), Rt = (e = 20) => ({ ...b, variants: { initial: { position: "absolute", left: "50%", top: "50%", opacity: 0, x: "-50%", y: `calc(-50% - ${e}px)` }, animate: { opacity: 1, y: "-50%", transition: { type: "just", duration: 0.2 } }, exit: { opacity: 0, y: "-50%" } } }), Pt = { ...b, variants: { initial: { scaleX: 0.5, scaleY: 0.5, scaleZ: 0.8, translateX: 0, translateY: 20, translateZ: 0, opacity: 0 }, animate: { scaleX: 1, scaleY: 1, scaleZ: 1, translateX: 0, translateY: 40, translateZ: 0, opacity: 1, transition: { type: "just", duration: 0.2 } }, exit: { scaleX: 0.8, scaleY: 0.8, scaleZ: 0.8, translateX: 0, translateY: 20, translateZ: 0, opacity: 0, transition: { type: "spring" } } } }, kt = { ...b, variants: { initial: { position: "absolute", top: "50%", left: "50%", scaleX: 0.5, scaleY: 0.5, scaleZ: 0.8, translateX: "-50%", translateY: "-50%", translateZ: 0, opacity: 0 }, animate: { scaleX: 1, scaleY: 1, scaleZ: 1, translateZ: 0, opacity: 1, transition: { type: "spring", duration: 0.4 } }, exit: { scaleX: 0.8, scaleY: 0.8, scaleZ: 0.8, translateZ: 0, opacity: 0 } }, transition: { damping: 0, duration: 0.2 } }, jt = { ...b, variants: { initial: { position: "fixed", top: 0, bottom: 0, right: 0, translateX: "100%", opacity: 0.9 }, animate: { translateX: 0, opacity: 1 }, exit: { translateX: "100%", opacity: 0.9 } }, transition: { damping: 0 } }, St = { ...b, variants: { initial: { position: "fixed", top: 0, bottom: 0, left: 0, translateX: "-100%", opacity: 0.9 }, animate: { translateX: 0, opacity: 1 }, exit: { translateX: "-100%", opacity: 0.9 } }, transition: { damping: 0 } }, Tt = { ...b, variants: { initial: { position: "fixed", bottom: 0, left: 0, right: 0, translateY: "100%", opacity: 0.9 }, animate: { translateY: 0, opacity: 1 }, exit: { translateY: "100%", opacity: 0.9 } }, transition: { damping: 0, duration: 0.2 } }, Nt = { ...b, variants: { initial: { position: "fixed", top: "100%", left: 0, right: 0, opacity: 0.9 }, animate: { top: 0, opacity: 1, transition: { type: "just" } }, exit: { top: "100%", opacity: 0.9 } }, transition: { damping: 0 } }, Dt = { zoomInDown: Pt, zoomInCenter: kt, generateFadeInFromTop: gt, generateFadeInFromTopCentered: Rt, slideRightInLeft: St, slideLeftInRight: jt, slideUpInBottom: Tt, slideUpEndInBottom: Nt }; export { Z as BodyScroll, pt as ModalProvider, Dt as animation, Ot as createModal, Yt as createStateModal, k as modal, $t as useGlobalModal, et as useModal };