73 lines
1.8 KiB
TypeScript
73 lines
1.8 KiB
TypeScript
import type { ChadClient } from '@shared/types.ts'
|
|
import { useSignaling } from '@shared/composables/use-signaling.ts'
|
|
import { createGlobalState } from '@vueuse/core'
|
|
import { computed, shallowRef } from 'vue'
|
|
import { useAuth } from './use-auth'
|
|
|
|
export const useClients = createGlobalState(() => {
|
|
const { me } = useAuth()
|
|
const signaling = useSignaling()
|
|
|
|
const clients = shallowRef<ChadClient[]>([])
|
|
|
|
function addClient(...incoming: ChadClient[]) {
|
|
const ids = new Set(incoming.map(c => c.socketId))
|
|
clients.value = [
|
|
...clients.value.filter(c => !ids.has(c.socketId)),
|
|
...incoming,
|
|
]
|
|
}
|
|
|
|
function removeClient(...socketIds: string[]) {
|
|
const ids = new Set(socketIds)
|
|
clients.value = clients.value.filter(c => !ids.has(c.socketId))
|
|
}
|
|
|
|
function updateClient(socketId: string, patch: Partial<Omit<ChadClient, 'socketId'>>) {
|
|
clients.value = clients.value.map(c =>
|
|
c.socketId === socketId ? { ...c, ...patch } : c,
|
|
)
|
|
}
|
|
|
|
function findById(socketId: string) {
|
|
return clients.value.find(c => c.socketId === socketId)
|
|
}
|
|
|
|
function findByChannel(channelId: string) {
|
|
return clients.value.filter(c => c.channelId === channelId)
|
|
}
|
|
|
|
function findByUsername(username: string) {
|
|
return clients.value.find(c => c.username === username)
|
|
}
|
|
|
|
const self = computed(() => {
|
|
return clients.value.find((client) => {
|
|
if (signaling.socket.value) {
|
|
return client.socketId === signaling.socket.value.id
|
|
}
|
|
else if (me.value) {
|
|
return client.username === me.value.username
|
|
}
|
|
|
|
return undefined
|
|
})
|
|
})
|
|
|
|
function clear() {
|
|
clients.value = []
|
|
}
|
|
|
|
return {
|
|
clients,
|
|
self,
|
|
addClient,
|
|
removeClient,
|
|
updateClient,
|
|
findById,
|
|
findByChannel,
|
|
findByUsername,
|
|
clear,
|
|
}
|
|
})
|