about summary refs log tree commit diff
path: root/src/view/com/post-thread/PostThread.tsx
blob: f84593db80cfcf5f5b7476efc42c1fa3753cd029 (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
import React, {useRef} from 'react'
import {observer} from 'mobx-react-lite'
import {ActivityIndicator, StyleSheet, View} from 'react-native'
import {CenteredView, FlatList} from '../util/Views'
import {
  PostThreadViewModel,
  PostThreadViewPostModel,
} from 'state/models/post-thread-view'
import {PostThreadItem} from './PostThreadItem'
import {ComposePrompt} from '../composer/Prompt'
import {ErrorMessage} from '../util/error/ErrorMessage'
import {s} from 'lib/styles'
import {isDesktopWeb} from 'platform/detection'
import {usePalette} from 'lib/hooks/usePalette'

const REPLY_PROMPT = {_reactKey: '__reply__', _isHighlightedPost: false}
const BOTTOM_BORDER = {
  _reactKey: '__bottom_border__',
  _isHighlightedPost: false,
}
type YieldedItem = PostThreadViewPostModel | typeof REPLY_PROMPT

export const PostThread = observer(function PostThread({
  uri,
  view,
  onPressReply,
}: {
  uri: string
  view: PostThreadViewModel
  onPressReply: () => void
}) {
  const pal = usePalette('default')
  const ref = useRef<FlatList>(null)
  const [isRefreshing, setIsRefreshing] = React.useState(false)
  const posts = React.useMemo(() => {
    if (view.thread) {
      return Array.from(flattenThread(view.thread)).concat([BOTTOM_BORDER])
    }
    return []
  }, [view.thread])

  // events
  // =
  const onRefresh = React.useCallback(async () => {
    setIsRefreshing(true)
    try {
      view?.refresh()
    } catch (err) {
      view.rootStore.log.error('Failed to refresh posts thread', err)
    }
    setIsRefreshing(false)
  }, [view, setIsRefreshing])
  const onLayout = React.useCallback(() => {
    const index = posts.findIndex(post => post._isHighlightedPost)
    if (index !== -1) {
      ref.current?.scrollToIndex({
        index,
        animated: false,
        viewOffset: 40,
      })
    }
  }, [posts, ref])
  const onScrollToIndexFailed = React.useCallback(
    (info: {
      index: number
      highestMeasuredFrameIndex: number
      averageItemLength: number
    }) => {
      ref.current?.scrollToOffset({
        animated: false,
        offset: info.averageItemLength * info.index,
      })
    },
    [ref],
  )
  const renderItem = React.useCallback(
    ({item}: {item: YieldedItem}) => {
      if (item === REPLY_PROMPT) {
        return <ComposePrompt onPressCompose={onPressReply} />
      } else if (item === BOTTOM_BORDER) {
        // HACK
        // due to some complexities with how flatlist works, this is the easiest way
        // I could find to get a border positioned directly under the last item
        // -prf
        return <View style={[styles.bottomBorder, pal.border]} />
      } else if (item instanceof PostThreadViewPostModel) {
        return <PostThreadItem item={item} onPostReply={onRefresh} />
      }
      return <></>
    },
    [onRefresh, onPressReply, pal],
  )

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

  // error
  // =
  if (view.hasError) {
    return (
      <CenteredView>
        <ErrorMessage message={view.error} onPressTryAgain={onRefresh} />
      </CenteredView>
    )
  }

  // loaded
  // =
  return (
    <FlatList
      ref={ref}
      data={posts}
      initialNumToRender={posts.length}
      keyExtractor={item => item._reactKey}
      renderItem={renderItem}
      refreshing={isRefreshing}
      onRefresh={onRefresh}
      onLayout={onLayout}
      onScrollToIndexFailed={onScrollToIndexFailed}
      style={s.hContentRegion}
      contentContainerStyle={s.contentContainerExtra}
    />
  )
})

function* flattenThread(
  post: PostThreadViewPostModel,
  isAscending = false,
): Generator<YieldedItem, void> {
  if (post.parent) {
    if ('notFound' in post.parent && post.parent.notFound) {
      // TODO render not found
    } else {
      yield* flattenThread(post.parent as PostThreadViewPostModel, true)
    }
  }
  yield post
  if (isDesktopWeb && post._isHighlightedPost) {
    yield REPLY_PROMPT
  }
  if (post.replies?.length) {
    for (const reply of post.replies) {
      if ('notFound' in reply && reply.notFound) {
        // TODO render not found
      } else {
        yield* flattenThread(reply as PostThreadViewPostModel)
      }
    }
  } else if (!isAscending && !post.parent && post.post.replyCount > 0) {
    post._hasMore = true
  }
}

const styles = StyleSheet.create({
  bottomBorder: {
    borderBottomWidth: 1,
  },
})