vue-broadcaster
Version:
76 lines (75 loc) • 2.61 kB
JavaScript
import { getCurrentInstance as f, inject as C, onUnmounted as m, provide as p } from "vue";
class I {
listeners = /* @__PURE__ */ new Map();
on(o, n, r, a, e) {
let s = this.listeners.get(o), t = !1;
return s ? t = s.some((d) => d.handler === n) : (s = [], this.listeners.set(o, s)), t || s.push({ handler: n, once: r, excludeSelf: a, uid: e }), () => this.off(o, n);
}
off(o, n) {
const r = this.listeners.get(o);
if (!r) return;
const a = r.findIndex((e) => e.handler === n);
a !== -1 && r.splice(a, 1), r.length === 0 && this.listeners.delete(o);
}
emit(o, n, r) {
const a = this.listeners.get(o);
a && Array.from(a).forEach((e) => {
try {
if (e.excludeSelf && r !== void 0 && e.uid !== void 0 && e.uid === r)
return;
e.handler(n);
} catch (s) {
console.error(`Error handling broadcast event "${o}":`, s);
}
e.once && this.off(o, e.handler);
});
}
}
const N = Symbol("broadcaster"), g = (v) => {
const { injectionKey: o = N } = v || {};
return {
useBroadcast: () => {
const e = f(), s = e ? e.uid : void 0, t = new I();
p(o, t);
const d = [];
return m(() => {
d.forEach((c) => c());
}), { broadcast: (c, i) => t.emit(c, i, s), receive: (c, i, E) => {
const { once: x = !1, excludeSelf: b = !1 } = E || {};
return b && s === void 0 && B(), d.push(() => t.off(c, i)), t.on(c, i, x, b, s);
} };
},
useReceiveBroadcast: (e, s, t) => {
const { once: d = !1, excludeSelf: l = !1 } = t || {}, u = f(), c = u ? u.uid : void 0;
l && c === void 0 && B();
const i = C(o, null);
return i ? (m(() => {
i.off(e, s);
}), i.on(e, s, d, l, c)) : (console.warn(`No broadcast provider found for event type "${e}"`), () => {
});
},
useChildBroadcast: () => {
const e = f(), s = e ? e.uid : void 0;
s === void 0 && B();
const t = C(o);
return t || console.warn("No broadcast provider found"), (l, u) => {
t && t.emit(l, u, s);
};
}
};
}, B = () => {
console.warn("Failed to obtain uid, excludeSelf option is invalid");
}, R = Symbol("global_broadcaster"), h = g(), {
useBroadcast: w,
useReceiveBroadcast: _,
useChildBroadcast: G
} = g({ injectionKey: R }), K = h.useBroadcast, j = h.useReceiveBroadcast, A = h.useChildBroadcast;
export {
g as createBroadcastCompositions,
K as useBroadcast,
A as useChildBroadcast,
w as useGlobalBroadcast,
G as useGlobalChildBroadcast,
_ as useGlobalReceiveBroadcast,
j as useReceiveBroadcast
};