about summary refs log tree commit diff
path: root/src/view/screens/Feeds.tsx
blob: c2ec9208f4985149c2a2d5ca8df5b16178a9ecd9 (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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import React from 'react'
import {ActivityIndicator, StyleSheet, RefreshControl, View} from 'react-native'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {FontAwesomeIconStyle} from '@fortawesome/react-native-fontawesome'
import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {ViewHeader} from 'view/com/util/ViewHeader'
import {FAB} from 'view/com/util/fab/FAB'
import {Link} from 'view/com/util/Link'
import {NativeStackScreenProps, FeedsTabNavigatorParams} from 'lib/routes/types'
import {observer} from 'mobx-react-lite'
import {usePalette} from 'lib/hooks/usePalette'
import {useStores} from 'state/index'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {ComposeIcon2, CogIcon} from 'lib/icons'
import {s} from 'lib/styles'
import {SearchInput} from 'view/com/util/forms/SearchInput'
import {UserAvatar} from 'view/com/util/UserAvatar'
import {
  LoadingPlaceholder,
  FeedFeedLoadingPlaceholder,
} from 'view/com/util/LoadingPlaceholder'
import {ErrorMessage} from 'view/com/util/error/ErrorMessage'
import debounce from 'lodash.debounce'
import {Text} from 'view/com/util/text/Text'
import {MyFeedsItem} from 'state/models/ui/my-feeds'
import {FeedSourceModel} from 'state/models/content/feed-source'
import {FlatList} from 'view/com/util/Views'
import {useFocusEffect} from '@react-navigation/native'
import {FeedSourceCard} from 'view/com/feeds/FeedSourceCard'
import {Trans, msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useSetMinimalShellMode} from '#/state/shell'

type Props = NativeStackScreenProps<FeedsTabNavigatorParams, 'Feeds'>
export const FeedsScreen = withAuthRequired(
  observer<Props>(function FeedsScreenImpl({}: Props) {
    const pal = usePalette('default')
    const store = useStores()
    const {_} = useLingui()
    const setMinimalShellMode = useSetMinimalShellMode()
    const {isMobile, isTabletOrDesktop} = useWebMediaQueries()
    const myFeeds = store.me.myFeeds
    const [query, setQuery] = React.useState<string>('')
    const debouncedSearchFeeds = React.useMemo(
      () => debounce(q => myFeeds.discovery.search(q), 500), // debounce for 500ms
      [myFeeds],
    )

    useFocusEffect(
      React.useCallback(() => {
        setMinimalShellMode(false)
        myFeeds.setup()

        const softResetSub = store.onScreenSoftReset(() => myFeeds.refresh())
        return () => {
          softResetSub.remove()
        }
      }, [store, myFeeds, setMinimalShellMode]),
    )
    React.useEffect(() => {
      // watch for changes to saved/pinned feeds
      return myFeeds.registerListeners()
    }, [myFeeds])

    const onPressCompose = React.useCallback(() => {
      store.shell.openComposer({})
    }, [store])
    const onChangeQuery = React.useCallback(
      (text: string) => {
        setQuery(text)
        if (text.length > 1) {
          debouncedSearchFeeds(text)
        } else {
          myFeeds.discovery.refresh()
        }
      },
      [debouncedSearchFeeds, myFeeds.discovery],
    )
    const onPressCancelSearch = React.useCallback(() => {
      setQuery('')
      myFeeds.discovery.refresh()
    }, [myFeeds])
    const onSubmitQuery = React.useCallback(() => {
      debouncedSearchFeeds(query)
      debouncedSearchFeeds.flush()
    }, [debouncedSearchFeeds, query])

    const renderHeaderBtn = React.useCallback(() => {
      return (
        <Link
          href="/settings/saved-feeds"
          hitSlop={10}
          accessibilityRole="button"
          accessibilityLabel={_(msg`Edit Saved Feeds`)}
          accessibilityHint="Opens screen to edit Saved Feeds">
          <CogIcon size={22} strokeWidth={2} style={pal.textLight} />
        </Link>
      )
    }, [pal, _])

    const onRefresh = React.useCallback(() => {
      myFeeds.refresh()
    }, [myFeeds])

    const renderItem = React.useCallback(
      ({item}: {item: MyFeedsItem}) => {
        if (item.type === 'discover-feeds-loading') {
          return <FeedFeedLoadingPlaceholder />
        } else if (item.type === 'spinner') {
          return (
            <View style={s.p10}>
              <ActivityIndicator />
            </View>
          )
        } else if (item.type === 'error') {
          return <ErrorMessage message={item.error} />
        } else if (item.type === 'saved-feeds-header') {
          if (!isMobile) {
            return (
              <View
                style={[
                  pal.view,
                  styles.header,
                  pal.border,
                  {
                    borderBottomWidth: 1,
                  },
                ]}>
                <Text type="title-lg" style={[pal.text, s.bold]}>
                  <Trans>My Feeds</Trans>
                </Text>
                <Link
                  href="/settings/saved-feeds"
                  accessibilityLabel={_(msg`Edit My Feeds`)}
                  accessibilityHint="">
                  <CogIcon strokeWidth={1.5} style={pal.icon} size={28} />
                </Link>
              </View>
            )
          }
          return <View />
        } else if (item.type === 'saved-feeds-loading') {
          return (
            <>
              {Array.from(Array(item.numItems)).map((_i, i) => (
                <SavedFeedLoadingPlaceholder key={`placeholder-${i}`} />
              ))}
            </>
          )
        } else if (item.type === 'saved-feed') {
          return <SavedFeed feed={item.feed} />
        } else if (item.type === 'discover-feeds-header') {
          return (
            <>
              <View
                style={[
                  pal.view,
                  styles.header,
                  {
                    marginTop: 16,
                    paddingLeft: isMobile ? 12 : undefined,
                    paddingRight: 10,
                    paddingBottom: isMobile ? 6 : undefined,
                  },
                ]}>
                <Text type="title-lg" style={[pal.text, s.bold]}>
                  <Trans>Discover new feeds</Trans>
                </Text>
                {!isMobile && (
                  <SearchInput
                    query={query}
                    onChangeQuery={onChangeQuery}
                    onPressCancelSearch={onPressCancelSearch}
                    onSubmitQuery={onSubmitQuery}
                    style={{flex: 1, maxWidth: 250}}
                  />
                )}
              </View>
              {isMobile && (
                <View style={{paddingHorizontal: 8, paddingBottom: 10}}>
                  <SearchInput
                    query={query}
                    onChangeQuery={onChangeQuery}
                    onPressCancelSearch={onPressCancelSearch}
                    onSubmitQuery={onSubmitQuery}
                  />
                </View>
              )}
            </>
          )
        } else if (item.type === 'discover-feed') {
          return (
            <FeedSourceCard
              item={item.feed}
              showSaveBtn
              showDescription
              showLikes
            />
          )
        } else if (item.type === 'discover-feeds-no-results') {
          return (
            <View
              style={{
                paddingHorizontal: 16,
                paddingTop: 10,
                paddingBottom: '150%',
              }}>
              <Text type="lg" style={pal.textLight}>
                <Trans>No results found for "{query}"</Trans>
              </Text>
            </View>
          )
        }
        return null
      },
      [
        isMobile,
        pal,
        query,
        onChangeQuery,
        onPressCancelSearch,
        onSubmitQuery,
        _,
      ],
    )

    return (
      <View style={[pal.view, styles.container]}>
        {isMobile && (
          <ViewHeader
            title="Feeds"
            canGoBack={false}
            renderButton={renderHeaderBtn}
            showBorder
          />
        )}

        <FlatList
          style={[!isTabletOrDesktop && s.flex1, styles.list]}
          data={myFeeds.items}
          keyExtractor={item => item._reactKey}
          contentContainerStyle={styles.contentContainer}
          refreshControl={
            <RefreshControl
              refreshing={myFeeds.isRefreshing}
              onRefresh={onRefresh}
              tintColor={pal.colors.text}
              titleColor={pal.colors.text}
            />
          }
          renderItem={renderItem}
          initialNumToRender={10}
          onEndReached={() => myFeeds.loadMore()}
          extraData={myFeeds.isLoading}
          // @ts-ignore our .web version only -prf
          desktopFixedHeight
        />
        <FAB
          testID="composeFAB"
          onPress={onPressCompose}
          icon={<ComposeIcon2 strokeWidth={1.5} size={29} style={s.white} />}
          accessibilityRole="button"
          accessibilityLabel={_(msg`New post`)}
          accessibilityHint=""
        />
      </View>
    )
  }),
)

function SavedFeed({feed}: {feed: FeedSourceModel}) {
  const pal = usePalette('default')
  const {isMobile} = useWebMediaQueries()
  return (
    <Link
      testID={`saved-feed-${feed.displayName}`}
      href={feed.href}
      style={[pal.border, styles.savedFeed, isMobile && styles.savedFeedMobile]}
      hoverStyle={pal.viewLight}
      accessibilityLabel={feed.displayName}
      accessibilityHint=""
      asAnchor
      anchorNoUnderline>
      {feed.error ? (
        <View
          style={{width: 28, flexDirection: 'row', justifyContent: 'center'}}>
          <FontAwesomeIcon
            icon="exclamation-circle"
            color={pal.colors.textLight}
          />
        </View>
      ) : (
        <UserAvatar type="algo" size={28} avatar={feed.avatar} />
      )}
      <View
        style={{flex: 1, flexDirection: 'row', gap: 8, alignItems: 'center'}}>
        <Text type="lg-medium" style={pal.text} numberOfLines={1}>
          {feed.displayName}
        </Text>
        {feed.error ? (
          <View style={[styles.offlineSlug, pal.borderDark]}>
            <Text type="xs" style={pal.textLight}>
              <Trans>Feed offline</Trans>
            </Text>
          </View>
        ) : null}
      </View>
      {isMobile && (
        <FontAwesomeIcon
          icon="chevron-right"
          size={14}
          style={pal.textLight as FontAwesomeIconStyle}
        />
      )}
    </Link>
  )
}

function SavedFeedLoadingPlaceholder() {
  const pal = usePalette('default')
  const {isMobile} = useWebMediaQueries()
  return (
    <View
      style={[
        pal.border,
        styles.savedFeed,
        isMobile && styles.savedFeedMobile,
      ]}>
      <LoadingPlaceholder width={28} height={28} style={{borderRadius: 4}} />
      <LoadingPlaceholder width={140} height={12} />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  list: {
    height: '100%',
  },
  contentContainer: {
    paddingBottom: 100,
  },

  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 16,
    paddingHorizontal: 16,
    paddingVertical: 12,
  },

  savedFeed: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingVertical: 14,
    gap: 12,
    borderBottomWidth: 1,
  },
  savedFeedMobile: {
    paddingVertical: 10,
  },
  offlineSlug: {
    borderWidth: 1,
    borderRadius: 4,
    paddingHorizontal: 4,
    paddingVertical: 2,
  },
})