chad/client/app/composables/use-clients.ts
Никита Круглицкий ec67be8aa6
All checks were successful
Deploy / deploy (push) Successful in 4m32s
куча говна
2025-10-20 00:10:13 +06:00

67 lines
1.8 KiB
TypeScript

import type { ChadClient, UpdatedClient } from '#shared/types'
import { createGlobalState } from '@vueuse/core'
export const useClients = createGlobalState(() => {
const auth = useAuth()
const signaling = useSignaling()
const toast = useToast()
const clients = shallowRef<ChadClient[]>([])
const me = computed(() => clients.value.find(client => client.userId === auth.me.value?.id))
watch(signaling.socket, (socket) => {
if (!socket)
return
socket.on('clientChanged', (clientId: ChadClient['socketId'], updatedClient: UpdatedClient) => {
const client = getClient(clientId)
updateClient(clientId, updatedClient)
if (client && client.displayName !== updatedClient.displayName)
toast.add({ severity: 'info', summary: `${client.displayName} is now ${updatedClient.displayName}`, closable: false, life: 1000 })
})
socket.on('disconnect', () => {
clients.value = []
})
})
function getClient(clientId: ChadClient['socketId']) {
return clients.value.find(client => client.socketId === clientId)
}
function addClient(...client: ChadClient[]) {
clients.value.push(...client)
triggerRef(clients)
}
function removeClient(clientId: ChadClient['socketId']) {
clients.value = clients.value.filter(client => client.socketId !== clientId)
}
function updateClient(clientId: ChadClient['socketId'], updatedClient: UpdatedClient) {
const clientIdx = clients.value.findIndex(client => client.socketId === clientId)
if (clientIdx === -1)
return
clients.value[clientIdx] = {
...clients.value[clientIdx],
...updatedClient,
} as ChadClient
triggerRef(clients)
}
return {
me,
clients,
getClient,
addClient,
removeClient,
updateClient,
}
})