Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304import {useCallback, useMemo, useState} from 'react'import { Dimensions, type GestureResponderEvent, type StyleProp, View, type ViewStyle,} from 'react-native'import {type AppBskyGraphDefs} from '@atproto/api'import {msg} from '@lingui/core/macro'import {useLingui} from '@lingui/react'import {Trans} from '@lingui/react/macro'
import {cleanError} from '#/lib/strings/errors'import {logger} from '#/logger'import {useModerationOpts} from '#/state/preferences/moderation-opts'import {useListMembersQuery} from '#/state/queries/list-members'import {useSession} from '#/state/session'import {ErrorMessage} from '#/view/com/util/error/ErrorMessage'import {List, type ListRef} from '#/view/com/util/List'import {ProfileCardFeedLoadingPlaceholder} from '#/view/com/util/LoadingPlaceholder'import {LoadMoreRetryBtn} from '#/view/com/util/LoadMoreRetryBtn'import {atoms as a, useTheme} from '#/alf'import {Button, ButtonText} from '#/components/Button'import {useDialogControl} from '#/components/Dialog'import {UserAddRemoveListsDialog} from '#/components/dialogs/lists/UserAddRemoveListsDialog'import {ListFooter} from '#/components/Lists'import * as ProfileCard from '#/components/ProfileCard'import type * as bsky from '#/types/bsky'
const LOADING_ITEM = {kind: 'loading', _reactKey: '__loading__'} as constconst EMPTY_ITEM = {kind: 'empty', _reactKey: '__empty__'} as constconst ERROR_ITEM = {kind: 'error', _reactKey: '__error__'} as constconst LOAD_MORE_ERROR_ITEM = { kind: 'load_more_error', _reactKey: '__load_more_error__',} as const
type Item = | typeof LOADING_ITEM | typeof EMPTY_ITEM | typeof ERROR_ITEM | typeof LOAD_MORE_ERROR_ITEM | { kind: 'list_item' listItem: AppBskyGraphDefs.ListItemView }
export function ListMembers({ list, style, scrollElRef, onScrolledDownChange, onPressTryAgain, renderHeader, renderEmptyState, testID, headerOffset = 0, desktopFixedHeightOffset,}: { list: string style?: StyleProp<ViewStyle> scrollElRef?: ListRef onScrolledDownChange: (isScrolledDown: boolean) => void onPressTryAgain?: () => void renderHeader: () => React.ReactElement renderEmptyState: () => React.ReactElement testID?: string headerOffset?: number desktopFixedHeightOffset?: number}) { const t = useTheme() const {_} = useLingui() const [isRefreshing, setIsRefreshing] = useState(false) const {currentAccount} = useSession() const moderationOpts = useModerationOpts() const editListsDialogControl = useDialogControl() const [selectedProfile, setSelectedProfile] = useState< bsky.profile.AnyProfileView | undefined >()
const { data, isFetching, isFetched, isError, error, refetch, fetchNextPage, hasNextPage, isFetchingNextPage, } = useListMembersQuery(list) const isEmpty = !isFetching && !data?.pages[0].items.length const isOwner = currentAccount && data?.pages[0].list.creator.did === currentAccount.did
const items = useMemo(() => { const items: Item[] = [] if (isFetched) { if (isEmpty && isError) { items.push(ERROR_ITEM) } if (isEmpty) { items.push(EMPTY_ITEM) } else if (data) { for (const page of data.pages) { items.push( ...page.items.map(item => ({ kind: 'list_item' as const, listItem: item, })), ) } } if (!isEmpty && isError) { items.push(LOAD_MORE_ERROR_ITEM) } } else if (isFetching) { items.push(LOADING_ITEM) } return items }, [isFetched, isEmpty, isError, data, isFetching])
// events // =
const onRefresh = useCallback(async () => { setIsRefreshing(true) try { await refetch() } catch (err) { logger.error('Failed to refresh lists', {message: err}) } setIsRefreshing(false) }, [refetch, setIsRefreshing])
const onEndReached = useCallback(async () => { if (isFetching || !hasNextPage || isError) return try { await fetchNextPage() } catch (err) { logger.error('Failed to load more lists', {message: err}) } }, [isFetching, hasNextPage, isError, fetchNextPage])
const onPressRetryLoadMore = useCallback(() => { void fetchNextPage() }, [fetchNextPage])
const onPressEditMembership = useCallback( (e: GestureResponderEvent, profile: bsky.profile.AnyProfileView) => { e.preventDefault() setSelectedProfile(profile) editListsDialogControl.open() }, [editListsDialogControl], )
// rendering // =
const renderItem = useCallback( ({item}: {item: Item}) => { switch (item.kind) { case 'empty': { return renderEmptyState() } case 'error': { return ( <ErrorMessage message={cleanError(error)} onPressTryAgain={onPressTryAgain} /> ) } case 'load_more_error': { return ( <LoadMoreRetryBtn label={_( msg`There was an issue fetching the list. Tap here to try again.`, )} onPress={onPressRetryLoadMore} /> ) } case 'loading': { return <ProfileCardFeedLoadingPlaceholder /> } case 'list_item': { const profile = item.listItem.subject if (!moderationOpts) return null
return ( <View style={[ a.py_md, a.px_xl, a.border_t, t.atoms.border_contrast_low, ]}> <ProfileCard.Link profile={profile}> <ProfileCard.Outer> <ProfileCard.Header> <ProfileCard.Avatar profile={profile} moderationOpts={moderationOpts} /> <ProfileCard.NameAndHandle profile={profile} moderationOpts={moderationOpts} /> {isOwner && ( <Button testID={`user-${profile.handle}-editBtn`} label={_(msg({message: 'Edit', context: 'action'}))} onPress={e => onPressEditMembership(e, profile)} size="small" color="secondary"> <ButtonText> <Trans context="action">Edit</Trans> </ButtonText> </Button> )} </ProfileCard.Header>
<ProfileCard.Labels profile={profile} moderationOpts={moderationOpts} />
<ProfileCard.Description profile={profile} /> </ProfileCard.Outer> </ProfileCard.Link> </View> ) } } }, [ renderEmptyState, error, onPressTryAgain, onPressRetryLoadMore, moderationOpts, isOwner, onPressEditMembership, _, t, ], )
const renderFooter = useCallback(() => { if (isEmpty) return null return ( <ListFooter hasNextPage={hasNextPage} error={cleanError(error)} isFetchingNextPage={isFetchingNextPage} onRetry={fetchNextPage} height={180 + headerOffset} /> ) }, [ hasNextPage, error, isFetchingNextPage, fetchNextPage, isEmpty, headerOffset, ])
return ( <View testID={testID} style={style}> <List testID={testID ? `${testID}-flatlist` : undefined} ref={scrollElRef} data={items} keyExtractor={(item: Item) => item.kind === 'list_item' ? item.listItem.subject.did : item._reactKey } renderItem={renderItem} ListHeaderComponent={!isEmpty ? renderHeader : undefined} ListFooterComponent={renderFooter} refreshing={isRefreshing} onRefresh={() => void onRefresh()} headerOffset={headerOffset} contentContainerStyle={{ minHeight: Dimensions.get('window').height * 1.5, }} onScrolledDownChange={onScrolledDownChange} onEndReached={() => void onEndReached()} onEndReachedThreshold={0.6} removeClippedSubviews={true} desktopFixedHeight={desktopFixedHeightOffset || true} />
<UserAddRemoveListsDialog control={editListsDialogControl} profile={selectedProfile} /> </View> )}