UNPKG

@mittwald/react-tunnel

Version:

It's like a Portal – but with React components

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