UNPKG

@mittwald/react-tunnel

Version:

It's like a Portal – but with React components

73 lines (72 loc) 2.54 kB
"use client" /* */ var g = Object.defineProperty; var b = (n, e, r) => e in n ? g(n, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : n[e] = r; var h = (n, e, r) => b(n, typeof e != "symbol" ? e + "" : e, r); import { jsx as f } from "react/jsx-runtime"; import { useState as v, createContext as w, useContext as m, useId as x, useRef as M, useEffect as p } from "react"; import { observable as a, makeObservable as y, action as C } from "mobx"; import { observer as E } from "mobx-react-lite"; const l = "default"; class o { constructor() { h(this, "children", a.map( {}, { deep: !1 } )); h(this, "preparedChildren", /* @__PURE__ */ new Map()); y(this, { deleteChildren: C.bound, setChildren: C.bound }); } static useNew() { return v(() => new o())[0]; } setChildren(e = l, r, i) { var d; const t = this.children.get(e) ?? a.map({}, { deep: !1 }); t.set(r, i), (d = this.preparedChildren.get(e)) == null || d.delete(r), this.children.set(e, t); } prepareChildren(e = l, r, i) { const t = this.preparedChildren.get(e) ?? /* @__PURE__ */ new Map(); t.set(r, i), this.preparedChildren.set(e, t); } deleteChildrenFromMap(e, r, i) { const t = e.get(r); t == null || t.delete(i), (t == null ? void 0 : t.size) === 0 && e.delete(r); } deleteChildren(e = l, r) { this.deleteChildrenFromMap(this.children, e, r), this.deleteChildrenFromMap(this.preparedChildren, e, r); } getChildren(e = l) { var i, t; const r = ((i = this.children.get(e)) == null ? void 0 : i.entries()) ?? ((t = this.preparedChildren.get(e)) == null ? void 0 : t.entries()); if (r) return Array.from(r); } } const c = w(new o()), k = (n) => { const { children: e } = n; return /* @__PURE__ */ f(c.Provider, { value: o.useNew(), children: e }); }, z = (n) => { const { children: e, id: r, staticEntryId: i } = n, t = m(c), d = x(), s = i ?? d, u = M(!1); return u.current || t.prepareChildren(r, s, e), p(() => { u.current = !0, t.setChildren(r, s, e); }, [e, r, s]), p(() => () => { t.deleteChildren(r, s); }, [r, s]), null; }, T = (n) => { const { children: e } = n; return typeof e == "function" ? e() : e; }, A = E((n) => { const { children: e, id: r } = n, i = m(c).getChildren(r), t = i ? i.map(([d, s]) => /* @__PURE__ */ f(T, { children: s }, d)) : null; return typeof e == "function" ? e(t) : t ?? e; }); export { z as TunnelEntry, A as TunnelExit, k as TunnelProvider };