Add foaf-based follow discovery

zio/stable
Paul Frazee 2023-03-17 18:01:53 -05:00
parent 6af2585f32
commit ff39b072f3
6 changed files with 335 additions and 130 deletions

View File

@ -4,6 +4,7 @@ import {useTheme, PaletteColorName, PaletteColor} from '../ThemeContext'
export interface UsePaletteValue { export interface UsePaletteValue {
colors: PaletteColor colors: PaletteColor
view: ViewStyle view: ViewStyle
viewLight: ViewStyle
btn: ViewStyle btn: ViewStyle
border: ViewStyle border: ViewStyle
borderDark: ViewStyle borderDark: ViewStyle
@ -20,6 +21,9 @@ export function usePalette(color: PaletteColorName): UsePaletteValue {
view: { view: {
backgroundColor: palette.background, backgroundColor: palette.background,
}, },
viewLight: {
backgroundColor: palette.backgroundLight,
},
btn: { btn: {
backgroundColor: palette.backgroundLight, backgroundColor: palette.backgroundLight,
}, },

View File

@ -0,0 +1,98 @@
import {AppBskyActorProfile, AppBskyActorRef} from '@atproto/api'
import {makeAutoObservable, runInAction} from 'mobx'
import sampleSize from 'lodash.samplesize'
import {bundleAsync} from 'lib/async/bundle'
import {RootStoreModel} from '../root-store'
export type RefWithInfoAndFollowers = AppBskyActorRef.WithInfo & {
followers: AppBskyActorProfile.View[]
}
export type ProfileViewFollows = AppBskyActorProfile.View & {
follows: AppBskyActorRef.WithInfo[]
}
export class FoafsModel {
isLoading = false
hasData = false
sources: string[] = []
foafs: Map<string, ProfileViewFollows> = new Map()
popular: RefWithInfoAndFollowers[] = []
constructor(public rootStore: RootStoreModel) {
makeAutoObservable(this)
}
fetch = bundleAsync(async () => {
try {
this.isLoading = true
await this.rootStore.me.follows.fetchIfNeeded()
// grab 10 of the users followed by the user
this.sources = sampleSize(
Object.keys(this.rootStore.me.follows.followDidToRecordMap),
10,
)
if (this.sources.length === 0) {
return
}
this.foafs.clear()
this.popular.length = 0
// fetch their profiles
const profiles = await this.rootStore.api.app.bsky.actor.getProfiles({
actors: this.sources,
})
// fetch their follows
const results = await Promise.allSettled(
this.sources.map(source =>
this.rootStore.api.app.bsky.graph.getFollows({user: source}),
),
)
// store the follows and construct a "most followed" set
const popular: RefWithInfoAndFollowers[] = []
for (let i = 0; i < results.length; i++) {
const res = results[i]
const profile = profiles.data.profiles[i]
const source = this.sources[i]
if (res.status === 'fulfilled' && profile) {
// filter out users already followed by the user or that *is* the user
res.value.data.follows = res.value.data.follows.filter(follow => {
return (
follow.did !== this.rootStore.me.did &&
!this.rootStore.me.follows.isFollowing(follow.did)
)
})
runInAction(() => {
this.foafs.set(source, {
...profile,
follows: res.value.data.follows,
})
})
for (const follow of res.value.data.follows) {
let item = popular.find(p => p.did === follow.did)
if (!item) {
item = {...follow, followers: []}
popular.push(item)
}
item.followers.push(profile)
}
}
}
popular.sort((a, b) => b.followers.length - a.followers.length)
runInAction(() => {
this.popular = popular.filter(p => p.followers.length > 1).slice(0, 20)
})
this.hasData = true
} catch (e) {
console.error('Failed to fetch FOAFs', e)
} finally {
runInAction(() => {
this.isLoading = false
})
}
})
}

View File

@ -1,116 +1,67 @@
import React from 'react' import React from 'react'
import {ActivityIndicator, StyleSheet, View} from 'react-native' import {StyleSheet, View} from 'react-native'
import {CenteredView, FlatList} from '../util/Views' import {AppBskyActorRef, AppBskyActorProfile} from '@atproto/api'
import {observer} from 'mobx-react-lite' import {RefWithInfoAndFollowers} from 'state/models/discovery/foafs'
import {ErrorScreen} from '../util/error/ErrorScreen'
import {ProfileCardWithFollowBtn} from '../profile/ProfileCard' import {ProfileCardWithFollowBtn} from '../profile/ProfileCard'
import {useStores} from 'state/index' import {Text} from '../util/text/Text'
import {
SuggestedActorsViewModel,
SuggestedActor,
} from 'state/models/suggested-actors-view'
import {s} from 'lib/styles'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
export const SuggestedFollows = observer( export const SuggestedFollows = ({
({onNoSuggestions}: {onNoSuggestions?: () => void}) => { title,
const pal = usePalette('default') suggestions,
const store = useStores() }: {
title: string
const view = React.useMemo<SuggestedActorsViewModel>( suggestions: (AppBskyActorRef.WithInfo | RefWithInfoAndFollowers)[]
() => new SuggestedActorsViewModel(store), }) => {
[store], const pal = usePalette('default')
) return (
<View style={[styles.container, pal.view]}>
React.useEffect(() => { <Text type="title" style={[styles.heading, pal.text]}>
view {title}
.loadMore() </Text>
.catch((err: any) => {suggestions.map(item => (
store.log.error('Failed to fetch suggestions', err), <View key={item.did} style={[styles.card, pal.view, pal.border]}>
) <ProfileCardWithFollowBtn
}, [view, store.log]) key={item.did}
did={item.did}
React.useEffect(() => { declarationCid={item.declaration.cid}
if (!view.isLoading && !view.hasError && !view.hasContent) { handle={item.handle}
onNoSuggestions?.() displayName={item.displayName}
} avatar={item.avatar}
}, [view, view.isLoading, view.hasError, view.hasContent, onNoSuggestions]) noBorder
description=""
const onRefresh = () => { followers={
view item.followers
.refresh() ? (item.followers as AppBskyActorProfile.View[])
.catch((err: any) => : undefined
store.log.error('Failed to fetch suggestions', err), }
) />
} </View>
const onEndReached = () => { ))}
view </View>
.loadMore() )
.catch(err => }
view?.rootStore.log.error('Failed to load more suggestions', err),
)
}
const renderItem = ({item}: {item: SuggestedActor}) => {
return (
<ProfileCardWithFollowBtn
key={item.did}
did={item.did}
declarationCid={item.declaration.cid}
handle={item.handle}
displayName={item.displayName}
avatar={item.avatar}
description={item.description}
/>
)
}
return (
<View style={styles.container}>
{view.hasError ? (
<CenteredView>
<ErrorScreen
title="Failed to load suggestions"
message="There was an error while trying to load suggested follows."
details={view.error}
onPressTryAgain={onRefresh}
/>
</CenteredView>
) : view.isEmpty ? (
<View />
) : (
<View style={[styles.suggestionsContainer, pal.view]}>
<FlatList
data={view.suggestions}
keyExtractor={item => item.did}
refreshing={view.isRefreshing}
onRefresh={onRefresh}
onEndReached={onEndReached}
renderItem={renderItem}
initialNumToRender={15}
ListFooterComponent={() => (
<View style={styles.footer}>
{view.isLoading && <ActivityIndicator />}
</View>
)}
contentContainerStyle={s.contentContainer}
/>
</View>
)}
</View>
)
},
)
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
height: '100%', paddingVertical: 10,
paddingHorizontal: 4,
}, },
suggestionsContainer: { heading: {
height: '100%', fontWeight: 'bold',
paddingHorizontal: 4,
paddingBottom: 8,
}, },
footer: {
height: 200, card: {
paddingTop: 20, borderRadius: 12,
marginBottom: 2,
borderWidth: 1,
},
loadMore: {
paddingLeft: 16,
paddingVertical: 12,
}, },
}) })

View File

@ -1,6 +1,7 @@
import React from 'react' import React from 'react'
import {StyleSheet, View} from 'react-native' import {StyleSheet, View} from 'react-native'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import {AppBskyActorProfile} from '@atproto/api'
import {Link} from '../util/Link' import {Link} from '../util/Link'
import {Text} from '../util/text/Text' import {Text} from '../util/text/Text'
import {UserAvatar} from '../util/UserAvatar' import {UserAvatar} from '../util/UserAvatar'
@ -16,6 +17,7 @@ export function ProfileCard({
description, description,
isFollowedBy, isFollowedBy,
noBorder, noBorder,
followers,
renderButton, renderButton,
}: { }: {
handle: string handle: string
@ -24,17 +26,13 @@ export function ProfileCard({
description?: string description?: string
isFollowedBy?: boolean isFollowedBy?: boolean
noBorder?: boolean noBorder?: boolean
followers?: AppBskyActorProfile.View[] | undefined
renderButton?: () => JSX.Element renderButton?: () => JSX.Element
}) { }) {
const pal = usePalette('default') const pal = usePalette('default')
return ( return (
<Link <Link
style={[ style={[styles.outer, pal.border, noBorder && styles.outerNoBorder]}
styles.outer,
pal.view,
pal.border,
noBorder && styles.outerNoBorder,
]}
href={`/profile/${handle}`} href={`/profile/${handle}`}
title={handle} title={handle}
noFeedback noFeedback
@ -73,6 +71,25 @@ export function ProfileCard({
</Text> </Text>
</View> </View>
) : undefined} ) : undefined}
{followers?.length ? (
<View style={styles.followedBy}>
<Text
type="sm"
style={[styles.followsByDesc, pal.textLight]}
numberOfLines={2}
lineHeight={1.2}>
Followed by{' '}
{followers.map(f => f.displayName || f.handle).join(', ')}
</Text>
{followers.slice(0, 3).map(f => (
<View key={f.did} style={styles.followedByAviContainer}>
<View style={[styles.followedByAvi, pal.view]}>
<UserAvatar avatar={f.avatar} size={32} />
</View>
</View>
))}
</View>
) : undefined}
</Link> </Link>
) )
} }
@ -86,6 +103,8 @@ export const ProfileCardWithFollowBtn = observer(
avatar, avatar,
description, description,
isFollowedBy, isFollowedBy,
noBorder,
followers,
}: { }: {
did: string did: string
declarationCid: string declarationCid: string
@ -94,6 +113,8 @@ export const ProfileCardWithFollowBtn = observer(
avatar?: string avatar?: string
description?: string description?: string
isFollowedBy?: boolean isFollowedBy?: boolean
noBorder?: boolean
followers?: AppBskyActorProfile.View[] | undefined
}) => { }) => {
const store = useStores() const store = useStores()
const isMe = store.me.handle === handle const isMe = store.me.handle === handle
@ -105,6 +126,8 @@ export const ProfileCardWithFollowBtn = observer(
avatar={avatar} avatar={avatar}
description={description} description={description}
isFollowedBy={isFollowedBy} isFollowedBy={isFollowedBy}
noBorder={noBorder}
followers={followers}
renderButton={ renderButton={
isMe isMe
? undefined ? undefined
@ -128,8 +151,8 @@ const styles = StyleSheet.create({
alignItems: 'center', alignItems: 'center',
}, },
layoutAvi: { layoutAvi: {
width: 60, width: 54,
paddingLeft: 10, paddingLeft: 4,
paddingTop: 8, paddingTop: 8,
paddingBottom: 10, paddingBottom: 10,
}, },
@ -164,4 +187,27 @@ const styles = StyleSheet.create({
marginLeft: 6, marginLeft: 6,
paddingHorizontal: 14, paddingHorizontal: 14,
}, },
followedBy: {
flexDirection: 'row',
alignItems: 'flex-start',
paddingLeft: 54,
paddingRight: 20,
marginBottom: 10,
marginTop: -6,
},
followedByAviContainer: {
width: 24,
height: 36,
},
followedByAvi: {
width: 36,
height: 36,
borderRadius: 18,
padding: 2,
},
followsByDesc: {
flex: 1,
paddingRight: 10,
},
}) })

View File

@ -128,6 +128,46 @@ export function NotificationFeedLoadingPlaceholder() {
) )
} }
export function ProfileCardLoadingPlaceholder({
style,
}: {
style?: StyleProp<ViewStyle>
}) {
const pal = usePalette('default')
return (
<View style={[styles.profileCard, pal.view, style]}>
<LoadingPlaceholder
width={40}
height={40}
style={styles.profileCardAvi}
/>
<View>
<LoadingPlaceholder width={140} height={8} style={[s.mb5]} />
<LoadingPlaceholder width={120} height={8} style={[s.mb10]} />
<LoadingPlaceholder width={220} height={8} style={[s.mb5]} />
</View>
</View>
)
}
export function ProfileCardFeedLoadingPlaceholder() {
return (
<>
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
<ProfileCardLoadingPlaceholder />
</>
)
}
const styles = StyleSheet.create({ const styles = StyleSheet.create({
loadingPlaceholder: { loadingPlaceholder: {
borderRadius: 6, borderRadius: 6,
@ -147,6 +187,15 @@ const styles = StyleSheet.create({
paddingLeft: 46, paddingLeft: 46,
margin: 1, margin: 1,
}, },
profileCard: {
flexDirection: 'row',
padding: 10,
margin: 1,
},
profileCardAvi: {
borderRadius: 20,
marginRight: 10,
},
smallAvatar: { smallAvatar: {
borderRadius: 15, borderRadius: 15,
marginRight: 10, marginRight: 10,

View File

@ -1,6 +1,7 @@
import React from 'react' import React from 'react'
import { import {
Keyboard, Keyboard,
RefreshControl,
StyleSheet, StyleSheet,
TextInput, TextInput,
TouchableOpacity, TouchableOpacity,
@ -13,21 +14,23 @@ import {
FontAwesomeIconStyle, FontAwesomeIconStyle,
} from '@fortawesome/react-native-fontawesome' } from '@fortawesome/react-native-fontawesome'
import {withAuthRequired} from 'view/com/auth/withAuthRequired' import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {ScrollView} from '../com/util/Views' import {ScrollView} from 'view/com/util/Views'
import { import {
NativeStackScreenProps, NativeStackScreenProps,
SearchTabNavigatorParams, SearchTabNavigatorParams,
} from 'lib/routes/types' } from 'lib/routes/types'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import {UserAvatar} from '../com/util/UserAvatar' import {UserAvatar} from 'view/com/util/UserAvatar'
import {Text} from '../com/util/text/Text' import {Text} from 'view/com/util/text/Text'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import {UserAutocompleteViewModel} from 'state/models/user-autocomplete-view' import {UserAutocompleteViewModel} from 'state/models/user-autocomplete-view'
import {FoafsModel} from 'state/models/discovery/foafs'
import {s} from 'lib/styles' import {s} from 'lib/styles'
import {MagnifyingGlassIcon} from 'lib/icons' import {MagnifyingGlassIcon} from 'lib/icons'
import {WhoToFollow} from '../com/discover/WhoToFollow' import {WhoToFollow} from 'view/com/discover/WhoToFollow'
import {SuggestedPosts} from '../com/discover/SuggestedPosts' import {SuggestedFollows} from 'view/com/discover/SuggestedFollows'
import {ProfileCard} from '../com/profile/ProfileCard' import {ProfileCard} from 'view/com/profile/ProfileCard'
import {ProfileCardFeedLoadingPlaceholder} from 'view/com/util/LoadingPlaceholder'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {useTheme} from 'lib/ThemeContext' import {useTheme} from 'lib/ThemeContext'
import {useOnMainScroll} from 'lib/hooks/useOnMainScroll' import {useOnMainScroll} from 'lib/hooks/useOnMainScroll'
@ -53,6 +56,11 @@ export const SearchScreen = withAuthRequired(
() => new UserAutocompleteViewModel(store), () => new UserAutocompleteViewModel(store),
[store], [store],
) )
const foafsView = React.useMemo<FoafsModel>(
() => new FoafsModel(store),
[store],
)
const [refreshing, setRefreshing] = React.useState(false)
const onSoftReset = () => { const onSoftReset = () => {
scrollElRef.current?.scrollTo({x: 0, y: 0}) scrollElRef.current?.scrollTo({x: 0, y: 0})
@ -71,9 +79,12 @@ export const SearchScreen = withAuthRequired(
} }
store.shell.setMinimalShellMode(false) store.shell.setMinimalShellMode(false)
autocompleteView.setup() autocompleteView.setup()
if (!foafsView.hasData) {
foafsView.fetch()
}
return cleanup return cleanup
}, [store, autocompleteView, lastRenderTime, setRenderTime]), }, [store, autocompleteView, foafsView, lastRenderTime, setRenderTime]),
) )
const onPressMenu = () => { const onPressMenu = () => {
@ -98,15 +109,18 @@ export const SearchScreen = withAuthRequired(
autocompleteView.setActive(false) autocompleteView.setActive(false)
textInput.current?.blur() textInput.current?.blur()
} }
const onRefresh = React.useCallback(async () => {
setRefreshing(true)
try {
await foafsView.fetch()
} finally {
setRefreshing(false)
}
}, [foafsView, setRefreshing])
return ( return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}> <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<ScrollView <View style={[pal.view, styles.container]}>
ref={scrollElRef}
testID="searchScrollView"
style={[pal.view, styles.container]}
onScroll={onMainScroll}
scrollEventThrottle={100}>
<View style={[pal.view, pal.border, styles.header]}> <View style={[pal.view, pal.border, styles.header]}>
<TouchableOpacity <TouchableOpacity
testID="viewHeaderBackOrMenuBtn" testID="viewHeaderBackOrMenuBtn"
@ -180,14 +194,53 @@ export const SearchScreen = withAuthRequired(
</Text> </Text>
</View> </View>
) : ( ) : (
<ScrollView onScroll={Keyboard.dismiss}> <ScrollView
<WhoToFollow key={`wtf-${lastRenderTime}`} /> ref={scrollElRef}
<SuggestedPosts key={`sp-${lastRenderTime}`} /> testID="searchScrollView"
style={pal.view}
onScroll={onMainScroll}
scrollEventThrottle={100}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
}>
{foafsView.isLoading ? (
<ProfileCardFeedLoadingPlaceholder />
) : foafsView.sources.length ? (
<>
{foafsView.popular.length > 0 && (
<View style={styles.suggestions}>
<SuggestedFollows
title="In your network"
suggestions={foafsView.popular}
/>
</View>
)}
{foafsView.sources.map((source, i) => {
const item = foafsView.foafs.get(source)
if (!item || item.follows.length === 0) {
return <View key={`sf-${item?.did || i}`} />
}
return (
<View key={`sf-${item.did}`} style={styles.suggestions}>
<SuggestedFollows
title={`Followed by ${
item.displayName || item.handle
}`}
suggestions={item.follows.slice(0, 10)}
/>
</View>
)
})}
</>
) : (
<View style={pal.view}>
<WhoToFollow />
</View>
)}
<View style={s.footerSpacer} /> <View style={s.footerSpacer} />
</ScrollView> </ScrollView>
)} )}
<View style={s.footerSpacer} /> </View>
</ScrollView>
</TouchableWithoutFeedback> </TouchableWithoutFeedback>
) )
}), }),
@ -235,4 +288,8 @@ const styles = StyleSheet.create({
textAlign: 'center', textAlign: 'center',
paddingTop: 10, paddingTop: 10,
}, },
suggestions: {
marginBottom: 8,
},
}) })