|
| 1 | +import { useEffect, useState } from 'react'; |
| 2 | + |
| 3 | +import { AIState, Channel, Event } from 'stream-chat'; |
| 4 | + |
| 5 | +import type { DefaultStreamChatGenerics } from '../../../types/types'; |
| 6 | + |
| 7 | +export const AIStates = { |
| 8 | + Error: 'AI_STATE_ERROR', |
| 9 | + ExternalSources: 'AI_STATE_EXTERNAL_SOURCES', |
| 10 | + Generating: 'AI_STATE_GENERATING', |
| 11 | + Idle: 'AI_STATE_IDLE', |
| 12 | + Thinking: 'AI_STATE_THINKING', |
| 13 | +}; |
| 14 | + |
| 15 | +/** |
| 16 | + * A hook that returns the current state of the AI. |
| 17 | + * @param {Channel} channel - The channel for which we want to know the AI state. |
| 18 | + * @returns {{ aiState: AIState }} The current AI state for the given channel. |
| 19 | + */ |
| 20 | +export const useAIState = < |
| 21 | + StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics |
| 22 | +>( |
| 23 | + channel?: Channel<StreamChatGenerics>, |
| 24 | +): { aiState: AIState } => { |
| 25 | + const [aiState, setAiState] = useState<AIState>(AIStates.Idle); |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + if (!channel) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + const indicatorChangedListener = channel.on( |
| 33 | + 'ai_indicator.update', |
| 34 | + (event: Event<StreamChatGenerics>) => { |
| 35 | + const { cid } = event; |
| 36 | + const state = event.ai_state as AIState; |
| 37 | + if (channel.cid === cid) { |
| 38 | + setAiState(state); |
| 39 | + } |
| 40 | + }, |
| 41 | + ); |
| 42 | + |
| 43 | + const indicatorClearedListener = channel.on('ai_indicator.clear', (event) => { |
| 44 | + const { cid } = event; |
| 45 | + if (channel.cid === cid) { |
| 46 | + setAiState(AIStates.Idle); |
| 47 | + } |
| 48 | + }); |
| 49 | + |
| 50 | + return () => { |
| 51 | + indicatorChangedListener.unsubscribe(); |
| 52 | + indicatorClearedListener.unsubscribe(); |
| 53 | + }; |
| 54 | + }, [channel]); |
| 55 | + |
| 56 | + return { aiState }; |
| 57 | +}; |
0 commit comments