about summary refs log tree commit diff
path: root/src/view/com/discover/SuggestedFollows.tsx
blob: d2afc4b3366ab3f9101f2fc94c1417a751176d33 (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
import React, {useEffect, useState} from 'react'
import {
  ActivityIndicator,
  FlatList,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {observer} from 'mobx-react-lite'
import _omit from 'lodash.omit'
import {ErrorScreen} from '../util/error/ErrorScreen'
import {Link} from '../util/Link'
import {Text} from '../util/text/Text'
import {UserAvatar} from '../util/UserAvatar'
import * as Toast from '../util/Toast'
import {useStores} from '../../../state'
import * as apilib from '../../../state/lib/api'
import {
  SuggestedActorsViewModel,
  SuggestedActor,
} from '../../../state/models/suggested-actors-view'
import {s, gradients} from '../../lib/styles'
import {usePalette} from '../../lib/hooks/usePalette'

export const SuggestedFollows = observer(
  ({
    onNoSuggestions,
    asLinks,
  }: {
    onNoSuggestions?: () => void
    asLinks?: boolean
  }) => {
    const pal = usePalette('default')
    const store = useStores()
    const [follows, setFollows] = useState<Record<string, string>>({})

    // Using default import (React.use...) instead of named import (use...) to be able to mock store's data in jest environment
    const view = React.useMemo<SuggestedActorsViewModel>(
      () => new SuggestedActorsViewModel(store),
      [store],
    )

    useEffect(() => {
      view
        .setup()
        .catch((err: any) =>
          store.log.error('Failed to fetch suggestions', err),
        )
    }, [view, store.log])

    useEffect(() => {
      if (!view.isLoading && !view.hasError && !view.hasContent) {
        onNoSuggestions?.()
      }
    }, [view, view.isLoading, view.hasError, view.hasContent, onNoSuggestions])

    const onPressTryAgain = () =>
      view
        .setup()
        .catch((err: any) =>
          store.log.error('Failed to fetch suggestions', err),
        )

    const onPressFollow = async (item: SuggestedActor) => {
      try {
        const res = await apilib.follow(store, item.did, item.declaration.cid)
        setFollows({[item.did]: res.uri, ...follows})
      } catch (e: any) {
        store.log.error('Failed fo create follow', e)
        Toast.show('An issue occurred, please try again.')
      }
    }
    const onPressUnfollow = async (item: SuggestedActor) => {
      try {
        await apilib.unfollow(store, follows[item.did])
        setFollows(_omit(follows, [item.did]))
      } catch (e: any) {
        store.log.error('Failed fo delete follow', e)
        Toast.show('An issue occurred, please try again.')
      }
    }

    const renderItem = ({item}: {item: SuggestedActor}) => {
      if (asLinks) {
        return (
          <Link
            href={`/profile/${item.handle}`}
            title={item.displayName || item.handle}>
            <User
              item={item}
              follow={follows[item.did]}
              onPressFollow={onPressFollow}
              onPressUnfollow={onPressUnfollow}
            />
          </Link>
        )
      }
      return (
        <User
          item={item}
          follow={follows[item.did]}
          onPressFollow={onPressFollow}
          onPressUnfollow={onPressUnfollow}
        />
      )
    }
    return (
      <View style={styles.container}>
        {view.isLoading ? (
          <View>
            <ActivityIndicator />
          </View>
        ) : view.hasError ? (
          <ErrorScreen
            title="Failed to load suggestions"
            message="There was an error while trying to load suggested follows."
            details={view.error}
            onPressTryAgain={onPressTryAgain}
          />
        ) : view.isEmpty ? (
          <View />
        ) : (
          <View style={[styles.suggestionsContainer, pal.view]}>
            <FlatList
              data={view.suggestions}
              keyExtractor={item => item._reactKey}
              renderItem={renderItem}
              style={s.flex1}
              contentContainerStyle={s.contentContainer}
            />
          </View>
        )}
      </View>
    )
  },
)

const User = ({
  item,
  follow,
  onPressFollow,
  onPressUnfollow,
}: {
  item: SuggestedActor
  follow: string | undefined
  onPressFollow: (item: SuggestedActor) => void
  onPressUnfollow: (item: SuggestedActor) => void
}) => {
  const pal = usePalette('default')
  return (
    <View style={[styles.actor, pal.view, pal.border]}>
      <View style={styles.actorMeta}>
        <View style={styles.actorAvi}>
          <UserAvatar
            size={40}
            displayName={item.displayName}
            handle={item.handle}
            avatar={item.avatar}
          />
        </View>
        <View style={styles.actorContent}>
          <Text type="title-sm" style={pal.text} numberOfLines={1}>
            {item.displayName || item.handle}
          </Text>
          <Text style={pal.textLight} numberOfLines={1}>
            @{item.handle}
          </Text>
        </View>
        <View style={styles.actorBtn}>
          {follow ? (
            <TouchableOpacity onPress={() => onPressUnfollow(item)}>
              <View style={[styles.btn, styles.secondaryBtn, pal.btn]}>
                <Text type="button" style={pal.text}>
                  Unfollow
                </Text>
              </View>
            </TouchableOpacity>
          ) : (
            <TouchableOpacity onPress={() => onPressFollow(item)}>
              <LinearGradient
                colors={[gradients.blueLight.start, gradients.blueLight.end]}
                start={{x: 0, y: 0}}
                end={{x: 1, y: 1}}
                style={[styles.btn, styles.gradientBtn]}>
                <FontAwesomeIcon
                  icon="plus"
                  style={[s.white, s.mr5]}
                  size={15}
                />
                <Text style={[s.white, s.fw600, s.f15]}>Follow</Text>
              </LinearGradient>
            </TouchableOpacity>
          )}
        </View>
      </View>
      {item.description ? (
        <View style={styles.actorDetails}>
          <Text style={pal.text} numberOfLines={4}>
            {item.description}
          </Text>
        </View>
      ) : undefined}
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },

  suggestionsContainer: {
    flex: 1,
  },

  actor: {
    borderTopWidth: 1,
  },
  actorMeta: {
    flexDirection: 'row',
  },
  actorAvi: {
    width: 60,
    paddingLeft: 10,
    paddingTop: 10,
    paddingBottom: 10,
  },
  actorContent: {
    flex: 1,
    paddingRight: 10,
    paddingTop: 10,
  },
  actorBtn: {
    paddingRight: 10,
    paddingTop: 10,
  },
  actorDetails: {
    paddingLeft: 60,
    paddingRight: 10,
    paddingBottom: 10,
  },

  gradientBtn: {
    paddingHorizontal: 24,
    paddingVertical: 6,
  },
  secondaryBtn: {
    paddingHorizontal: 14,
  },
  btn: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 7,
    borderRadius: 50,
    marginLeft: 6,
  },
})