@y-presence/client
Version:
Easy way to add presence (live cursors/avatars) to your multiplayer application using Yjs
89 lines (86 loc) • 2.31 kB
JavaScript
;
var i = Object.defineProperty;
var u = Object.getOwnPropertyDescriptor;
var T = Object.getOwnPropertyNames;
var b = Object.prototype.hasOwnProperty;
var U = (t, e) => {
for (var s in e)
i(t, s, { get: e[s], enumerable: !0 });
}, f = (t, e, s, r) => {
if (e && typeof e == "object" || typeof e == "function")
for (let a of T(e))
!b.call(t, a) && a !== s && i(t, a, { get: () => e[a], enumerable: !(r = u(e, a)) || r.enumerable });
return t;
};
var v = (t) => f(i({}, "__esModule", { value: !0 }), t);
// src/index.ts
var E = {};
U(E, {
Room: () => l
});
module.exports = v(E);
// src/room.ts
var l = class {
constructor(e, s) {
this.listeners = {
others: [],
users: [],
self: []
};
this.awareness = e, this.setPresence(s), this.awareness.on("change", (r, a) => {
let c = this.getUsers();
if (this.listeners.users.forEach((n) => {
n(c);
}), a === "local") {
let n = this.getSelf();
this.listeners.self.forEach((h) => {
h(n);
});
return;
}
let o = this.getOthers();
this.listeners.others.forEach((n) => {
n(o);
});
});
}
updatePresence(e) {
for (let s in e)
this.awareness.setLocalStateField(s, e[s]);
}
setPresence(e) {
this.awareness.setLocalState(e);
}
getSelf() {
return {
id: this.awareness.clientID,
presence: this.awareness.getLocalState()
};
}
getOthers() {
let e = [];
return this.awareness.getStates().forEach((s, r) => {
r !== this.awareness.clientID && e.push({ id: r, presence: s });
}), e;
}
getUsers() {
let e = [];
return this.awareness.getStates().forEach((s, r) => {
e.push({ id: r, presence: s });
}), e;
}
subscribe(e, s) {
return e === "users" || e === "others" ? (this.listeners[e].push(s), () => this.unsubscribe(e, s)) : (this.listeners[e].push(s), () => this.unsubscribe(e, s));
}
unsubscribe(e, s) {
for (let r = 0; r < this.listeners[e].length; r++)
s === this.listeners[e][r] && this.listeners[e].splice(r, 1);
}
destroy() {
this.awareness.setLocalState(null), this.awareness.destroy();
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Room
});