import { useQueryClient } from '@tanstack/react-query' import { useCallback, useMemo } from 'react' import { TypingBroadcastDataAttributes } from '../types/jolt_events/typing_events' export const TYPING_TIMEOUT_INTERVAL = 6000 // 6 seconds export interface PersonTyping extends TypingBroadcastDataAttributes { expires: number } /** * Hook for managing the cache of people currently typing in a conversation */ export const useTypingStatusCache = (conversationId: number) => { const queryClient = useQueryClient() const cacheKey = useMemo(() => ['conversationTyping', String(conversationId)], [conversationId]) const addTypingEvent = useCallback( (data: TypingBroadcastDataAttributes) => { queryClient.setQueryData(cacheKey, (oldData: PersonTyping[] = []) => { const filtered = oldData.filter( item => item.author_id !== data.author_id && item.expires > Date.now() ) const expires = Date.now() + TYPING_TIMEOUT_INTERVAL return [...filtered, { ...data, expires }] }) }, [queryClient, cacheKey] ) const removeTypingEventById = useCallback( (id: string) => { queryClient.setQueryData(cacheKey, (oldData: PersonTyping[] = []) => { return oldData.filter(item => item.id !== id) }) }, [queryClient, cacheKey] ) const removeAllTypingEventsByAuthorId = useCallback( (authorId: number) => { queryClient.setQueryData(cacheKey, (oldData: PersonTyping[] = []) => { return oldData.filter(item => item.author_id !== authorId) }) }, [queryClient, cacheKey] ) return { addTypingEvent, removeTypingEventById, removeAllTypingEventsByAuthorId, } }