UNPKG

@instantdb/core

Version:
51 lines 1.68 kB
import { pick } from './utils/pick.js'; import { areObjectsShallowEqual, areObjectKeysEqual } from './utils/object.js'; export function buildPresenceSlice(data, opts, userPeerId) { const slice = { peers: {}, }; const includeUser = opts && 'user' in opts ? opts.user : true; if (includeUser) { const user = pick(data.user ?? {}, opts?.keys); slice.user = { ...user, peerId: userPeerId }; } for (const id of Object.keys(data.peers ?? {})) { const shouldIncludeAllPeers = opts?.peers === undefined; const isPeerIncluded = Array.isArray(opts?.peers) && opts?.peers.includes(id); if (shouldIncludeAllPeers || isPeerIncluded) { const peer = pick(data.peers[id], opts?.keys); slice.peers[id] = { ...peer, peerId: id }; } } return slice; } /** * Compare two presence slices * 0. compare isLoading and error * 1. shallow compare user * 2. compare peers keys * 3. shallow compare each peer */ export function hasPresenceResponseChanged(a, b) { if (a.isLoading !== b.isLoading) return true; if (a.error !== b.error) return true; if (a.user || b.user) { if (!a.user || !b.user) return true; const same = areObjectsShallowEqual(a.user, b.user); if (!same) return true; } const sameKeys = areObjectKeysEqual(a.peers, b.peers); if (!sameKeys) return true; for (const id of Object.keys(a.peers)) { const same = areObjectsShallowEqual(a.peers[id], b.peers[id]); if (!same) return true; } return false; } //# sourceMappingURL=presence.js.map