chad/client/app/composables/use-clients.ts
Никита Круглицкий e2064dba6c
All checks were successful
Deploy / deploy (push) Successful in 38s
front update
2025-10-09 06:14:35 +06:00

59 lines
1.5 KiB
TypeScript

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