import { useQuery } from '@tanstack/react-query' import { useMemo } from 'react' import { useConversationContext } from '../contexts/conversation_context' import { useCurrentPerson } from './use_current_person' import { PersonTyping } from './use_typing_status_cache' /** * Hook for getting people currently typing in a conversation * * The query function itself doesn't do anything, but we add to the cache * from useTypingStatusCache when we receive a typing event. */ export const useTypingIndicators = () => { const { conversationId, currentPageReplyRootId } = useConversationContext() const cacheKey = useMemo(() => ['conversationTyping', String(conversationId)], [conversationId]) const currentPerson = useCurrentPerson() const isCurrentPerson = (authorId: number) => authorId === currentPerson?.id const inMainConversationView = !currentPageReplyRootId const now = Date.now() const { data } = useQuery({ queryKey: cacheKey, queryFn: () => stableArray, initialData: stableArray, }) return data.filter(({ author_id, expires, reply_root_id }) => { if (isCurrentPerson(author_id)) return false if (now > expires) return false // If you are in the main conversation view, you will see any message sent if (inMainConversationView) return true // If you are in a reply view, you will only see messages sent in this reply thread return reply_root_id === currentPageReplyRootId }) } /** * Format text for typing indicators based on the number of people typing */ export const getTypingIndicatorText = (people: PersonTyping[]): string => { if (!people.length) return '' if (people.length === 1) { return `${people[0].author_name} is typing...` } else if (people.length === 2) { return `${people[0].author_name} and ${people[1].author_name} are typing...` } else { return 'Several people are typing...' } } const stableArray: PersonTyping[] = []