about summary refs log tree commit diff
path: root/src/state/queries/usePostThread/index.ts
blob: 782888cfbef4135763db512ccae33fd0dd7b8272 (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
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
318
319
320
321
322
323
324
325
import {useCallback, useMemo, useState} from 'react'
import {useQuery, useQueryClient} from '@tanstack/react-query'

import {isWeb} from '#/platform/detection'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {useThreadPreferences} from '#/state/queries/preferences/useThreadPreferences'
import {
  LINEAR_VIEW_BELOW,
  LINEAR_VIEW_BF,
  TREE_VIEW_BELOW,
  TREE_VIEW_BELOW_DESKTOP,
  TREE_VIEW_BF,
} from '#/state/queries/usePostThread/const'
import {
  createCacheMutator,
  getThreadPlaceholder,
} from '#/state/queries/usePostThread/queryCache'
import {
  buildThread,
  sortAndAnnotateThreadItems,
} from '#/state/queries/usePostThread/traversal'
import {
  createPostThreadOtherQueryKey,
  createPostThreadQueryKey,
  type ThreadItem,
  type UsePostThreadQueryResult,
} from '#/state/queries/usePostThread/types'
import {getThreadgateRecord} from '#/state/queries/usePostThread/utils'
import * as views from '#/state/queries/usePostThread/views'
import {useAgent, useSession} from '#/state/session'
import {useMergeThreadgateHiddenReplies} from '#/state/threadgate-hidden-replies'
import {useBreakpoints} from '#/alf'

export * from '#/state/queries/usePostThread/types'

export function usePostThread({anchor}: {anchor?: string}) {
  const qc = useQueryClient()
  const agent = useAgent()
  const {hasSession} = useSession()
  const {gtPhone} = useBreakpoints()
  const moderationOpts = useModerationOpts()
  const mergeThreadgateHiddenReplies = useMergeThreadgateHiddenReplies()
  const {
    isLoaded: isThreadPreferencesLoaded,
    sort,
    setSort: baseSetSort,
    view,
    setView: baseSetView,
    prioritizeFollowedUsers,
  } = useThreadPreferences()
  const below = useMemo(() => {
    return view === 'linear'
      ? LINEAR_VIEW_BELOW
      : isWeb && gtPhone
      ? TREE_VIEW_BELOW_DESKTOP
      : TREE_VIEW_BELOW
  }, [view, gtPhone])

  const postThreadQueryKey = createPostThreadQueryKey({
    anchor,
    sort,
    view,
    prioritizeFollowedUsers,
  })
  const postThreadOtherQueryKey = createPostThreadOtherQueryKey({
    anchor,
    prioritizeFollowedUsers,
  })

  const query = useQuery<UsePostThreadQueryResult>({
    enabled: isThreadPreferencesLoaded && !!anchor && !!moderationOpts,
    queryKey: postThreadQueryKey,
    async queryFn(ctx) {
      const {data} = await agent.app.bsky.unspecced.getPostThreadV2({
        anchor: anchor!,
        branchingFactor: view === 'linear' ? LINEAR_VIEW_BF : TREE_VIEW_BF,
        below,
        sort: sort,
        prioritizeFollowedUsers: prioritizeFollowedUsers,
      })

      /*
       * Initialize `ctx.meta` to track if we know we have additional replies
       * we could fetch once we hit the end.
       */
      ctx.meta = ctx.meta || {
        hasOtherReplies: false,
      }

      /*
       * If we know we have additional replies, we'll set this to true.
       */
      if (data.hasOtherReplies) {
        ctx.meta.hasOtherReplies = true
      }

      const result = {
        thread: data.thread || [],
        threadgate: data.threadgate,
        hasOtherReplies: !!ctx.meta.hasOtherReplies,
      }

      const record = getThreadgateRecord(result.threadgate)
      if (result.threadgate && record) {
        result.threadgate.record = record
      }

      return result as UsePostThreadQueryResult
    },
    placeholderData() {
      if (!anchor) return
      const placeholder = getThreadPlaceholder(qc, anchor)
      /*
       * Always return something here, even empty data, so that
       * `isPlaceholderData` is always true, which we'll use to insert
       * skeletons.
       */
      const thread = placeholder ? [placeholder] : []
      return {thread, threadgate: undefined, hasOtherReplies: false}
    },
    select(data) {
      const record = getThreadgateRecord(data.threadgate)
      if (data.threadgate && record) {
        data.threadgate.record = record
      }
      return data
    },
  })

  const thread = useMemo(() => query.data?.thread || [], [query.data?.thread])
  const threadgate = useMemo(
    () => query.data?.threadgate,
    [query.data?.threadgate],
  )
  const hasOtherThreadItems = useMemo(
    () => !!query.data?.hasOtherReplies,
    [query.data?.hasOtherReplies],
  )
  const [otherItemsVisible, setOtherItemsVisible] = useState(false)

  /**
   * Creates a mutator for the post thread cache. This is used to insert
   * replies into the thread cache after posting.
   */
  const mutator = useMemo(
    () =>
      createCacheMutator({
        params: {view, below},
        postThreadQueryKey,
        postThreadOtherQueryKey,
        queryClient: qc,
      }),
    [qc, view, below, postThreadQueryKey, postThreadOtherQueryKey],
  )

  /**
   * If we have additional items available from the server and the user has
   * chosen to view them, start loading data
   */
  const additionalQueryEnabled = hasOtherThreadItems && otherItemsVisible
  const additionalItemsQuery = useQuery({
    enabled: additionalQueryEnabled,
    queryKey: postThreadOtherQueryKey,
    async queryFn() {
      const {data} = await agent.app.bsky.unspecced.getPostThreadOtherV2({
        anchor: anchor!,
        prioritizeFollowedUsers,
      })
      return data
    },
  })
  const serverOtherThreadItems: ThreadItem[] = useMemo(() => {
    if (!additionalQueryEnabled) return []
    if (additionalItemsQuery.isLoading) {
      return Array.from({length: 2}).map((_, i) =>
        views.skeleton({
          key: `other-reply-${i}`,
          item: 'reply',
        }),
      )
    } else if (additionalItemsQuery.isError) {
      /*
       * We could insert an special error component in here, but since these
       * are optional additional replies, it's not critical that they're shown
       * atm.
       */
      return []
    } else if (additionalItemsQuery.data?.thread) {
      const {threadItems} = sortAndAnnotateThreadItems(
        additionalItemsQuery.data.thread,
        {
          view,
          skipModerationHandling: true,
          threadgateHiddenReplies: mergeThreadgateHiddenReplies(
            threadgate?.record,
          ),
          moderationOpts: moderationOpts!,
        },
      )
      return threadItems
    } else {
      return []
    }
  }, [
    view,
    additionalQueryEnabled,
    additionalItemsQuery,
    mergeThreadgateHiddenReplies,
    moderationOpts,
    threadgate?.record,
  ])

  /**
   * Sets the sort order for the thread and resets the additional thread items
   */
  const setSort: typeof baseSetSort = useCallback(
    nextSort => {
      setOtherItemsVisible(false)
      baseSetSort(nextSort)
    },
    [baseSetSort, setOtherItemsVisible],
  )

  /**
   * Sets the view variant for the thread and resets the additional thread items
   */
  const setView: typeof baseSetView = useCallback(
    nextView => {
      setOtherItemsVisible(false)
      baseSetView(nextView)
    },
    [baseSetView, setOtherItemsVisible],
  )

  /*
   * This is the main thread response, sorted into separate buckets based on
   * moderation, and annotated with all UI state needed for rendering.
   */
  const {threadItems, otherThreadItems} = useMemo(() => {
    return sortAndAnnotateThreadItems(thread, {
      view: view,
      threadgateHiddenReplies: mergeThreadgateHiddenReplies(threadgate?.record),
      moderationOpts: moderationOpts!,
    })
  }, [
    thread,
    threadgate?.record,
    mergeThreadgateHiddenReplies,
    moderationOpts,
    view,
  ])

  /*
   * Take all three sets of thread items and combine them into a single thread,
   * along with any other thread items required for rendering e.g. "Show more
   * replies" or the reply composer.
   */
  const items = useMemo(() => {
    return buildThread({
      threadItems,
      otherThreadItems,
      serverOtherThreadItems,
      isLoading: query.isPlaceholderData,
      hasSession,
      hasOtherThreadItems,
      otherItemsVisible,
      showOtherItems: () => setOtherItemsVisible(true),
    })
  }, [
    threadItems,
    otherThreadItems,
    serverOtherThreadItems,
    query.isPlaceholderData,
    hasSession,
    hasOtherThreadItems,
    otherItemsVisible,
    setOtherItemsVisible,
  ])

  return useMemo(
    () => ({
      state: {
        /*
         * Copy in any query state that is useful
         */
        isFetching: query.isFetching,
        isPlaceholderData: query.isPlaceholderData,
        error: query.error,
        /*
         * Other state
         */
        sort,
        view,
        otherItemsVisible,
      },
      data: {
        items,
        threadgate,
      },
      actions: {
        /*
         * Copy in any query actions that are useful
         */
        insertReplies: mutator.insertReplies,
        refetch: query.refetch,
        /*
         * Other actions
         */
        setSort,
        setView,
      },
    }),
    [
      query,
      mutator.insertReplies,
      otherItemsVisible,
      sort,
      view,
      setSort,
      setView,
      threadgate,
      items,
    ],
  )
}