fix: delete user presence when leaving or on exit (#698)
This commit is contained in:
parent
6cb5b4a75a
commit
a5e2b55294
1 changed files with 14 additions and 32 deletions
|
@ -95,41 +95,23 @@ export function useMultiplayerState(roomId: string) {
|
||||||
|
|
||||||
// Handle changes to other users' presence
|
// Handle changes to other users' presence
|
||||||
unsubs.push(
|
unsubs.push(
|
||||||
room.subscribe('others', (others) => {
|
room.subscribe('others', (others, event) => {
|
||||||
app.updateUsers(
|
if (event.type === 'leave') {
|
||||||
others
|
if (event.user.presence) {
|
||||||
.toArray()
|
app?.removeUser(event.user.presence.id)
|
||||||
.filter((other) => other.presence)
|
}
|
||||||
.map((other) => other.presence!.user)
|
} else {
|
||||||
.filter(Boolean)
|
app.updateUsers(
|
||||||
)
|
others
|
||||||
|
.toArray()
|
||||||
|
.filter((other) => other.presence)
|
||||||
|
.map((other) => other.presence!.user)
|
||||||
|
.filter(Boolean)
|
||||||
|
)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
// Handle events from the room
|
|
||||||
unsubs.push(
|
|
||||||
room.subscribe(
|
|
||||||
'event',
|
|
||||||
(e: { connectionId: number; event: { name: string; userId: string } }) => {
|
|
||||||
switch (e.event.name) {
|
|
||||||
case 'exit': {
|
|
||||||
app?.removeUser(e.event.userId)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
// Send the exit event when the tab closes
|
|
||||||
function handleExit() {
|
|
||||||
if (!(room && app?.room)) return
|
|
||||||
room?.broadcastEvent({ name: 'exit', userId: app.room.userId })
|
|
||||||
}
|
|
||||||
|
|
||||||
window.addEventListener('beforeunload', handleExit)
|
|
||||||
unsubs.push(() => window.removeEventListener('beforeunload', handleExit))
|
|
||||||
|
|
||||||
let stillAlive = true
|
let stillAlive = true
|
||||||
|
|
||||||
// Setup the document's storage and subscriptions
|
// Setup the document's storage and subscriptions
|
||||||
|
|
Loading…
Reference in a new issue