about summary refs log tree commit diff
path: root/src/view/com/post-thread/PostThread.tsx
blob: b3da0b01b6f9c31de2f7e1e955f630984515d526 (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
import React, {useRef} from 'react'
import {observer} from 'mobx-react-lite'
import {
  ActivityIndicator,
  RefreshControl,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native'
import {AppBskyFeedDefs} from '@atproto/api'
import {CenteredView, FlatList} from '../util/Views'
import {
  PostThreadModel,
  PostThreadItemModel,
} from 'state/models/content/post-thread'
import {
  FontAwesomeIcon,
  FontAwesomeIconStyle,
} from '@fortawesome/react-native-fontawesome'
import {PostThreadItem} from './PostThreadItem'
import {ComposePrompt} from '../composer/Prompt'
import {ErrorMessage} from '../util/error/ErrorMessage'
import {Text} from '../util/text/Text'
import {s} from 'lib/styles'
import {isDesktopWeb, isMobileWeb} from 'platform/detection'
import {usePalette} from 'lib/hooks/usePalette'
import {useNavigation} from '@react-navigation/native'
import {NavigationProp} from 'lib/routes/types'

const REPLY_PROMPT = {_reactKey: '__reply__', _isHighlightedPost: false}
const DELETED = {_reactKey: '__deleted__', _isHighlightedPost: false}
const BLOCKED = {_reactKey: '__blocked__', _isHighlightedPost: false}
const BOTTOM_COMPONENT = {
  _reactKey: '__bottom_component__',
  _isHighlightedPost: false,
}
type YieldedItem =
  | PostThreadItemModel
  | typeof REPLY_PROMPT
  | typeof DELETED
  | typeof BLOCKED

export const PostThread = observer(function PostThread({
  uri,
  view,
  onPressReply,
}: {
  uri: string
  view: PostThreadModel
  onPressReply: () => void
}) {
  const pal = usePalette('default')
  const ref = useRef<FlatList>(null)
  const [isRefreshing, setIsRefreshing] = React.useState(false)
  const navigation = useNavigation<NavigationProp>()
  const posts = React.useMemo(() => {
    if (view.thread) {
      return Array.from(flattenThread(view.thread)).concat([BOTTOM_COMPONENT])
    }
    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 onPressBack = React.useCallback(() => {
    if (navigation.canGoBack()) {
      navigation.goBack()
    } else {
      navigation.navigate('Home')
    }
  }, [navigation])

  const renderItem = React.useCallback(
    ({item}: {item: YieldedItem}) => {
      if (item === REPLY_PROMPT) {
        return <ComposePrompt onPressCompose={onPressReply} />
      } else if (item === DELETED) {
        return (
          <View style={[pal.border, pal.viewLight, styles.missingItem]}>
            <Text type="lg-bold" style={pal.textLight}>
              Deleted post.
            </Text>
          </View>
        )
      } else if (item === BLOCKED) {
        return (
          <View style={[pal.border, pal.viewLight, styles.missingItem]}>
            <Text type="lg-bold" style={pal.textLight}>
              Blocked post.
            </Text>
          </View>
        )
      } else if (item === BOTTOM_COMPONENT) {
        // 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
        // -
        // addendum -- it's also the best way to get mobile web to add padding
        // at the bottom of the thread since paddingbottom is ignored. yikes.
        // -prf
        return (
          <View
            style={[
              styles.bottomBorder,
              pal.border,
              isMobileWeb && styles.bottomSpacer,
            ]}
          />
        )
      } else if (item instanceof PostThreadItemModel) {
        return <PostThreadItem item={item} onPostReply={onRefresh} />
      }
      return <></>
    },
    [onRefresh, onPressReply, pal],
  )

  // loading
  // =
  if (
    !view.hasLoaded ||
    (view.isLoading && !view.isRefreshing) ||
    view.params.uri !== uri
  ) {
    return (
      <CenteredView>
        <View style={s.p20}>
          <ActivityIndicator size="large" />
        </View>
      </CenteredView>
    )
  }

  // error
  // =
  if (view.hasError) {
    if (view.notFound) {
      return (
        <CenteredView>
          <View style={[pal.view, pal.border, styles.notFoundContainer]}>
            <Text type="title-lg" style={[pal.text, s.mb5]}>
              Post not found
            </Text>
            <Text type="md" style={[pal.text, s.mb10]}>
              The post may have been deleted.
            </Text>
            <TouchableOpacity
              onPress={onPressBack}
              accessibilityRole="button"
              accessibilityLabel="Back"
              accessibilityHint="">
              <Text type="2xl" style={pal.link}>
                <FontAwesomeIcon
                  icon="angle-left"
                  style={[pal.link as FontAwesomeIconStyle, s.mr5]}
                  size={14}
                />
                Back
              </Text>
            </TouchableOpacity>
          </View>
        </CenteredView>
      )
    }
    return (
      <CenteredView>
        <ErrorMessage message={view.error} onPressTryAgain={onRefresh} />
      </CenteredView>
    )
  }
  if (view.isBlocked) {
    return (
      <CenteredView>
        <View style={[pal.view, pal.border, styles.notFoundContainer]}>
          <Text type="title-lg" style={[pal.text, s.mb5]}>
            Post hidden
          </Text>
          <Text type="md" style={[pal.text, s.mb10]}>
            You have blocked the author or you have been blocked by the author.
          </Text>
          <TouchableOpacity
            onPress={onPressBack}
            accessibilityRole="button"
            accessibilityLabel="Back"
            accessibilityHint="">
            <Text type="2xl" style={pal.link}>
              <FontAwesomeIcon
                icon="angle-left"
                style={[pal.link as FontAwesomeIconStyle, s.mr5]}
                size={14}
              />
              Back
            </Text>
          </TouchableOpacity>
        </View>
      </CenteredView>
    )
  }

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

function* flattenThread(
  post: PostThreadItemModel,
  isAscending = false,
): Generator<YieldedItem, void> {
  if (post.parent) {
    if (AppBskyFeedDefs.isNotFoundPost(post.parent)) {
      yield DELETED
    } else if (AppBskyFeedDefs.isBlockedPost(post.parent)) {
      yield BLOCKED
    } else {
      yield* flattenThread(post.parent as PostThreadItemModel, true)
    }
  }
  yield post
  if (isDesktopWeb && post._isHighlightedPost) {
    yield REPLY_PROMPT
  }
  if (post.replies?.length) {
    for (const reply of post.replies) {
      if (AppBskyFeedDefs.isNotFoundPost(reply)) {
        yield DELETED
      } else {
        yield* flattenThread(reply as PostThreadItemModel)
      }
    }
  } else if (!isAscending && !post.parent && post.post.replyCount) {
    post._hasMore = true
  }
}

const styles = StyleSheet.create({
  notFoundContainer: {
    margin: 10,
    paddingHorizontal: 18,
    paddingVertical: 14,
    borderRadius: 6,
  },
  missingItem: {
    borderTop: 1,
    paddingHorizontal: 18,
    paddingVertical: 18,
  },
  bottomBorder: {
    borderBottomWidth: 1,
  },
  bottomSpacer: {
    height: 200,
  },
})