about summary refs log tree commit diff
path: root/src/view/com/feeds/ProfileFeedgens.tsx
diff options
context:
space:
mode:
authorPaul Frazee <pfrazee@gmail.com>2023-11-13 14:46:19 -0800
committerGitHub <noreply@github.com>2023-11-13 14:46:19 -0800
commit9fca7b3af6114d28e13f475395c8911c55b33cb1 (patch)
tree1cf22e7dfe3d4778d8eaf62b66c6d8ba3ef8c227 /src/view/com/feeds/ProfileFeedgens.tsx
parentb04748e703cede419a027f6bbb3c8180ed10eb1f (diff)
downloadvoidsky-9fca7b3af6114d28e13f475395c8911c55b33cb1.tar.zst
Add feedgens tab to profile (#1889)
Diffstat (limited to 'src/view/com/feeds/ProfileFeedgens.tsx')
-rw-r--r--src/view/com/feeds/ProfileFeedgens.tsx199
1 files changed, 199 insertions, 0 deletions
diff --git a/src/view/com/feeds/ProfileFeedgens.tsx b/src/view/com/feeds/ProfileFeedgens.tsx
new file mode 100644
index 000000000..2cc688c50
--- /dev/null
+++ b/src/view/com/feeds/ProfileFeedgens.tsx
@@ -0,0 +1,199 @@
+import React, {MutableRefObject} from 'react'
+import {
+  ActivityIndicator,
+  Dimensions,
+  RefreshControl,
+  StyleProp,
+  StyleSheet,
+  View,
+  ViewStyle,
+} from 'react-native'
+import {FlatList} from '../util/Views'
+import {FeedSourceCardLoaded} from './FeedSourceCard'
+import {ErrorMessage} from '../util/error/ErrorMessage'
+import {LoadMoreRetryBtn} from '../util/LoadMoreRetryBtn'
+import {Text} from '../util/text/Text'
+import {usePalette} from 'lib/hooks/usePalette'
+import {useProfileFeedgensQuery} from '#/state/queries/profile-feedgens'
+import {OnScrollHandler} from '#/lib/hooks/useOnMainScroll'
+import {logger} from '#/logger'
+import {Trans} from '@lingui/macro'
+import {cleanError} from '#/lib/strings/errors'
+import {useAnimatedScrollHandler} from 'react-native-reanimated'
+import {useTheme} from '#/lib/ThemeContext'
+import {usePreferencesQuery} from '#/state/queries/preferences'
+import {hydrateFeedGenerator} from '#/state/queries/feed'
+
+const LOADING = {_reactKey: '__loading__'}
+const EMPTY = {_reactKey: '__empty__'}
+const ERROR_ITEM = {_reactKey: '__error__'}
+const LOAD_MORE_ERROR_ITEM = {_reactKey: '__load_more_error__'}
+
+export function ProfileFeedgens({
+  did,
+  scrollElRef,
+  onScroll,
+  scrollEventThrottle,
+  headerOffset,
+  style,
+  testID,
+}: {
+  did: string
+  scrollElRef?: MutableRefObject<FlatList<any> | null>
+  onScroll?: OnScrollHandler
+  scrollEventThrottle?: number
+  headerOffset: number
+  style?: StyleProp<ViewStyle>
+  testID?: string
+}) {
+  const pal = usePalette('default')
+  const theme = useTheme()
+  const [isPTRing, setIsPTRing] = React.useState(false)
+  const {
+    data,
+    isFetching,
+    isFetched,
+    hasNextPage,
+    fetchNextPage,
+    isError,
+    error,
+    refetch,
+  } = useProfileFeedgensQuery(did)
+  const isEmpty = !isFetching && !data?.pages[0]?.feeds.length
+  const {data: preferences} = usePreferencesQuery()
+
+  const items = React.useMemo(() => {
+    let items: any[] = []
+    if (isError && isEmpty) {
+      items = items.concat([ERROR_ITEM])
+    }
+    if (!isFetched && isFetching) {
+      items = items.concat([LOADING])
+    } else if (isEmpty) {
+      items = items.concat([EMPTY])
+    } else if (data?.pages) {
+      for (const page of data?.pages) {
+        items = items.concat(page.feeds.map(feed => hydrateFeedGenerator(feed)))
+      }
+    }
+    if (isError && !isEmpty) {
+      items = items.concat([LOAD_MORE_ERROR_ITEM])
+    }
+    return items
+  }, [isError, isEmpty, isFetched, isFetching, data])
+
+  // events
+  // =
+
+  const onRefresh = React.useCallback(async () => {
+    setIsPTRing(true)
+    try {
+      await refetch()
+    } catch (err) {
+      logger.error('Failed to refresh feeds', {error: err})
+    }
+    setIsPTRing(false)
+  }, [refetch, setIsPTRing])
+
+  const onEndReached = React.useCallback(async () => {
+    if (isFetching || !hasNextPage || isError) return
+
+    try {
+      await fetchNextPage()
+    } catch (err) {
+      logger.error('Failed to load more feeds', {error: err})
+    }
+  }, [isFetching, hasNextPage, isError, fetchNextPage])
+
+  const onPressRetryLoadMore = React.useCallback(() => {
+    fetchNextPage()
+  }, [fetchNextPage])
+
+  // rendering
+  // =
+
+  const renderItemInner = React.useCallback(
+    ({item}: {item: any}) => {
+      if (item === EMPTY) {
+        return (
+          <View
+            testID="listsEmpty"
+            style={[{padding: 18, borderTopWidth: 1}, pal.border]}>
+            <Text style={pal.textLight}>
+              <Trans>You have no lists.</Trans>
+            </Text>
+          </View>
+        )
+      } else if (item === ERROR_ITEM) {
+        return (
+          <ErrorMessage message={cleanError(error)} onPressTryAgain={refetch} />
+        )
+      } else if (item === LOAD_MORE_ERROR_ITEM) {
+        return (
+          <LoadMoreRetryBtn
+            label="There was an issue fetching your lists. Tap here to try again."
+            onPress={onPressRetryLoadMore}
+          />
+        )
+      } else if (item === LOADING) {
+        return (
+          <View style={{padding: 20}}>
+            <ActivityIndicator />
+          </View>
+        )
+      }
+      if (preferences) {
+        return (
+          <FeedSourceCardLoaded
+            feed={item}
+            preferences={preferences}
+            style={styles.item}
+          />
+        )
+      }
+      return null
+    },
+    [error, refetch, onPressRetryLoadMore, pal, preferences],
+  )
+
+  const scrollHandler = useAnimatedScrollHandler(onScroll || {})
+  return (
+    <View testID={testID} style={style}>
+      <FlatList
+        testID={testID ? `${testID}-flatlist` : undefined}
+        ref={scrollElRef}
+        data={items}
+        keyExtractor={(item: any) => item._reactKey}
+        renderItem={renderItemInner}
+        refreshControl={
+          <RefreshControl
+            refreshing={isPTRing}
+            onRefresh={onRefresh}
+            tintColor={pal.colors.text}
+            titleColor={pal.colors.text}
+            progressViewOffset={headerOffset}
+          />
+        }
+        contentContainerStyle={{
+          minHeight: Dimensions.get('window').height * 1.5,
+        }}
+        style={{paddingTop: headerOffset}}
+        onScroll={onScroll != null ? scrollHandler : undefined}
+        scrollEventThrottle={scrollEventThrottle}
+        indicatorStyle={theme.colorScheme === 'dark' ? 'white' : 'black'}
+        removeClippedSubviews={true}
+        contentOffset={{x: 0, y: headerOffset * -1}}
+        // @ts-ignore our .web version only -prf
+        desktopFixedHeight
+        onEndReached={onEndReached}
+      />
+    </View>
+  )
+}
+
+const styles = StyleSheet.create({
+  item: {
+    paddingHorizontal: 18,
+    paddingVertical: 4,
+  },
+})