about summary refs log tree commit diff
path: root/src/state/messages/convo/index.tsx
blob: a53f08900001f7b7b2019bcfeda6eebb7c2a0d61 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import React, {useContext, useState, useSyncExternalStore} from 'react'
import {type ChatBskyConvoDefs} from '@atproto/api'
import {useFocusEffect} from '@react-navigation/native'
import {useQueryClient} from '@tanstack/react-query'

import {useAppState} from '#/lib/hooks/useAppState'
import {Convo} from '#/state/messages/convo/agent'
import {
  type ConvoParams,
  type ConvoState,
  type ConvoStateBackgrounded,
  type ConvoStateDisabled,
  type ConvoStateReady,
  type ConvoStateSuspended,
} from '#/state/messages/convo/types'
import {isConvoActive} from '#/state/messages/convo/util'
import {useMessagesEventBus} from '#/state/messages/events'
import {
  RQKEY as getConvoKey,
  useMarkAsReadMutation,
} from '#/state/queries/messages/conversation'
import {RQKEY_ROOT as ListConvosQueryKeyRoot} from '#/state/queries/messages/list-conversations'
import {RQKEY as createProfileQueryKey} from '#/state/queries/profile'
import {useAgent} from '#/state/session'

export * from '#/state/messages/convo/util'

const ChatContext = React.createContext<ConvoState | null>(null)

export function useConvo() {
  const ctx = useContext(ChatContext)
  if (!ctx) {
    throw new Error('useConvo must be used within a ConvoProvider')
  }
  return ctx
}

/**
 * This hook should only be used when the Convo is "active", meaning the chat
 * is loaded and ready to be used, or its in a suspended or background state,
 * and ready for resumption.
 */
export function useConvoActive() {
  const ctx = useContext(ChatContext) as
    | ConvoStateReady
    | ConvoStateBackgrounded
    | ConvoStateSuspended
    | ConvoStateDisabled
  if (!ctx) {
    throw new Error('useConvo must be used within a ConvoProvider')
  }
  if (!isConvoActive(ctx)) {
    throw new Error(
      `useConvoActive must only be rendered when the Convo is ready.`,
    )
  }
  return ctx
}

export function ConvoProvider({
  children,
  convoId,
}: Pick<ConvoParams, 'convoId'> & {children: React.ReactNode}) {
  const queryClient = useQueryClient()
  const agent = useAgent()
  const events = useMessagesEventBus()
  const [convo] = useState(() => {
    const placeholder = queryClient.getQueryData<ChatBskyConvoDefs.ConvoView>(
      getConvoKey(convoId),
    )
    return new Convo({
      convoId,
      agent,
      events,
      placeholderData: placeholder ? {convo: placeholder} : undefined,
    })
  })
  const service = useSyncExternalStore(convo.subscribe, convo.getSnapshot)
  const {mutate: markAsRead} = useMarkAsReadMutation()

  const appState = useAppState()
  const isActive = appState === 'active'
  useFocusEffect(
    React.useCallback(() => {
      if (isActive) {
        convo.resume()
        markAsRead({convoId})

        return () => {
          convo.background()
          markAsRead({convoId})
        }
      }
    }, [isActive, convo, convoId, markAsRead]),
  )

  React.useEffect(() => {
    return convo.on(event => {
      switch (event.type) {
        case 'invalidate-block-state': {
          for (const did of event.accountDids) {
            queryClient.invalidateQueries({
              queryKey: createProfileQueryKey(did),
            })
          }
          queryClient.invalidateQueries({
            queryKey: [ListConvosQueryKeyRoot],
          })
        }
      }
    })
  }, [convo, queryClient])

  return <ChatContext.Provider value={service}>{children}</ChatContext.Provider>
}