about summary refs log tree commit diff
path: root/src/view/com/post-thread/PostThread.tsx
blob: 6b7f96e0684c78a77060ac24fc56c1fc6866b982 (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
import React, {useState, useEffect} from 'react'
import {observer} from 'mobx-react-lite'
import {ActivityIndicator, FlatList, Text, View} from 'react-native'
import {
  PostThreadViewModel,
  PostThreadViewPostModel,
} from '../../../state/models/post-thread-view'
import {useStores} from '../../../state'
import {SharePostModel} from '../../../state/models/shell-ui'
import {PostThreadItem} from './PostThreadItem'
import {ErrorMessage} from '../util/ErrorMessage'

export const PostThread = observer(function PostThread({
  uri,
  view,
}: {
  uri: string
  view: PostThreadViewModel
}) {
  const store = useStores()

  const onPressShare = (uri: string) => {
    store.shell.openModal(new SharePostModel(uri))
  }
  const onRefresh = () => {
    view?.refresh().catch(err => console.error('Failed to refresh', err))
  }

  // loading
  // =
  if ((view.isLoading && !view.isRefreshing) || view.params.uri !== uri) {
    return (
      <View>
        <ActivityIndicator />
      </View>
    )
  }

  // error
  // =
  if (view.hasError) {
    return (
      <View>
        <ErrorMessage
          dark
          message={view.error}
          style={{margin: 6}}
          onPressTryAgain={onRefresh}
        />
      </View>
    )
  }

  // loaded
  // =
  const posts = view.thread ? Array.from(flattenThread(view.thread)) : []
  const renderItem = ({item}: {item: PostThreadViewPostModel}) => (
    <PostThreadItem
      item={item}
      onPressShare={onPressShare}
      onPostReply={onRefresh}
    />
  )
  return (
    <FlatList
      data={posts}
      keyExtractor={item => item._reactKey}
      renderItem={renderItem}
      refreshing={view.isRefreshing}
      onRefresh={onRefresh}
      style={{flex: 1}}
    />
  )
})

function* flattenThread(
  post: PostThreadViewPostModel,
): Generator<PostThreadViewPostModel, void> {
  if (post.parent) {
    yield* flattenThread(post.parent)
  }
  yield post
  if (post.replies?.length) {
    for (const reply of post.replies) {
      yield* flattenThread(reply)
    }
  }
}