about summary refs log tree commit diff
path: root/src/view/com/notifications/Feed.tsx
blob: 2196b34691606ddd91f2a6d6217b8bb490bd12c3 (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
import React, {MutableRefObject} from 'react'
import {observer} from 'mobx-react-lite'
import {CenteredView, FlatList} from '../util/Views'
import {ActivityIndicator, RefreshControl, StyleSheet, View} from 'react-native'
import {NotificationsFeedModel} from 'state/models/feeds/notifications'
import {FeedItem} from './FeedItem'
import {NotificationFeedLoadingPlaceholder} from '../util/LoadingPlaceholder'
import {ErrorMessage} from '../util/error/ErrorMessage'
import {LoadMoreRetryBtn} from '../util/LoadMoreRetryBtn'
import {EmptyState} from '../util/EmptyState'
import {OnScrollCb} from 'lib/hooks/useOnMainScroll'
import {s} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette'

const EMPTY_FEED_ITEM = {_reactKey: '__empty__'}
const LOAD_MORE_ERROR_ITEM = {_reactKey: '__load_more_error__'}

export const Feed = observer(function Feed({
  view,
  scrollElRef,
  onPressTryAgain,
  onScroll,
}: {
  view: NotificationsFeedModel
  scrollElRef?: MutableRefObject<FlatList<any> | null>
  onPressTryAgain?: () => void
  onScroll?: OnScrollCb
}) {
  const pal = usePalette('default')
  const data = React.useMemo(() => {
    let feedItems
    if (view.hasLoaded) {
      if (view.isEmpty) {
        feedItems = [EMPTY_FEED_ITEM]
      } else {
        feedItems = view.notifications
      }
    }
    if (view.loadMoreError) {
      feedItems = (feedItems || []).concat([LOAD_MORE_ERROR_ITEM])
    }
    return feedItems
  }, [view.hasLoaded, view.isEmpty, view.notifications, view.loadMoreError])

  const onRefresh = React.useCallback(async () => {
    try {
      await view.refresh()
      await view.markAllRead()
    } catch (err) {
      view.rootStore.log.error('Failed to refresh notifications feed', err)
    }
  }, [view])

  const onEndReached = React.useCallback(async () => {
    try {
      await view.loadMore()
    } catch (err) {
      view.rootStore.log.error('Failed to load more notifications', err)
    }
  }, [view])

  const onPressRetryLoadMore = React.useCallback(() => {
    view.retryLoadMore()
  }, [view])

  // TODO optimize renderItem or FeedItem, we're getting this notice from RN: -prf
  //   VirtualizedList: You have a large list that is slow to update - make sure your
  //   renderItem function renders components that follow React performance best practices
  //   like PureComponent, shouldComponentUpdate, etc
  const renderItem = React.useCallback(
    ({item}: {item: any}) => {
      if (item === EMPTY_FEED_ITEM) {
        return (
          <EmptyState
            icon="bell"
            message="No notifications yet!"
            style={styles.emptyState}
          />
        )
      } else if (item === LOAD_MORE_ERROR_ITEM) {
        return (
          <LoadMoreRetryBtn
            label="There was an issue fetching notifications. Tap here to try again."
            onPress={onPressRetryLoadMore}
          />
        )
      }
      return <FeedItem item={item} />
    },
    [onPressRetryLoadMore],
  )

  const FeedFooter = React.useCallback(
    () =>
      view.isLoading ? (
        <View style={styles.feedFooter}>
          <ActivityIndicator />
        </View>
      ) : (
        <View />
      ),
    [view],
  )

  return (
    <View style={s.hContentRegion}>
      <CenteredView>
        {view.isLoading && !data && <NotificationFeedLoadingPlaceholder />}
        {view.hasError && (
          <ErrorMessage
            message={view.error}
            onPressTryAgain={onPressTryAgain}
          />
        )}
      </CenteredView>
      {data && (
        <FlatList
          ref={scrollElRef}
          data={data}
          keyExtractor={item => item._reactKey}
          renderItem={renderItem}
          ListFooterComponent={FeedFooter}
          refreshControl={
            <RefreshControl
              refreshing={view.isRefreshing}
              onRefresh={onRefresh}
              tintColor={pal.colors.text}
              titleColor={pal.colors.text}
            />
          }
          onEndReached={onEndReached}
          onEndReachedThreshold={0.6}
          onScroll={onScroll}
          contentContainerStyle={s.contentContainer}
        />
      )}
    </View>
  )
})

const styles = StyleSheet.create({
  feedFooter: {paddingTop: 20},
  emptyState: {paddingVertical: 40},
})