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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
|
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
} from 'react'
import {
ChatBskyConvoDefs,
ChatBskyConvoListConvos,
moderateProfile,
} from '@atproto/api'
import {
InfiniteData,
QueryClient,
useInfiniteQuery,
useQueryClient,
} from '@tanstack/react-query'
import {useCurrentConvoId} from '#/state/messages/current-convo-id'
import {useMessagesEventBus} from '#/state/messages/events'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {DM_SERVICE_HEADERS} from '#/state/queries/messages/const'
import {useAgent, useSession} from '#/state/session'
export const RQKEY = ['convo-list']
type RQPageParam = string | undefined
export function useListConvosQuery() {
const {getAgent} = useAgent()
return useInfiniteQuery({
queryKey: RQKEY,
queryFn: async ({pageParam}) => {
const {data} = await getAgent().api.chat.bsky.convo.listConvos(
{cursor: pageParam},
{headers: DM_SERVICE_HEADERS},
)
return data
},
initialPageParam: undefined as RQPageParam,
getNextPageParam: lastPage => lastPage.cursor,
// refetch every 60 seconds since we can't get *all* info from the logs
// i.e. reading chats on another device won't update the unread count
refetchInterval: 60_000,
})
}
const ListConvosContext = createContext<ChatBskyConvoDefs.ConvoView[] | null>(
null,
)
export function useListConvos() {
const ctx = useContext(ListConvosContext)
if (!ctx) {
throw new Error('useListConvos must be used within a ListConvosProvider')
}
return ctx
}
export function ListConvosProvider({children}: {children: React.ReactNode}) {
const {hasSession} = useSession()
if (!hasSession) {
return (
<ListConvosContext.Provider value={[]}>
{children}
</ListConvosContext.Provider>
)
}
return <ListConvosProviderInner>{children}</ListConvosProviderInner>
}
export function ListConvosProviderInner({
children,
}: {
children: React.ReactNode
}) {
const {refetch, data} = useListConvosQuery()
const messagesBus = useMessagesEventBus()
const queryClient = useQueryClient()
const {currentConvoId} = useCurrentConvoId()
const {currentAccount} = useSession()
useEffect(() => {
const unsub = messagesBus.on(
events => {
if (events.type !== 'logs') return
events.logs.forEach(log => {
if (ChatBskyConvoDefs.isLogBeginConvo(log)) {
refetch()
} else if (ChatBskyConvoDefs.isLogLeaveConvo(log)) {
queryClient.setQueryData(RQKEY, (old: ConvoListQueryData) =>
optimisticDelete(log.convoId, old),
)
} else if (ChatBskyConvoDefs.isLogDeleteMessage(log)) {
queryClient.setQueryData(RQKEY, (old: ConvoListQueryData) =>
optimisticUpdate(log.convoId, old, convo =>
log.message.id === convo.lastMessage?.id
? {
...convo,
rev: log.rev,
lastMessage: log.message,
}
: convo,
),
)
} else if (ChatBskyConvoDefs.isLogCreateMessage(log)) {
queryClient.setQueryData(RQKEY, (old: ConvoListQueryData) => {
if (!old) return old
function updateConvo(convo: ChatBskyConvoDefs.ConvoView) {
if (!ChatBskyConvoDefs.isLogCreateMessage(log)) return convo
let unreadCount = convo.unreadCount
if (convo.id !== currentConvoId) {
if (
ChatBskyConvoDefs.isMessageView(log.message) ||
ChatBskyConvoDefs.isDeletedMessageView(log.message)
) {
if (log.message.sender.did !== currentAccount?.did) {
unreadCount++
}
}
} else {
unreadCount = 0
}
return {
...convo,
rev: log.rev,
lastMessage: log.message,
unreadCount,
}
}
function filterConvoFromPage(
convo: ChatBskyConvoDefs.ConvoView[],
) {
return convo.filter(c => c.id !== log.convoId)
}
const existingConvo = getConvoFromQueryData(log.convoId, old)
if (existingConvo) {
return {
...old,
pages: old.pages.map((page, i) => {
if (i === 0) {
return {
...page,
convos: [
updateConvo(existingConvo),
...filterConvoFromPage(page.convos),
],
}
}
return {
...page,
convos: filterConvoFromPage(page.convos),
}
}),
}
} else {
refetch()
}
})
}
})
},
{
// get events for all chats
convoId: undefined,
},
)
return () => unsub()
}, [messagesBus, currentConvoId, refetch, queryClient, currentAccount?.did])
const ctx = useMemo(() => {
return data?.pages.flatMap(page => page.convos) ?? []
}, [data])
return (
<ListConvosContext.Provider value={ctx}>
{children}
</ListConvosContext.Provider>
)
}
export function useUnreadMessageCount() {
const {currentConvoId} = useCurrentConvoId()
const {currentAccount} = useSession()
const convos = useListConvos()
const moderationOpts = useModerationOpts()
const count = useMemo(() => {
return (
convos
.filter(convo => convo.id !== currentConvoId)
.reduce((acc, convo) => {
const otherMember = convo.members.find(
member => member.did !== currentAccount?.did,
)
if (!otherMember || !moderationOpts) return acc
const moderation = moderateProfile(otherMember, moderationOpts)
const shouldIgnore =
convo.muted ||
moderation.blocked ||
otherMember.did === 'missing.invalid'
const unreadCount = !shouldIgnore && convo.unreadCount > 0 ? 1 : 0
return acc + unreadCount
}, 0) ?? 0
)
}, [convos, currentAccount?.did, currentConvoId, moderationOpts])
return useMemo(() => {
return {
count,
numUnread: count > 0 ? (count > 30 ? '30+' : String(count)) : undefined,
}
}, [count])
}
type ConvoListQueryData = {
pageParams: Array<string | undefined>
pages: Array<ChatBskyConvoListConvos.OutputSchema>
}
export function useOnMarkAsRead() {
const queryClient = useQueryClient()
return useCallback(
(chatId: string) => {
queryClient.setQueryData(RQKEY, (old: ConvoListQueryData) => {
return optimisticUpdate(chatId, old, convo => ({
...convo,
unreadCount: 0,
}))
})
},
[queryClient],
)
}
function optimisticUpdate(
chatId: string,
old: ConvoListQueryData,
updateFn: (convo: ChatBskyConvoDefs.ConvoView) => ChatBskyConvoDefs.ConvoView,
) {
if (!old) return old
return {
...old,
pages: old.pages.map(page => ({
...page,
convos: page.convos.map(convo =>
chatId === convo.id ? updateFn(convo) : convo,
),
})),
}
}
function optimisticDelete(chatId: string, old: ConvoListQueryData) {
if (!old) return old
return {
...old,
pages: old.pages.map(page => ({
...page,
convos: page.convos.filter(convo => chatId !== convo.id),
})),
}
}
function getConvoFromQueryData(chatId: string, old: ConvoListQueryData) {
for (const page of old.pages) {
for (const convo of page.convos) {
if (convo.id === chatId) {
return convo
}
}
}
return null
}
export function* findAllProfilesInQueryData(
queryClient: QueryClient,
did: string,
) {
const queryDatas = queryClient.getQueriesData<
InfiniteData<ChatBskyConvoListConvos.OutputSchema>
>({
queryKey: RQKEY,
})
for (const [_queryKey, queryData] of queryDatas) {
if (!queryData?.pages) {
continue
}
for (const page of queryData.pages) {
for (const convo of page.convos) {
for (const member of convo.members) {
if (member.did === did) {
yield member
}
}
}
}
}
}
|