Merge branch 'custom-algos' into main

zio/stable
Paul Frazee 2023-05-25 21:17:11 -05:00
commit 7b6948e617
85 changed files with 4593 additions and 1361 deletions

View File

@ -1,6 +1,10 @@
module.exports = { module.exports = {
root: true, root: true,
extends: ['@react-native-community', 'plugin:react-native-a11y/ios'], extends: [
'@react-native-community',
'plugin:react-native-a11y/ios',
'prettier',
],
parser: '@typescript-eslint/parser', parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'detox'], plugins: ['@typescript-eslint', 'detox'],
ignorePatterns: [ ignorePatterns: [

View File

@ -4,7 +4,7 @@
"slug": "bluesky", "slug": "bluesky",
"scheme": "bluesky", "scheme": "bluesky",
"owner": "blueskysocial", "owner": "blueskysocial",
"version": "1.28.0", "version": "1.29.0",
"orientation": "portrait", "orientation": "portrait",
"icon": "./assets/icon.png", "icon": "./assets/icon.png",
"userInterfaceStyle": "light", "userInterfaceStyle": "light",
@ -40,7 +40,7 @@
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"
}, },
"android": { "android": {
"versionCode": 14, "versionCode": 15,
"adaptiveIcon": { "adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png", "foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"

View File

@ -107,6 +107,8 @@ func serve(cctx *cli.Context) error {
// generic routes // generic routes
e.GET("/search", server.WebGeneric) e.GET("/search", server.WebGeneric)
e.GET("/search/feeds", server.WebGeneric)
e.GET("/feeds", server.WebGeneric)
e.GET("/notifications", server.WebGeneric) e.GET("/notifications", server.WebGeneric)
e.GET("/moderation", server.WebGeneric) e.GET("/moderation", server.WebGeneric)
e.GET("/moderation/mute-lists", server.WebGeneric) e.GET("/moderation/mute-lists", server.WebGeneric)
@ -114,6 +116,7 @@ func serve(cctx *cli.Context) error {
e.GET("/moderation/blocked-accounts", server.WebGeneric) e.GET("/moderation/blocked-accounts", server.WebGeneric)
e.GET("/settings", server.WebGeneric) e.GET("/settings", server.WebGeneric)
e.GET("/settings/app-passwords", server.WebGeneric) e.GET("/settings/app-passwords", server.WebGeneric)
e.GET("/settings/saved-feeds", server.WebGeneric)
e.GET("/sys/debug", server.WebGeneric) e.GET("/sys/debug", server.WebGeneric)
e.GET("/sys/log", server.WebGeneric) e.GET("/sys/log", server.WebGeneric)
e.GET("/support", server.WebGeneric) e.GET("/support", server.WebGeneric)
@ -127,6 +130,8 @@ func serve(cctx *cli.Context) error {
e.GET("/profile/:handle/follows", server.WebGeneric) e.GET("/profile/:handle/follows", server.WebGeneric)
e.GET("/profile/:handle/followers", server.WebGeneric) e.GET("/profile/:handle/followers", server.WebGeneric)
e.GET("/profile/:handle/lists/:rkey", server.WebGeneric) e.GET("/profile/:handle/lists/:rkey", server.WebGeneric)
e.GET("/profile/:handle/feed/:rkey", server.WebGeneric)
e.GET("/profile/:handle/feed/:rkey/liked-by", server.WebGeneric)
// post endpoints; only first populates info // post endpoints; only first populates info
e.GET("/profile/:handle/post/:rkey", server.WebPost) e.GET("/profile/:handle/post/:rkey", server.WebPost)

View File

@ -13,6 +13,7 @@ const ADMIN_PASSWORD = 'admin-pass'
const SECOND = 1000 const SECOND = 1000
const MINUTE = SECOND * 60 const MINUTE = SECOND * 60
const HOUR = MINUTE * 60 const HOUR = MINUTE * 60
const DAY = HOUR * 24
export interface TestUser { export interface TestUser {
email: string email: string
@ -66,6 +67,8 @@ export async function createServer(
adminPassword: ADMIN_PASSWORD, adminPassword: ADMIN_PASSWORD,
inviteRequired, inviteRequired,
didPlcUrl: plcUrl, didPlcUrl: plcUrl,
didCacheMaxTTL: DAY,
didCacheStaleTTL: HOUR,
jwtSecret: 'jwt-secret', jwtSecret: 'jwt-secret',
availableUserDomains: ['.test'], availableUserDomains: ['.test'],
appUrlPasswordReset: 'app://forgot-password', appUrlPasswordReset: 'app://forgot-password',

View File

@ -1,6 +1,6 @@
{ {
"name": "bsky.app", "name": "bsky.app",
"version": "1.28.0", "version": "1.29.0",
"private": true, "private": true,
"scripts": { "scripts": {
"postinstall": "patch-package", "postinstall": "patch-package",
@ -22,7 +22,7 @@
"e2e:run": "detox test --configuration ios.sim.debug --take-screenshots all" "e2e:run": "detox test --configuration ios.sim.debug --take-screenshots all"
}, },
"dependencies": { "dependencies": {
"@atproto/api": "0.3.3", "@atproto/api": "0.3.8",
"@bam.tech/react-native-image-resizer": "^3.0.4", "@bam.tech/react-native-image-resizer": "^3.0.4",
"@braintree/sanitize-url": "^6.0.2", "@braintree/sanitize-url": "^6.0.2",
"@expo/webpack-config": "^18.0.1", "@expo/webpack-config": "^18.0.1",
@ -111,6 +111,7 @@
"react-native": "0.71.7", "react-native": "0.71.7",
"react-native-appstate-hook": "^1.0.6", "react-native-appstate-hook": "^1.0.6",
"react-native-background-fetch": "^4.1.8", "react-native-background-fetch": "^4.1.8",
"react-native-draggable-flatlist": "^4.0.1",
"react-native-drawer-layout": "^3.2.0", "react-native-drawer-layout": "^3.2.0",
"react-native-fs": "^2.20.0", "react-native-fs": "^2.20.0",
"react-native-gesture-handler": "~2.9.0", "react-native-gesture-handler": "~2.9.0",
@ -140,7 +141,7 @@
"zod": "^3.20.2" "zod": "^3.20.2"
}, },
"devDependencies": { "devDependencies": {
"@atproto/pds": "^0.1.8", "@atproto/pds": "^0.1.10",
"@babel/core": "^7.20.0", "@babel/core": "^7.20.0",
"@babel/preset-env": "^7.20.0", "@babel/preset-env": "^7.20.0",
"@babel/runtime": "^7.20.0", "@babel/runtime": "^7.20.0",

View File

@ -14,6 +14,7 @@ import {createBottomTabNavigator} from '@react-navigation/bottom-tabs'
import { import {
HomeTabNavigatorParams, HomeTabNavigatorParams,
SearchTabNavigatorParams, SearchTabNavigatorParams,
FeedsTabNavigatorParams,
NotificationsTabNavigatorParams, NotificationsTabNavigatorParams,
FlatNavigatorParams, FlatNavigatorParams,
AllNavigatorParams, AllNavigatorParams,
@ -32,14 +33,18 @@ import {useStores} from './state'
import {HomeScreen} from './view/screens/Home' import {HomeScreen} from './view/screens/Home'
import {SearchScreen} from './view/screens/Search' import {SearchScreen} from './view/screens/Search'
import {FeedsScreen} from './view/screens/Feeds'
import {NotificationsScreen} from './view/screens/Notifications' import {NotificationsScreen} from './view/screens/Notifications'
import {ModerationScreen} from './view/screens/Moderation' import {ModerationScreen} from './view/screens/Moderation'
import {ModerationMuteListsScreen} from './view/screens/ModerationMuteLists' import {ModerationMuteListsScreen} from './view/screens/ModerationMuteLists'
import {DiscoverFeedsScreen} from 'view/screens/DiscoverFeeds'
import {NotFoundScreen} from './view/screens/NotFound' import {NotFoundScreen} from './view/screens/NotFound'
import {SettingsScreen} from './view/screens/Settings' import {SettingsScreen} from './view/screens/Settings'
import {ProfileScreen} from './view/screens/Profile' import {ProfileScreen} from './view/screens/Profile'
import {ProfileFollowersScreen} from './view/screens/ProfileFollowers' import {ProfileFollowersScreen} from './view/screens/ProfileFollowers'
import {ProfileFollowsScreen} from './view/screens/ProfileFollows' import {ProfileFollowsScreen} from './view/screens/ProfileFollows'
import {CustomFeedScreen} from './view/screens/CustomFeed'
import {CustomFeedLikedByScreen} from './view/screens/CustomFeedLikedBy'
import {ProfileListScreen} from './view/screens/ProfileList' import {ProfileListScreen} from './view/screens/ProfileList'
import {PostThreadScreen} from './view/screens/PostThread' import {PostThreadScreen} from './view/screens/PostThread'
import {PostLikedByScreen} from './view/screens/PostLikedBy' import {PostLikedByScreen} from './view/screens/PostLikedBy'
@ -54,6 +59,7 @@ import {CopyrightPolicyScreen} from './view/screens/CopyrightPolicy'
import {AppPasswords} from 'view/screens/AppPasswords' import {AppPasswords} from 'view/screens/AppPasswords'
import {ModerationMutedAccounts} from 'view/screens/ModerationMutedAccounts' import {ModerationMutedAccounts} from 'view/screens/ModerationMutedAccounts'
import {ModerationBlockedAccounts} from 'view/screens/ModerationBlockedAccounts' import {ModerationBlockedAccounts} from 'view/screens/ModerationBlockedAccounts'
import {SavedFeeds} from 'view/screens/SavedFeeds'
import {getRoutingInstrumentation} from 'lib/sentry' import {getRoutingInstrumentation} from 'lib/sentry'
import {bskyTitle} from 'lib/strings/headings' import {bskyTitle} from 'lib/strings/headings'
@ -61,6 +67,7 @@ const navigationRef = createNavigationContainerRef<AllNavigatorParams>()
const HomeTab = createNativeStackNavigator<HomeTabNavigatorParams>() const HomeTab = createNativeStackNavigator<HomeTabNavigatorParams>()
const SearchTab = createNativeStackNavigator<SearchTabNavigatorParams>() const SearchTab = createNativeStackNavigator<SearchTabNavigatorParams>()
const FeedsTab = createNativeStackNavigator<FeedsTabNavigatorParams>()
const NotificationsTab = const NotificationsTab =
createNativeStackNavigator<NotificationsTabNavigatorParams>() createNativeStackNavigator<NotificationsTabNavigatorParams>()
const MyProfileTab = createNativeStackNavigator<MyProfileTabNavigatorParams>() const MyProfileTab = createNativeStackNavigator<MyProfileTabNavigatorParams>()
@ -100,6 +107,11 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
component={ModerationBlockedAccounts} component={ModerationBlockedAccounts}
options={{title: title('Blocked Accounts')}} options={{title: title('Blocked Accounts')}}
/> />
<Stack.Screen
name="DiscoverFeeds"
component={DiscoverFeedsScreen}
options={{title: title('Discover Feeds')}}
/>
<Stack.Screen <Stack.Screen
name="Settings" name="Settings"
component={SettingsScreen} component={SettingsScreen}
@ -144,6 +156,16 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
component={PostRepostedByScreen} component={PostRepostedByScreen}
options={({route}) => ({title: title(`Post by @${route.params.name}`)})} options={({route}) => ({title: title(`Post by @${route.params.name}`)})}
/> />
<Stack.Screen
name="CustomFeed"
component={CustomFeedScreen}
options={{title: title('Feed')}}
/>
<Stack.Screen
name="CustomFeedLikedBy"
component={CustomFeedLikedByScreen}
options={{title: title('Liked by')}}
/>
<Stack.Screen <Stack.Screen
name="Debug" name="Debug"
component={DebugScreen} component={DebugScreen}
@ -184,6 +206,11 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
component={AppPasswords} component={AppPasswords}
options={{title: title('App Passwords')}} options={{title: title('App Passwords')}}
/> />
<Stack.Screen
name="SavedFeeds"
component={SavedFeeds}
options={{title: title('Edit My Feeds')}}
/>
</> </>
) )
} }
@ -201,11 +228,12 @@ function TabsNavigator() {
screenOptions={{headerShown: false}} screenOptions={{headerShown: false}}
tabBar={tabBar}> tabBar={tabBar}>
<Tab.Screen name="HomeTab" component={HomeTabNavigator} /> <Tab.Screen name="HomeTab" component={HomeTabNavigator} />
<Tab.Screen name="SearchTab" component={SearchTabNavigator} />
<Tab.Screen name="FeedsTab" component={FeedsTabNavigator} />
<Tab.Screen <Tab.Screen
name="NotificationsTab" name="NotificationsTab"
component={NotificationsTabNavigator} component={NotificationsTabNavigator}
/> />
<Tab.Screen name="SearchTab" component={SearchTabNavigator} />
<Tab.Screen name="MyProfileTab" component={MyProfileTabNavigator} /> <Tab.Screen name="MyProfileTab" component={MyProfileTabNavigator} />
</Tab.Navigator> </Tab.Navigator>
) )
@ -245,6 +273,23 @@ function SearchTabNavigator() {
) )
} }
function FeedsTabNavigator() {
const contentStyle = useColorSchemeStyle(styles.bgLight, styles.bgDark)
return (
<FeedsTab.Navigator
screenOptions={{
gestureEnabled: true,
fullScreenGestureEnabled: true,
headerShown: false,
animationDuration: 250,
contentStyle,
}}>
<FeedsTab.Screen name="Feeds" component={FeedsScreen} />
{commonScreens(FeedsTab as typeof HomeTab)}
</FeedsTab.Navigator>
)
}
function NotificationsTabNavigator() { function NotificationsTabNavigator() {
const contentStyle = useColorSchemeStyle(styles.bgLight, styles.bgDark) const contentStyle = useColorSchemeStyle(styles.bgLight, styles.bgDark)
return ( return (
@ -318,6 +363,11 @@ const FlatNavigator = observer(() => {
component={SearchScreen} component={SearchScreen}
options={{title: title('Search')}} options={{title: title('Search')}}
/> />
<Flat.Screen
name="Feeds"
component={FeedsScreen}
options={{title: title('Feeds')}}
/>
<Flat.Screen <Flat.Screen
name="Notifications" name="Notifications"
component={NotificationsScreen} component={NotificationsScreen}

View File

@ -143,9 +143,6 @@ export class FeedTuner {
} }
} }
// sort by slice roots' timestamps
slices.sort((a, b) => b.ts.localeCompare(a.ts))
for (const slice of slices) { for (const slice of slices) {
for (const item of slice.items) { for (const item of slice.items) {
this.seenUris.add(item.post.uri) this.seenUris.add(item.post.uri)

View File

@ -18,6 +18,7 @@ export interface ExternalEmbedDraft {
uri: string uri: string
isLoading: boolean isLoading: boolean
meta?: LinkMeta meta?: LinkMeta
embed?: AppBskyEmbedRecord.Main
localThumb?: ImageModel localThumb?: ImageModel
} }
@ -135,40 +136,54 @@ export async function post(store: RootStoreModel, opts: PostOpts) {
} }
if (opts.extLink && !opts.images?.length) { if (opts.extLink && !opts.images?.length) {
let thumb if (opts.extLink.embed) {
if (opts.extLink.localThumb) { embed = opts.extLink.embed
opts.onStateChange?.('Uploading link thumbnail...') } else {
let encoding let thumb
if (opts.extLink.localThumb.mime) { if (opts.extLink.localThumb) {
encoding = opts.extLink.localThumb.mime opts.onStateChange?.('Uploading link thumbnail...')
} else if (opts.extLink.localThumb.path.endsWith('.png')) { let encoding
encoding = 'image/png' if (opts.extLink.localThumb.mime) {
} else if ( encoding = opts.extLink.localThumb.mime
opts.extLink.localThumb.path.endsWith('.jpeg') || } else if (opts.extLink.localThumb.path.endsWith('.png')) {
opts.extLink.localThumb.path.endsWith('.jpg') encoding = 'image/png'
) { } else if (
encoding = 'image/jpeg' opts.extLink.localThumb.path.endsWith('.jpeg') ||
} else { opts.extLink.localThumb.path.endsWith('.jpg')
store.log.warn( ) {
'Unexpected image format for thumbnail, skipping', encoding = 'image/jpeg'
opts.extLink.localThumb.path, } else {
) store.log.warn(
'Unexpected image format for thumbnail, skipping',
opts.extLink.localThumb.path,
)
}
if (encoding) {
const thumbUploadRes = await uploadBlob(
store,
opts.extLink.localThumb.path,
encoding,
)
thumb = thumbUploadRes.data.blob
}
} }
if (encoding) {
const thumbUploadRes = await uploadBlob(
store,
opts.extLink.localThumb.path,
encoding,
)
thumb = thumbUploadRes.data.blob
}
}
if (opts.quote) { if (opts.quote) {
embed = { embed = {
$type: 'app.bsky.embed.recordWithMedia', $type: 'app.bsky.embed.recordWithMedia',
record: embed, record: embed,
media: { media: {
$type: 'app.bsky.embed.external',
external: {
uri: opts.extLink.uri,
title: opts.extLink.meta?.title || '',
description: opts.extLink.meta?.description || '',
thumb,
},
} as AppBskyEmbedExternal.Main,
} as AppBskyEmbedRecordWithMedia.Main
} else {
embed = {
$type: 'app.bsky.embed.external', $type: 'app.bsky.embed.external',
external: { external: {
uri: opts.extLink.uri, uri: opts.extLink.uri,
@ -176,18 +191,8 @@ export async function post(store: RootStoreModel, opts: PostOpts) {
description: opts.extLink.meta?.description || '', description: opts.extLink.meta?.description || '',
thumb, thumb,
}, },
} as AppBskyEmbedExternal.Main, } as AppBskyEmbedExternal.Main
} as AppBskyEmbedRecordWithMedia.Main }
} else {
embed = {
$type: 'app.bsky.embed.external',
external: {
uri: opts.extLink.uri,
title: opts.extLink.meta?.title || '',
description: opts.extLink.meta?.description || '',
thumb,
},
} as AppBskyEmbedExternal.Main
} }
} }

View File

@ -4,6 +4,22 @@ import set from 'lodash.set'
const ongoingActions = new Set<any>() const ongoingActions = new Set<any>()
/**
* This is a TypeScript function that optimistically updates data on the client-side before sending a
* request to the server and rolling back changes if the request fails.
* @param {T} model - The object or record that needs to be updated optimistically.
* @param preUpdate - `preUpdate` is a function that is called before the server update is executed. It
* can be used to perform any necessary actions or updates on the model or UI before the server update
* is initiated.
* @param serverUpdate - `serverUpdate` is a function that returns a Promise representing the server
* update operation. This function is called after the previous state of the model has been recorded
* and the `preUpdate` function has been executed. If the server update is successful, the `postUpdate`
* function is called with the result
* @param [postUpdate] - `postUpdate` is an optional callback function that will be called after the
* server update is successful. It takes in the response from the server update as its parameter. If
* this parameter is not provided, nothing will happen after the server update.
* @returns A Promise that resolves to `void`.
*/
export const updateDataOptimistically = async < export const updateDataOptimistically = async <
T extends Record<string, any>, T extends Record<string, any>,
U, U,

View File

@ -94,6 +94,49 @@ export function SUGGESTED_FOLLOWS(serviceUrl: string) {
} }
} }
export const STAGING_DEFAULT_FEED = (rkey: string) =>
`at://did:plc:wqzurwm3kmaig6e6hnc2gqwo/app.bsky.feed.generator/${rkey}`
export const PROD_DEFAULT_FEED = (rkey: string) =>
`at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/${rkey}`
export async function DEFAULT_FEEDS(
serviceUrl: string,
resolveHandle: (name: string) => Promise<string>,
) {
if (serviceUrl.includes('localhost')) {
// local dev
const aliceDid = await resolveHandle('alice.test')
return {
pinned: [`at://${aliceDid}/app.bsky.feed.generator/alice-favs`],
saved: [`at://${aliceDid}/app.bsky.feed.generator/alice-favs`],
}
} else if (serviceUrl.includes('staging')) {
// staging
return {
pinned: [STAGING_DEFAULT_FEED('whats-hot')],
saved: [
STAGING_DEFAULT_FEED('bsky-team'),
STAGING_DEFAULT_FEED('with-friends'),
STAGING_DEFAULT_FEED('whats-hot'),
STAGING_DEFAULT_FEED('hot-classic'),
],
}
} else {
// production
return {
pinned: [
PROD_DEFAULT_FEED('whats-hot'),
PROD_DEFAULT_FEED('with-friends'),
],
saved: [
PROD_DEFAULT_FEED('bsky-team'),
PROD_DEFAULT_FEED('with-friends'),
PROD_DEFAULT_FEED('whats-hot'),
PROD_DEFAULT_FEED('hot-classic'),
],
}
}
}
export const POST_IMG_MAX = { export const POST_IMG_MAX = {
width: 2000, width: 2000,
height: 2000, height: 2000,

40
src/lib/haptics.ts 100644
View File

@ -0,0 +1,40 @@
import {isIOS, isWeb} from 'platform/detection'
import ReactNativeHapticFeedback, {
HapticFeedbackTypes,
} from 'react-native-haptic-feedback'
const hapticImpact: HapticFeedbackTypes = isIOS ? 'impactMedium' : 'impactLight' // Users said the medium impact was too strong on Android; see APP-537s
export class Haptics {
static default() {
if (isWeb) {
return
}
ReactNativeHapticFeedback.trigger(hapticImpact)
}
static impact(type: HapticFeedbackTypes = hapticImpact) {
if (isWeb) {
return
}
ReactNativeHapticFeedback.trigger(type)
}
static selection() {
if (isWeb) {
return
}
ReactNativeHapticFeedback.trigger('selection')
}
static notification = (type: 'success' | 'warning' | 'error') => {
if (isWeb) {
return
}
switch (type) {
case 'success':
return ReactNativeHapticFeedback.trigger('notificationSuccess')
case 'warning':
return ReactNativeHapticFeedback.trigger('notificationWarning')
case 'error':
return ReactNativeHapticFeedback.trigger('notificationError')
}
}
}

View File

@ -0,0 +1,27 @@
import {useEffect, useState} from 'react'
import {useStores} from 'state/index'
import {CustomFeedModel} from 'state/models/feeds/custom-feed'
export function useCustomFeed(uri: string): CustomFeedModel | undefined {
const store = useStores()
const [item, setItem] = useState<CustomFeedModel | undefined>()
useEffect(() => {
async function fetchView() {
const res = await store.agent.app.bsky.feed.getFeedGenerator({
feed: uri,
})
const view = res.data.view
return view
}
async function buildFeedItem() {
const view = await fetchView()
if (view) {
const temp = new CustomFeedModel(store, view)
setItem(temp)
}
}
buildFeedItem()
}, [store, uri])
return item
}

View File

@ -0,0 +1,84 @@
import {useEffect, useRef, useMemo, ForwardedRef} from 'react'
import {Platform, findNodeHandle} from 'react-native'
import type {ScrollView} from 'react-native'
import {mergeRefs} from 'lib/merge-refs'
type Props<Scrollable extends ScrollView = ScrollView> = {
cursor?: string
outerRef?: ForwardedRef<Scrollable>
}
export function useDraggableScroll<Scrollable extends ScrollView = ScrollView>({
outerRef,
cursor = 'grab',
}: Props<Scrollable> = {}) {
const ref = useRef<Scrollable>(null)
useEffect(() => {
if (Platform.OS !== 'web' || !ref.current) {
return
}
const slider = findNodeHandle(ref.current) as unknown as HTMLDivElement
if (!slider) {
return
}
let isDragging = false
let isMouseDown = false
let startX = 0
let scrollLeft = 0
const mouseDown = (e: MouseEvent) => {
isMouseDown = true
startX = e.pageX - slider.offsetLeft
scrollLeft = slider.scrollLeft
slider.style.cursor = cursor
}
const mouseUp = () => {
if (isDragging) {
slider.addEventListener('click', e => e.stopPropagation(), {once: true})
}
isMouseDown = false
isDragging = false
slider.style.cursor = 'default'
}
const mouseMove = (e: MouseEvent) => {
if (!isMouseDown) {
return
}
// Require n pixels momement before start of drag (3 in this case )
const x = e.pageX - slider.offsetLeft
if (Math.abs(x - startX) < 3) {
return
}
isDragging = true
e.preventDefault()
const walk = x - startX
slider.scrollLeft = scrollLeft - walk
}
slider.addEventListener('mousedown', mouseDown)
window.addEventListener('mouseup', mouseUp)
window.addEventListener('mousemove', mouseMove)
return () => {
slider.removeEventListener('mousedown', mouseDown)
window.removeEventListener('mouseup', mouseUp)
window.removeEventListener('mousemove', mouseMove)
}
}, [cursor])
const refs = useMemo(
() => mergeRefs(outerRef ? [ref, outerRef] : [ref]),
[ref, outerRef],
)
return {
refs,
}
}

View File

@ -6,14 +6,16 @@ export function useNavigationTabState() {
const res = { const res = {
isAtHome: getTabState(state, 'Home') !== TabState.Outside, isAtHome: getTabState(state, 'Home') !== TabState.Outside,
isAtSearch: getTabState(state, 'Search') !== TabState.Outside, isAtSearch: getTabState(state, 'Search') !== TabState.Outside,
isAtFeeds: getTabState(state, 'Feeds') !== TabState.Outside,
isAtNotifications: isAtNotifications:
getTabState(state, 'Notifications') !== TabState.Outside, getTabState(state, 'Notifications') !== TabState.Outside,
isAtMyProfile: getTabState(state, 'MyProfile') !== TabState.Outside, isAtMyProfile: getTabState(state, 'MyProfile') !== TabState.Outside,
} }
if ( if (
!res.isAtHome && !res.isAtHome &&
!res.isAtNotifications &&
!res.isAtSearch && !res.isAtSearch &&
!res.isAtFeeds &&
!res.isAtNotifications &&
!res.isAtMyProfile !res.isAtMyProfile
) { ) {
// HACK for some reason useNavigationState will give us pre-hydration results // HACK for some reason useNavigationState will give us pre-hydration results

View File

@ -1,25 +1,56 @@
import {useState} from 'react' import {useState, useCallback, useRef} from 'react'
import {NativeSyntheticEvent, NativeScrollEvent} from 'react-native' import {NativeSyntheticEvent, NativeScrollEvent} from 'react-native'
import {RootStoreModel} from 'state/index' import {RootStoreModel} from 'state/index'
import {s} from 'lib/styles'
import {isDesktopWeb} from 'platform/detection'
const DY_LIMIT = isDesktopWeb ? 30 : 10
export type OnScrollCb = ( export type OnScrollCb = (
event: NativeSyntheticEvent<NativeScrollEvent>, event: NativeSyntheticEvent<NativeScrollEvent>,
) => void ) => void
export type ResetCb = () => void
export function useOnMainScroll(store: RootStoreModel) { export function useOnMainScroll(
let [lastY, setLastY] = useState(0) store: RootStoreModel,
let isMinimal = store.shell.minimalShellMode ): [OnScrollCb, boolean, ResetCb] {
return function onMainScroll(event: NativeSyntheticEvent<NativeScrollEvent>) { let lastY = useRef(0)
const y = event.nativeEvent.contentOffset.y let [isScrolledDown, setIsScrolledDown] = useState(false)
const dy = y - (lastY || 0) return [
setLastY(y) useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
const y = event.nativeEvent.contentOffset.y
const dy = y - (lastY.current || 0)
lastY.current = y
if (!isMinimal && y > 10 && dy > 10) { if (!store.shell.minimalShellMode && y > 10 && dy > DY_LIMIT) {
store.shell.setMinimalShellMode(true) store.shell.setMinimalShellMode(true)
isMinimal = true } else if (
} else if (isMinimal && (y <= 10 || dy < -10)) { store.shell.minimalShellMode &&
(y <= 10 || dy < DY_LIMIT * -1)
) {
store.shell.setMinimalShellMode(false)
}
if (
!isScrolledDown &&
event.nativeEvent.contentOffset.y > s.window.height
) {
setIsScrolledDown(true)
} else if (
isScrolledDown &&
event.nativeEvent.contentOffset.y < s.window.height
) {
setIsScrolledDown(false)
}
},
[store, isScrolledDown],
),
isScrolledDown,
useCallback(() => {
setIsScrolledDown(false)
store.shell.setMinimalShellMode(false) store.shell.setMinimalShellMode(false)
isMinimal = false lastY.current = 1e8 // NOTE we set this very high so that the onScroll logic works right -prf
} }, [store, setIsScrolledDown]),
} ]
} }

View File

@ -1,6 +1,6 @@
import React from 'react' import React from 'react'
import {StyleProp, TextStyle, ViewStyle} from 'react-native' import {StyleProp, TextStyle, ViewStyle} from 'react-native'
import Svg, {Path, Rect, Line, Ellipse} from 'react-native-svg' import Svg, {Path, Rect, Line, Ellipse, Circle} from 'react-native-svg'
export function GridIcon({ export function GridIcon({
style, style,
@ -472,7 +472,7 @@ export function HeartIcon({
size = 24, size = 24,
strokeWidth = 1.5, strokeWidth = 1.5,
}: { }: {
style?: StyleProp<ViewStyle> style?: StyleProp<TextStyle>
size?: string | number size?: string | number
strokeWidth: number strokeWidth: number
}) { }) {
@ -493,7 +493,7 @@ export function HeartIconSolid({
style, style,
size = 24, size = 24,
}: { }: {
style?: StyleProp<ViewStyle> style?: StyleProp<TextStyle>
size?: string | number size?: string | number
}) { }) {
return ( return (
@ -883,3 +883,77 @@ export function HandIcon({
</Svg> </Svg>
) )
} }
export function SatelliteDishIconSolid({
style,
size,
strokeWidth = 1.5,
}: {
style?: StyleProp<ViewStyle>
size?: string | number
strokeWidth?: number
}) {
return (
<Svg
width={size || 24}
height={size || 24}
viewBox="0 0 22 22"
style={style}
fill="none"
stroke="none">
<Path
d="M16 19.6622C14.5291 20.513 12.8214 21 11 21C5.47715 21 1 16.5229 1 11C1 9.17858 1.48697 7.47088 2.33782 6.00002C3.18867 4.52915 6 7.66219 6 7.66219L14.5 16.1622C14.5 16.1622 17.4709 18.8113 16 19.6622Z"
fill="currentColor"
/>
<Path
d="M8 1.62961C9.04899 1.22255 10.1847 1 11.3704 1C16.6887 1 21 5.47715 21 11C21 12.0452 20.8456 13.053 20.5592 14"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
/>
<Path
d="M9 5.38745C9.64553 5.13695 10.3444 5 11.0741 5C14.3469 5 17 7.75517 17 11.1538C17 11.797 16.905 12.4172 16.7287 13"
stroke="currentColor"
strokeWidth={strokeWidth}
strokeLinecap="round"
/>
<Circle cx="10" cy="12" r="2" fill="currentColor" />
</Svg>
)
}
export function SatelliteDishIcon({
style,
size,
strokeWidth = 1.5,
}: {
style?: StyleProp<TextStyle>
size?: string | number
strokeWidth?: number
}) {
return (
<Svg
fill="none"
viewBox="0 0 22 22"
strokeWidth={strokeWidth}
stroke="currentColor"
width={size}
height={size}
style={style}>
<Path d="M5.25593 8.3303L5.25609 8.33047L5.25616 8.33056L5.25621 8.33061L5.27377 8.35018L5.29289 8.3693L13.7929 16.8693L13.8131 16.8895L13.8338 16.908L13.834 16.9081L13.8342 16.9083L13.8342 16.9083L13.8345 16.9086L13.8381 16.9118L13.8574 16.9294C13.8752 16.9458 13.9026 16.9711 13.9377 17.0043C14.0081 17.0708 14.1088 17.1683 14.2258 17.2881C14.4635 17.5315 14.7526 17.8509 14.9928 18.1812C15.2067 18.4755 15.3299 18.7087 15.3817 18.8634C14.0859 19.5872 12.5926 20 11 20C6.02944 20 2 15.9706 2 11C2 9.4151 2.40883 7.9285 3.12619 6.63699C3.304 6.69748 3.56745 6.84213 3.89275 7.08309C4.24679 7.34534 4.58866 7.65673 4.84827 7.9106C4.97633 8.03583 5.08062 8.14337 5.152 8.21863C5.18763 8.25619 5.21487 8.28551 5.23257 8.30473L5.25178 8.32572L5.25571 8.33006L5.25593 8.3303ZM3.00217 6.60712C3.00217 6.6071 3.00267 6.6071 3.00372 6.60715C3.00271 6.60716 3.00218 6.60714 3.00217 6.60712Z" />
<Path
d="M8 1.62961C9.04899 1.22255 10.1847 1 11.3704 1C16.6887 1 21 5.47715 21 11C21 12.0452 20.8456 13.053 20.5592 14"
stroke-linecap="round"
/>
<Path
d="M9 5.38745C9.64553 5.13695 10.3444 5 11.0741 5C14.3469 5 17 7.75517 17 11.1538C17 11.797 16.905 12.4172 16.7287 13"
stroke-linecap="round"
/>
<Path
d="M12 12C12 12.7403 11.5978 13.3866 11 13.7324L8.26756 11C8.61337 10.4022 9.25972 10 10 10C11.1046 10 12 10.8954 12 12Z"
fill="currentColor"
stroke="none"
/>
</Svg>
)
}

View File

@ -1,3 +1,4 @@
import * as apilib from 'lib/api/index'
import {LikelyType, LinkMeta} from './link-meta' import {LikelyType, LinkMeta} from './link-meta'
// import {match as matchRoute} from 'view/routes' // import {match as matchRoute} from 'view/routes'
import {convertBskyAppUrlIfNeeded, makeRecordUri} from '../strings/url-helpers' import {convertBskyAppUrlIfNeeded, makeRecordUri} from '../strings/url-helpers'
@ -128,3 +129,29 @@ export async function getPostAsQuote(
}, },
} }
} }
export async function getFeedAsEmbed(
store: RootStoreModel,
url: string,
): Promise<apilib.ExternalEmbedDraft> {
url = convertBskyAppUrlIfNeeded(url)
const [_0, user, _1, rkey] = url.split('/').filter(Boolean)
const feed = makeRecordUri(user, 'app.bsky.feed.generator', rkey)
const res = await store.agent.app.bsky.feed.getFeedGenerator({feed})
return {
isLoading: false,
uri: feed,
meta: {
url: feed,
likelyType: LikelyType.AtpData,
title: res.data.view.displayName,
},
embed: {
$type: 'app.bsky.embed.record',
record: {
uri: res.data.view.uri,
cid: res.data.view.cid,
},
},
}
}

View File

@ -0,0 +1,27 @@
/**
* This TypeScript function merges multiple React refs into a single ref callback.
* When developing low level UI components, it is common to have to use a local ref
* but also support an external one using React.forwardRef.
* Natively, React does not offer a way to set two refs inside the ref property. This is the goal of this small utility.
* Today a ref can be a function or an object, tomorrow it could be another thing, who knows.
* This utility handles compatibility for you.
* This function is inspired by https://github.com/gregberge/react-merge-refs
* @param refs - An array of React refs, which can be either `React.MutableRefObject<T>` or
* `React.LegacyRef<T>`. These refs are used to store references to DOM elements or React components.
* The `mergeRefs` function takes in an array of these refs and returns a callback function that
* @returns The function `mergeRefs` is being returned. It takes an array of mutable or legacy refs and
* returns a ref callback function that can be used to merge multiple refs into a single ref.
*/
export function mergeRefs<T = any>(
refs: Array<React.MutableRefObject<T> | React.LegacyRef<T>>,
): React.RefCallback<T> {
return value => {
refs.forEach(ref => {
if (typeof ref === 'function') {
ref(value)
} else if (ref != null) {
;(ref as React.MutableRefObject<T | null>).current = value
}
})
}
}

View File

@ -9,6 +9,7 @@ export type CommonNavigatorParams = {
ModerationMuteLists: undefined ModerationMuteLists: undefined
ModerationMutedAccounts: undefined ModerationMutedAccounts: undefined
ModerationBlockedAccounts: undefined ModerationBlockedAccounts: undefined
DiscoverFeeds: undefined
Settings: undefined Settings: undefined
Profile: {name: string; hideBackButton?: boolean} Profile: {name: string; hideBackButton?: boolean}
ProfileFollowers: {name: string} ProfileFollowers: {name: string}
@ -17,6 +18,8 @@ export type CommonNavigatorParams = {
PostThread: {name: string; rkey: string} PostThread: {name: string; rkey: string}
PostLikedBy: {name: string; rkey: string} PostLikedBy: {name: string; rkey: string}
PostRepostedBy: {name: string; rkey: string} PostRepostedBy: {name: string; rkey: string}
CustomFeed: {name: string; rkey: string}
CustomFeedLikedBy: {name: string; rkey: string}
Debug: undefined Debug: undefined
Log: undefined Log: undefined
Support: undefined Support: undefined
@ -25,11 +28,13 @@ export type CommonNavigatorParams = {
CommunityGuidelines: undefined CommunityGuidelines: undefined
CopyrightPolicy: undefined CopyrightPolicy: undefined
AppPasswords: undefined AppPasswords: undefined
SavedFeeds: undefined
} }
export type BottomTabNavigatorParams = CommonNavigatorParams & { export type BottomTabNavigatorParams = CommonNavigatorParams & {
HomeTab: undefined HomeTab: undefined
SearchTab: undefined SearchTab: undefined
FeedsTab: undefined
NotificationsTab: undefined NotificationsTab: undefined
MyProfileTab: undefined MyProfileTab: undefined
} }
@ -42,6 +47,10 @@ export type SearchTabNavigatorParams = CommonNavigatorParams & {
Search: {q?: string} Search: {q?: string}
} }
export type FeedsTabNavigatorParams = CommonNavigatorParams & {
Feeds: undefined
}
export type NotificationsTabNavigatorParams = CommonNavigatorParams & { export type NotificationsTabNavigatorParams = CommonNavigatorParams & {
Notifications: undefined Notifications: undefined
} }
@ -53,6 +62,7 @@ export type MyProfileTabNavigatorParams = CommonNavigatorParams & {
export type FlatNavigatorParams = CommonNavigatorParams & { export type FlatNavigatorParams = CommonNavigatorParams & {
Home: undefined Home: undefined
Search: {q?: string} Search: {q?: string}
Feeds: undefined
Notifications: undefined Notifications: undefined
} }
@ -61,6 +71,8 @@ export type AllNavigatorParams = CommonNavigatorParams & {
Home: undefined Home: undefined
SearchTab: undefined SearchTab: undefined
Search: {q?: string} Search: {q?: string}
FeedsTab: undefined
Feeds: undefined
NotificationsTab: undefined NotificationsTab: undefined
Notifications: undefined Notifications: undefined
MyProfileTab: undefined MyProfileTab: undefined

View File

@ -82,6 +82,18 @@ export function isBskyPostUrl(url: string): boolean {
return false return false
} }
export function isBskyCustomFeedUrl(url: string): boolean {
if (isBskyAppUrl(url)) {
try {
const urlp = new URL(url)
return /profile\/(?<name>[^/]+)\/feed\/(?<rkey>[^/]+)/i.test(
urlp.pathname,
)
} catch {}
}
return false
}
export function convertBskyAppUrlIfNeeded(url: string): string { export function convertBskyAppUrlIfNeeded(url: string): string {
if (isBskyAppUrl(url)) { if (isBskyAppUrl(url)) {
try { try {

View File

@ -1,4 +1,4 @@
import {StyleProp, StyleSheet, TextStyle} from 'react-native' import {Dimensions, StyleProp, StyleSheet, TextStyle} from 'react-native'
import {Theme, TypographyVariant} from './ThemeContext' import {Theme, TypographyVariant} from './ThemeContext'
import {isMobileWeb} from 'platform/detection' import {isMobileWeb} from 'platform/detection'
@ -52,6 +52,7 @@ export const colors = {
green5: '#082b03', green5: '#082b03',
unreadNotifBg: '#ebf6ff', unreadNotifBg: '#ebf6ff',
brandBlue: '#0066FF',
} }
export const gradients = { export const gradients = {
@ -169,6 +170,10 @@ export const s = StyleSheet.create({
w100pct: {width: '100%'}, w100pct: {width: '100%'},
h100pct: {height: '100%'}, h100pct: {height: '100%'},
hContentRegion: isMobileWeb ? {flex: 1} : {height: '100%'}, hContentRegion: isMobileWeb ? {flex: 1} : {height: '100%'},
window: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
},
// text align // text align
textLeft: {textAlign: 'left'}, textLeft: {textAlign: 'left'},
@ -214,6 +219,8 @@ export const s = StyleSheet.create({
green3: {color: colors.green3}, green3: {color: colors.green3},
green4: {color: colors.green4}, green4: {color: colors.green4},
green5: {color: colors.green5}, green5: {color: colors.green5},
brandBlue: {color: colors.brandBlue},
}) })
export function lh( export function lh(

View File

@ -3,6 +3,8 @@ import {Router} from 'lib/routes/router'
export const router = new Router({ export const router = new Router({
Home: '/', Home: '/',
Search: '/search', Search: '/search',
Feeds: '/feeds',
DiscoverFeeds: '/search/feeds',
Notifications: '/notifications', Notifications: '/notifications',
Settings: '/settings', Settings: '/settings',
Moderation: '/moderation', Moderation: '/moderation',
@ -16,9 +18,12 @@ export const router = new Router({
PostThread: '/profile/:name/post/:rkey', PostThread: '/profile/:name/post/:rkey',
PostLikedBy: '/profile/:name/post/:rkey/liked-by', PostLikedBy: '/profile/:name/post/:rkey/liked-by',
PostRepostedBy: '/profile/:name/post/:rkey/reposted-by', PostRepostedBy: '/profile/:name/post/:rkey/reposted-by',
CustomFeed: '/profile/:name/feed/:rkey',
CustomFeedLikedBy: '/profile/:name/feed/:rkey/liked-by',
Debug: '/sys/debug', Debug: '/sys/debug',
Log: '/sys/log', Log: '/sys/log',
AppPasswords: '/settings/app-passwords', AppPasswords: '/settings/app-passwords',
SavedFeeds: '/settings/saved-feeds',
Support: '/support', Support: '/support',
PrivacyPolicy: '/support/privacy', PrivacyPolicy: '/support/privacy',
TermsOfService: '/support/tos', TermsOfService: '/support/tos',

View File

@ -0,0 +1,97 @@
import {makeAutoObservable} from 'mobx'
import {AppBskyUnspeccedGetPopularFeedGenerators} from '@atproto/api'
import {RootStoreModel} from '../root-store'
import {bundleAsync} from 'lib/async/bundle'
import {cleanError} from 'lib/strings/errors'
import {CustomFeedModel} from '../feeds/custom-feed'
export class FeedsDiscoveryModel {
// state
isLoading = false
isRefreshing = false
hasLoaded = false
error = ''
// data
feeds: CustomFeedModel[] = []
constructor(public rootStore: RootStoreModel) {
makeAutoObservable(
this,
{
rootStore: false,
},
{autoBind: true},
)
}
get hasMore() {
return false
}
get hasContent() {
return this.feeds.length > 0
}
get hasError() {
return this.error !== ''
}
get isEmpty() {
return this.hasLoaded && !this.hasContent
}
// public api
// =
refresh = bundleAsync(async () => {
this._xLoading()
try {
const res =
await this.rootStore.agent.app.bsky.unspecced.getPopularFeedGenerators(
{},
)
this._replaceAll(res)
this._xIdle()
} catch (e: any) {
this._xIdle(e)
}
})
clear() {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = false
this.error = ''
this.feeds = []
}
// state transitions
// =
_xLoading() {
this.isLoading = true
this.isRefreshing = true
this.error = ''
}
_xIdle(err?: any) {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = true
this.error = cleanError(err)
if (err) {
this.rootStore.log.error('Failed to fetch popular feeds', err)
}
}
// helper functions
// =
_replaceAll(res: AppBskyUnspeccedGetPopularFeedGenerators.Response) {
this.feeds = []
for (const f of res.data.feeds) {
this.feeds.push(new CustomFeedModel(this.rootStore, f))
}
}
}

View File

@ -0,0 +1,120 @@
import {AppBskyFeedDefs} from '@atproto/api'
import {makeAutoObservable, runInAction} from 'mobx'
import {RootStoreModel} from 'state/models/root-store'
import {sanitizeDisplayName} from 'lib/strings/display-names'
import {updateDataOptimistically} from 'lib/async/revertible'
export class CustomFeedModel {
// data
_reactKey: string
data: AppBskyFeedDefs.GeneratorView
isOnline: boolean
isValid: boolean
constructor(
public rootStore: RootStoreModel,
view: AppBskyFeedDefs.GeneratorView,
isOnline?: boolean,
isValid?: boolean,
) {
this._reactKey = view.uri
this.data = view
this.isOnline = isOnline ?? true
this.isValid = isValid ?? true
makeAutoObservable(
this,
{
rootStore: false,
},
{autoBind: true},
)
}
// local actions
// =
get uri() {
return this.data.uri
}
get displayName() {
if (this.data.displayName) {
return sanitizeDisplayName(this.data.displayName)
}
return `Feed by @${this.data.creator.handle}`
}
get isSaved() {
return this.rootStore.preferences.savedFeeds.includes(this.uri)
}
get isLiked() {
return this.data.viewer?.like
}
// public apis
// =
async save() {
await this.rootStore.preferences.addSavedFeed(this.uri)
}
async unsave() {
await this.rootStore.preferences.removeSavedFeed(this.uri)
}
async like() {
try {
await updateDataOptimistically(
this.data,
() => {
this.data.viewer = this.data.viewer || {}
this.data.viewer.like = 'pending'
this.data.likeCount = (this.data.likeCount || 0) + 1
},
() => this.rootStore.agent.like(this.data.uri, this.data.cid),
res => {
this.data.viewer = this.data.viewer || {}
this.data.viewer.like = res.uri
},
)
} catch (e: any) {
this.rootStore.log.error('Failed to like feed', e)
}
}
async unlike() {
if (!this.data.viewer?.like) {
return
}
try {
const likeUri = this.data.viewer.like
await updateDataOptimistically(
this.data,
() => {
this.data.viewer = this.data.viewer || {}
this.data.viewer.like = undefined
this.data.likeCount = (this.data.likeCount || 1) - 1
},
() => this.rootStore.agent.deleteLike(likeUri),
)
} catch (e: any) {
this.rootStore.log.error('Failed to unlike feed', e)
}
}
async reload() {
const res = await this.rootStore.agent.app.bsky.feed.getFeedGenerator({
feed: this.data.uri,
})
runInAction(() => {
this.data = res.data.view
this.isOnline = res.data.isOnline
this.isValid = res.data.isValid
})
}
serialize() {
return JSON.stringify(this.data)
}
}

View File

@ -0,0 +1,216 @@
import {makeAutoObservable, runInAction} from 'mobx'
import {AtUri} from '@atproto/api'
import {bundleAsync} from 'lib/async/bundle'
import {RootStoreModel} from '../root-store'
import {CustomFeedModel} from './custom-feed'
import {PostsFeedModel} from './posts'
import {PostsFeedSliceModel} from './post'
const FEED_PAGE_SIZE = 5
const FEEDS_PAGE_SIZE = 3
export type MultiFeedItem =
| {
_reactKey: string
type: 'header'
}
| {
_reactKey: string
type: 'feed-header'
avatar: string | undefined
title: string
}
| {
_reactKey: string
type: 'feed-slice'
slice: PostsFeedSliceModel
}
| {
_reactKey: string
type: 'feed-loading'
}
| {
_reactKey: string
type: 'feed-error'
error: string
}
| {
_reactKey: string
type: 'feed-footer'
title: string
uri: string
}
| {
_reactKey: string
type: 'footer'
}
export class PostsMultiFeedModel {
// state
isLoading = false
isRefreshing = false
hasLoaded = false
hasMore = true
// data
feedInfos: CustomFeedModel[] = []
feeds: PostsFeedModel[] = []
constructor(public rootStore: RootStoreModel) {
makeAutoObservable(this, {rootStore: false}, {autoBind: true})
}
get hasContent() {
return this.feeds.length !== 0
}
get isEmpty() {
return this.hasLoaded && !this.hasContent
}
get items() {
const items: MultiFeedItem[] = [{_reactKey: '__header__', type: 'header'}]
for (let i = 0; i < this.feedInfos.length; i++) {
if (!this.feeds[i]) {
break
}
const feed = this.feeds[i]
const feedInfo = this.feedInfos[i]
const urip = new AtUri(feedInfo.uri)
items.push({
_reactKey: `__feed_header_${i}__`,
type: 'feed-header',
avatar: feedInfo.data.avatar,
title: feedInfo.displayName,
})
if (feed.isLoading) {
items.push({
_reactKey: `__feed_loading_${i}__`,
type: 'feed-loading',
})
} else if (feed.hasError) {
items.push({
_reactKey: `__feed_error_${i}__`,
type: 'feed-error',
error: feed.error,
})
} else {
for (let j = 0; j < feed.slices.length; j++) {
items.push({
_reactKey: `__feed_slice_${i}_${j}__`,
type: 'feed-slice',
slice: feed.slices[j],
})
}
}
items.push({
_reactKey: `__feed_footer_${i}__`,
type: 'feed-footer',
title: feedInfo.displayName,
uri: `/profile/${feedInfo.data.creator.did}/feed/${urip.rkey}`,
})
}
if (!this.hasMore) {
items.push({_reactKey: '__footer__', type: 'footer'})
}
return items
}
// public api
// =
/**
* Nuke all data
*/
clear() {
this.rootStore.log.debug('MultiFeedModel:clear')
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = false
this.hasMore = true
this.feeds = []
}
/**
* Register any event listeners. Returns a cleanup function.
*/
registerListeners() {
const sub = this.rootStore.onPostDeleted(this.onPostDeleted.bind(this))
return () => sub.remove()
}
/**
* Reset and load
*/
async refresh() {
this.feedInfos = this.rootStore.me.savedFeeds.all.slice() // capture current feeds
await this.loadMore(true)
}
/**
* Load more posts to the end of the feed
*/
loadMore = bundleAsync(async (isRefreshing: boolean = false) => {
if (!isRefreshing && !this.hasMore) {
return
}
if (isRefreshing) {
this.isRefreshing = true // set optimistically for UI
this.feeds = []
}
this._xLoading(isRefreshing)
const start = this.feeds.length
const newFeeds: PostsFeedModel[] = []
for (
let i = start;
i < start + FEEDS_PAGE_SIZE && i < this.feedInfos.length;
i++
) {
const feed = new PostsFeedModel(this.rootStore, 'custom', {
feed: this.feedInfos[i].uri,
})
feed.pageSize = FEED_PAGE_SIZE
await feed.setup()
newFeeds.push(feed)
}
runInAction(() => {
this.feeds = this.feeds.concat(newFeeds)
this.hasMore = this.feeds.length < this.feedInfos.length
})
this._xIdle()
})
/**
* Attempt to load more again after a failure
*/
async retryLoadMore() {
this.hasMore = true
return this.loadMore()
}
/**
* Removes posts from the feed upon deletion.
*/
onPostDeleted(uri: string) {
for (const f of this.feeds) {
f.onPostDeleted(uri)
}
}
// state transitions
// =
_xLoading(isRefreshing = false) {
this.isLoading = true
this.isRefreshing = isRefreshing
}
_xIdle() {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = true
}
// helper functions
// =
}

View File

@ -290,7 +290,9 @@ export class NotificationsFeedModel {
} }
get hasNewLatest() { get hasNewLatest() {
return this.queuedNotifications && this.queuedNotifications?.length > 0 return Boolean(
this.queuedNotifications && this.queuedNotifications?.length > 0,
)
} }
get unreadCountLabel(): string { get unreadCountLabel(): string {

View File

@ -0,0 +1,265 @@
import {makeAutoObservable} from 'mobx'
import {AppBskyFeedDefs, AppBskyFeedPost, RichText} from '@atproto/api'
import {RootStoreModel} from '../root-store'
import {updateDataOptimistically} from 'lib/async/revertible'
import {PostLabelInfo, PostModeration} from 'lib/labeling/types'
import {FeedViewPostsSlice} from 'lib/api/feed-manip'
import {
getEmbedLabels,
getEmbedMuted,
getEmbedMutedByList,
getEmbedBlocking,
getEmbedBlockedBy,
getPostModeration,
filterAccountLabels,
filterProfileLabels,
mergePostModerations,
} from 'lib/labeling/helpers'
type FeedViewPost = AppBskyFeedDefs.FeedViewPost
type ReasonRepost = AppBskyFeedDefs.ReasonRepost
type PostView = AppBskyFeedDefs.PostView
let _idCounter = 0
export class PostsFeedItemModel {
// ui state
_reactKey: string = ''
// data
post: PostView
postRecord?: AppBskyFeedPost.Record
reply?: FeedViewPost['reply']
reason?: FeedViewPost['reason']
richText?: RichText
constructor(
public rootStore: RootStoreModel,
reactKey: string,
v: FeedViewPost,
) {
this._reactKey = reactKey
this.post = v.post
if (AppBskyFeedPost.isRecord(this.post.record)) {
const valid = AppBskyFeedPost.validateRecord(this.post.record)
if (valid.success) {
this.postRecord = this.post.record
this.richText = new RichText(this.postRecord, {cleanNewlines: true})
} else {
this.postRecord = undefined
this.richText = undefined
rootStore.log.warn(
'Received an invalid app.bsky.feed.post record',
valid.error,
)
}
} else {
this.postRecord = undefined
this.richText = undefined
rootStore.log.warn(
'app.bsky.feed.getTimeline or app.bsky.feed.getAuthorFeed served an unexpected record type',
this.post.record,
)
}
this.reply = v.reply
this.reason = v.reason
makeAutoObservable(this, {rootStore: false})
}
get rootUri(): string {
if (this.reply?.root.uri) {
return this.reply.root.uri
}
return this.post.uri
}
get isThreadMuted() {
return this.rootStore.mutedThreads.uris.has(this.rootUri)
}
get labelInfo(): PostLabelInfo {
return {
postLabels: (this.post.labels || []).concat(
getEmbedLabels(this.post.embed),
),
accountLabels: filterAccountLabels(this.post.author.labels),
profileLabels: filterProfileLabels(this.post.author.labels),
isMuted:
this.post.author.viewer?.muted ||
getEmbedMuted(this.post.embed) ||
false,
mutedByList:
this.post.author.viewer?.mutedByList ||
getEmbedMutedByList(this.post.embed),
isBlocking:
!!this.post.author.viewer?.blocking ||
getEmbedBlocking(this.post.embed) ||
false,
isBlockedBy:
!!this.post.author.viewer?.blockedBy ||
getEmbedBlockedBy(this.post.embed) ||
false,
}
}
get moderation(): PostModeration {
return getPostModeration(this.rootStore, this.labelInfo)
}
copy(v: FeedViewPost) {
this.post = v.post
this.reply = v.reply
this.reason = v.reason
}
copyMetrics(v: FeedViewPost) {
this.post.replyCount = v.post.replyCount
this.post.repostCount = v.post.repostCount
this.post.likeCount = v.post.likeCount
this.post.viewer = v.post.viewer
}
get reasonRepost(): ReasonRepost | undefined {
if (this.reason?.$type === 'app.bsky.feed.defs#reasonRepost') {
return this.reason as ReasonRepost
}
}
async toggleLike() {
this.post.viewer = this.post.viewer || {}
if (this.post.viewer.like) {
const url = this.post.viewer.like
await updateDataOptimistically(
this.post,
() => {
this.post.likeCount = (this.post.likeCount || 0) - 1
this.post.viewer!.like = undefined
},
() => this.rootStore.agent.deleteLike(url),
)
} else {
await updateDataOptimistically(
this.post,
() => {
this.post.likeCount = (this.post.likeCount || 0) + 1
this.post.viewer!.like = 'pending'
},
() => this.rootStore.agent.like(this.post.uri, this.post.cid),
res => {
this.post.viewer!.like = res.uri
},
)
}
}
async toggleRepost() {
this.post.viewer = this.post.viewer || {}
if (this.post.viewer?.repost) {
const url = this.post.viewer.repost
await updateDataOptimistically(
this.post,
() => {
this.post.repostCount = (this.post.repostCount || 0) - 1
this.post.viewer!.repost = undefined
},
() => this.rootStore.agent.deleteRepost(url),
)
} else {
await updateDataOptimistically(
this.post,
() => {
this.post.repostCount = (this.post.repostCount || 0) + 1
this.post.viewer!.repost = 'pending'
},
() => this.rootStore.agent.repost(this.post.uri, this.post.cid),
res => {
this.post.viewer!.repost = res.uri
},
)
}
}
async toggleThreadMute() {
if (this.isThreadMuted) {
this.rootStore.mutedThreads.uris.delete(this.rootUri)
} else {
this.rootStore.mutedThreads.uris.add(this.rootUri)
}
}
async delete() {
await this.rootStore.agent.deletePost(this.post.uri)
this.rootStore.emitPostDeleted(this.post.uri)
}
}
export class PostsFeedSliceModel {
// ui state
_reactKey: string = ''
// data
items: PostsFeedItemModel[] = []
constructor(
public rootStore: RootStoreModel,
reactKey: string,
slice: FeedViewPostsSlice,
) {
this._reactKey = reactKey
for (const item of slice.items) {
this.items.push(
new PostsFeedItemModel(rootStore, `slice-${_idCounter++}`, item),
)
}
makeAutoObservable(this, {rootStore: false})
}
get uri() {
if (this.isReply) {
return this.items[1].post.uri
}
return this.items[0].post.uri
}
get isThread() {
return (
this.items.length > 1 &&
this.items.every(
item => item.post.author.did === this.items[0].post.author.did,
)
)
}
get isReply() {
return this.items.length > 1 && !this.isThread
}
get rootItem() {
if (this.isReply) {
return this.items[1]
}
return this.items[0]
}
get moderation() {
return mergePostModerations(this.items.map(item => item.moderation))
}
containsUri(uri: string) {
return !!this.items.find(item => item.post.uri === uri)
}
isThreadParentAt(i: number) {
if (this.items.length === 1) {
return false
}
return i < this.items.length - 1
}
isThreadChildAt(i: number) {
if (this.items.length === 1) {
return false
}
return i > 0
}
}

View File

@ -1,11 +1,8 @@
import {makeAutoObservable, runInAction} from 'mobx' import {makeAutoObservable, runInAction} from 'mobx'
import { import {
AppBskyFeedGetTimeline as GetTimeline, AppBskyFeedGetTimeline as GetTimeline,
AppBskyFeedDefs,
AppBskyFeedPost,
AppBskyFeedGetAuthorFeed as GetAuthorFeed, AppBskyFeedGetAuthorFeed as GetAuthorFeed,
RichText, AppBskyFeedGetFeed as GetCustomFeed,
jsonToLex,
} from '@atproto/api' } from '@atproto/api'
import AwaitLock from 'await-lock' import AwaitLock from 'await-lock'
import {bundleAsync} from 'lib/async/bundle' import {bundleAsync} from 'lib/async/bundle'
@ -19,269 +16,11 @@ import {
mergePosts, mergePosts,
} from 'lib/api/build-suggested-posts' } from 'lib/api/build-suggested-posts'
import {FeedTuner, FeedViewPostsSlice} from 'lib/api/feed-manip' import {FeedTuner, FeedViewPostsSlice} from 'lib/api/feed-manip'
import {updateDataOptimistically} from 'lib/async/revertible' import {PostsFeedSliceModel} from './post'
import {PostLabelInfo, PostModeration} from 'lib/labeling/types'
import {
getEmbedLabels,
getEmbedMuted,
getEmbedMutedByList,
getEmbedBlocking,
getEmbedBlockedBy,
getPostModeration,
mergePostModerations,
filterAccountLabels,
filterProfileLabels,
} from 'lib/labeling/helpers'
type FeedViewPost = AppBskyFeedDefs.FeedViewPost
type ReasonRepost = AppBskyFeedDefs.ReasonRepost
type PostView = AppBskyFeedDefs.PostView
const PAGE_SIZE = 30 const PAGE_SIZE = 30
let _idCounter = 0 let _idCounter = 0
export class PostsFeedItemModel {
// ui state
_reactKey: string = ''
// data
post: PostView
postRecord?: AppBskyFeedPost.Record
reply?: FeedViewPost['reply']
reason?: FeedViewPost['reason']
richText?: RichText
constructor(
public rootStore: RootStoreModel,
reactKey: string,
v: FeedViewPost,
) {
this._reactKey = reactKey
this.post = v.post
if (AppBskyFeedPost.isRecord(this.post.record)) {
const valid = AppBskyFeedPost.validateRecord(this.post.record)
if (valid.success) {
this.postRecord = this.post.record
this.richText = new RichText(this.postRecord, {cleanNewlines: true})
} else {
this.postRecord = undefined
this.richText = undefined
rootStore.log.warn(
'Received an invalid app.bsky.feed.post record',
valid.error,
)
}
} else {
this.postRecord = undefined
this.richText = undefined
rootStore.log.warn(
'app.bsky.feed.getTimeline or app.bsky.feed.getAuthorFeed served an unexpected record type',
this.post.record,
)
}
this.reply = v.reply
this.reason = v.reason
makeAutoObservable(this, {rootStore: false})
}
get rootUri(): string {
if (this.reply?.root.uri) {
return this.reply.root.uri
}
return this.post.uri
}
get isThreadMuted() {
return this.rootStore.mutedThreads.uris.has(this.rootUri)
}
get labelInfo(): PostLabelInfo {
return {
postLabels: (this.post.labels || []).concat(
getEmbedLabels(this.post.embed),
),
accountLabels: filterAccountLabels(this.post.author.labels),
profileLabels: filterProfileLabels(this.post.author.labels),
isMuted:
this.post.author.viewer?.muted ||
getEmbedMuted(this.post.embed) ||
false,
mutedByList:
this.post.author.viewer?.mutedByList ||
getEmbedMutedByList(this.post.embed),
isBlocking:
!!this.post.author.viewer?.blocking ||
getEmbedBlocking(this.post.embed) ||
false,
isBlockedBy:
!!this.post.author.viewer?.blockedBy ||
getEmbedBlockedBy(this.post.embed) ||
false,
}
}
get moderation(): PostModeration {
return getPostModeration(this.rootStore, this.labelInfo)
}
copy(v: FeedViewPost) {
this.post = v.post
this.reply = v.reply
this.reason = v.reason
}
copyMetrics(v: FeedViewPost) {
this.post.replyCount = v.post.replyCount
this.post.repostCount = v.post.repostCount
this.post.likeCount = v.post.likeCount
this.post.viewer = v.post.viewer
}
get reasonRepost(): ReasonRepost | undefined {
if (this.reason?.$type === 'app.bsky.feed.defs#reasonRepost') {
return this.reason as ReasonRepost
}
}
async toggleLike() {
this.post.viewer = this.post.viewer || {}
if (this.post.viewer.like) {
const url = this.post.viewer.like
await updateDataOptimistically(
this.post,
() => {
this.post.likeCount = (this.post.likeCount || 0) - 1
this.post.viewer!.like = undefined
},
() => this.rootStore.agent.deleteLike(url),
)
} else {
await updateDataOptimistically(
this.post,
() => {
this.post.likeCount = (this.post.likeCount || 0) + 1
this.post.viewer!.like = 'pending'
},
() => this.rootStore.agent.like(this.post.uri, this.post.cid),
res => {
this.post.viewer!.like = res.uri
},
)
}
}
async toggleRepost() {
this.post.viewer = this.post.viewer || {}
if (this.post.viewer?.repost) {
const url = this.post.viewer.repost
await updateDataOptimistically(
this.post,
() => {
this.post.repostCount = (this.post.repostCount || 0) - 1
this.post.viewer!.repost = undefined
},
() => this.rootStore.agent.deleteRepost(url),
)
} else {
await updateDataOptimistically(
this.post,
() => {
this.post.repostCount = (this.post.repostCount || 0) + 1
this.post.viewer!.repost = 'pending'
},
() => this.rootStore.agent.repost(this.post.uri, this.post.cid),
res => {
this.post.viewer!.repost = res.uri
},
)
}
}
async toggleThreadMute() {
if (this.isThreadMuted) {
this.rootStore.mutedThreads.uris.delete(this.rootUri)
} else {
this.rootStore.mutedThreads.uris.add(this.rootUri)
}
}
async delete() {
await this.rootStore.agent.deletePost(this.post.uri)
this.rootStore.emitPostDeleted(this.post.uri)
}
}
export class PostsFeedSliceModel {
// ui state
_reactKey: string = ''
// data
items: PostsFeedItemModel[] = []
constructor(
public rootStore: RootStoreModel,
reactKey: string,
slice: FeedViewPostsSlice,
) {
this._reactKey = reactKey
for (const item of slice.items) {
this.items.push(
new PostsFeedItemModel(rootStore, `item-${_idCounter++}`, item),
)
}
makeAutoObservable(this, {rootStore: false})
}
get uri() {
if (this.isReply) {
return this.items[1].post.uri
}
return this.items[0].post.uri
}
get isThread() {
return (
this.items.length > 1 &&
this.items.every(
item => item.post.author.did === this.items[0].post.author.did,
)
)
}
get isReply() {
return this.items.length > 1 && !this.isThread
}
get rootItem() {
if (this.isReply) {
return this.items[1]
}
return this.items[0]
}
get moderation() {
return mergePostModerations(this.items.map(item => item.moderation))
}
containsUri(uri: string) {
return !!this.items.find(item => item.post.uri === uri)
}
isThreadParentAt(i: number) {
if (this.items.length === 1) {
return false
}
return i < this.items.length - 1
}
isThreadChildAt(i: number) {
if (this.items.length === 1) {
return false
}
return i > 0
}
}
export class PostsFeedModel { export class PostsFeedModel {
// state // state
isLoading = false isLoading = false
@ -297,6 +36,7 @@ export class PostsFeedModel {
loadMoreCursor: string | undefined loadMoreCursor: string | undefined
pollCursor: string | undefined pollCursor: string | undefined
tuner = new FeedTuner() tuner = new FeedTuner()
pageSize = PAGE_SIZE
// used to linearize async modifications to state // used to linearize async modifications to state
lock = new AwaitLock() lock = new AwaitLock()
@ -309,8 +49,11 @@ export class PostsFeedModel {
constructor( constructor(
public rootStore: RootStoreModel, public rootStore: RootStoreModel,
public feedType: 'home' | 'author' | 'suggested' | 'goodstuff', public feedType: 'home' | 'author' | 'suggested' | 'custom',
params: GetTimeline.QueryParams | GetAuthorFeed.QueryParams, params:
| GetTimeline.QueryParams
| GetAuthorFeed.QueryParams
| GetCustomFeed.QueryParams,
) { ) {
makeAutoObservable( makeAutoObservable(
this, this,
@ -387,10 +130,9 @@ export class PostsFeedModel {
} }
get feedTuners() { get feedTuners() {
if (this.feedType === 'goodstuff') { if (this.feedType === 'custom') {
return [ return [
FeedTuner.dedupReposts, FeedTuner.dedupReposts,
FeedTuner.likedRepliesOnly,
FeedTuner.preferredLangOnly( FeedTuner.preferredLangOnly(
this.rootStore.preferences.contentLanguages, this.rootStore.preferences.contentLanguages,
), ),
@ -416,7 +158,7 @@ export class PostsFeedModel {
this.tuner.reset() this.tuner.reset()
this._xLoading(isRefreshing) this._xLoading(isRefreshing)
try { try {
const res = await this._getFeed({limit: PAGE_SIZE}) const res = await this._getFeed({limit: this.pageSize})
await this._replaceAll(res) await this._replaceAll(res)
this._xIdle() this._xIdle()
} catch (e: any) { } catch (e: any) {
@ -455,7 +197,7 @@ export class PostsFeedModel {
try { try {
const res = await this._getFeed({ const res = await this._getFeed({
cursor: this.loadMoreCursor, cursor: this.loadMoreCursor,
limit: PAGE_SIZE, limit: this.pageSize,
}) })
await this._appendAll(res) await this._appendAll(res)
this._xIdle() this._xIdle()
@ -524,7 +266,7 @@ export class PostsFeedModel {
if (this.hasNewLatest || this.feedType === 'suggested') { if (this.hasNewLatest || this.feedType === 'suggested') {
return return
} }
const res = await this._getFeed({limit: PAGE_SIZE}) const res = await this._getFeed({limit: this.pageSize})
const tuner = new FeedTuner() const tuner = new FeedTuner()
const slices = tuner.tune(res.data.feed, this.feedTuners) const slices = tuner.tune(res.data.feed, this.feedTuners)
this.setHasNewLatest(slices[0]?.uri !== this.slices[0]?.uri) this.setHasNewLatest(slices[0]?.uri !== this.slices[0]?.uri)
@ -599,13 +341,15 @@ export class PostsFeedModel {
// helper functions // helper functions
// = // =
async _replaceAll(res: GetTimeline.Response | GetAuthorFeed.Response) { async _replaceAll(
res: GetTimeline.Response | GetAuthorFeed.Response | GetCustomFeed.Response,
) {
this.pollCursor = res.data.feed[0]?.post.uri this.pollCursor = res.data.feed[0]?.post.uri
return this._appendAll(res, true) return this._appendAll(res, true)
} }
async _appendAll( async _appendAll(
res: GetTimeline.Response | GetAuthorFeed.Response, res: GetTimeline.Response | GetAuthorFeed.Response | GetCustomFeed.Response,
replace = false, replace = false,
) { ) {
this.loadMoreCursor = res.data.cursor this.loadMoreCursor = res.data.cursor
@ -644,7 +388,9 @@ export class PostsFeedModel {
}) })
} }
_updateAll(res: GetTimeline.Response | GetAuthorFeed.Response) { _updateAll(
res: GetTimeline.Response | GetAuthorFeed.Response | GetCustomFeed.Response,
) {
for (const item of res.data.feed) { for (const item of res.data.feed) {
const existingSlice = this.slices.find(slice => const existingSlice = this.slices.find(slice =>
slice.containsUri(item.post.uri), slice.containsUri(item.post.uri),
@ -661,8 +407,13 @@ export class PostsFeedModel {
} }
protected async _getFeed( protected async _getFeed(
params: GetTimeline.QueryParams | GetAuthorFeed.QueryParams = {}, params:
): Promise<GetTimeline.Response | GetAuthorFeed.Response> { | GetTimeline.QueryParams
| GetAuthorFeed.QueryParams
| GetCustomFeed.QueryParams,
): Promise<
GetTimeline.Response | GetAuthorFeed.Response | GetCustomFeed.Response
> {
params = Object.assign({}, this.params, params) params = Object.assign({}, this.params, params)
if (this.feedType === 'suggested') { if (this.feedType === 'suggested') {
const responses = await getMultipleAuthorsPosts( const responses = await getMultipleAuthorsPosts(
@ -684,61 +435,31 @@ export class PostsFeedModel {
} }
} else if (this.feedType === 'home') { } else if (this.feedType === 'home') {
return this.rootStore.agent.getTimeline(params as GetTimeline.QueryParams) return this.rootStore.agent.getTimeline(params as GetTimeline.QueryParams)
} else if (this.feedType === 'goodstuff') { } else if (this.feedType === 'custom') {
const res = await getGoodStuff( this.checkIfCustomFeedIsOnlineAndValid(
this.rootStore.session.currentSession?.accessJwt || '', params as GetCustomFeed.QueryParams,
params as GetTimeline.QueryParams,
) )
res.data.feed = (res.data.feed || []).filter( return this.rootStore.agent.app.bsky.feed.getFeed(
item => !item.post.author.viewer?.muted, params as GetCustomFeed.QueryParams,
) )
return res
} else { } else {
return this.rootStore.agent.getAuthorFeed( return this.rootStore.agent.getAuthorFeed(
params as GetAuthorFeed.QueryParams, params as GetAuthorFeed.QueryParams,
) )
} }
} }
}
// HACK private async checkIfCustomFeedIsOnlineAndValid(
// temporary off-spec route to get the good stuff params: GetCustomFeed.QueryParams,
// -prf ) {
async function getGoodStuff( const res = await this.rootStore.agent.app.bsky.feed.getFeedGenerator({
accessJwt: string, feed: params.feed,
params: GetTimeline.QueryParams, })
): Promise<GetTimeline.Response> { if (!res.data.isOnline || !res.data.isValid) {
const controller = new AbortController() runInAction(() => {
const to = setTimeout(() => controller.abort(), 15e3) this.error =
'This custom feed is not online or may be experiencing issues.'
const uri = new URL('https://bsky.social/xrpc/app.bsky.unspecced.getPopular') })
let k: keyof GetTimeline.QueryParams
for (k in params) {
if (typeof params[k] !== 'undefined') {
uri.searchParams.set(k, String(params[k]))
} }
} }
const res = await fetch(String(uri), {
method: 'get',
headers: {
accept: 'application/json',
authorization: `Bearer ${accessJwt}`,
},
signal: controller.signal,
})
const resHeaders: Record<string, string> = {}
res.headers.forEach((value: string, key: string) => {
resHeaders[key] = value
})
let resBody = await res.json()
clearTimeout(to)
return {
success: res.status === 200,
headers: resHeaders,
data: jsonToLex(resBody),
}
} }

View File

@ -0,0 +1,120 @@
import {makeAutoObservable} from 'mobx'
import {AppBskyFeedGetActorFeeds as GetActorFeeds} from '@atproto/api'
import {RootStoreModel} from '../root-store'
import {bundleAsync} from 'lib/async/bundle'
import {cleanError} from 'lib/strings/errors'
import {CustomFeedModel} from '../feeds/custom-feed'
const PAGE_SIZE = 30
export class ActorFeedsModel {
// state
isLoading = false
isRefreshing = false
hasLoaded = false
error = ''
hasMore = true
loadMoreCursor?: string
// data
feeds: CustomFeedModel[] = []
constructor(
public rootStore: RootStoreModel,
public params: GetActorFeeds.QueryParams,
) {
makeAutoObservable(
this,
{
rootStore: false,
},
{autoBind: true},
)
}
get hasContent() {
return this.feeds.length > 0
}
get hasError() {
return this.error !== ''
}
get isEmpty() {
return this.hasLoaded && !this.hasContent
}
// public api
// =
async refresh() {
return this.loadMore(true)
}
clear() {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = false
this.error = ''
this.hasMore = true
this.loadMoreCursor = undefined
this.feeds = []
}
loadMore = bundleAsync(async (replace: boolean = false) => {
if (!replace && !this.hasMore) {
return
}
this._xLoading(replace)
try {
const res = await this.rootStore.agent.app.bsky.feed.getActorFeeds({
actor: this.params.actor,
limit: PAGE_SIZE,
cursor: replace ? undefined : this.loadMoreCursor,
})
if (replace) {
this._replaceAll(res)
} else {
this._appendAll(res)
}
this._xIdle()
} catch (e: any) {
this._xIdle(e)
}
})
// state transitions
// =
_xLoading(isRefreshing = false) {
this.isLoading = true
this.isRefreshing = isRefreshing
this.error = ''
}
_xIdle(err?: any) {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = true
this.error = cleanError(err)
if (err) {
this.rootStore.log.error('Failed to fetch user followers', err)
}
}
// helper functions
// =
_replaceAll(res: GetActorFeeds.Response) {
this.feeds = []
this._appendAll(res)
}
_appendAll(res: GetActorFeeds.Response) {
this.loadMoreCursor = res.data.cursor
this.hasMore = !!this.loadMoreCursor
for (const f of res.data.feeds) {
this.feeds.push(new CustomFeedModel(this.rootStore, f))
}
}
}

View File

@ -27,6 +27,7 @@ function genId(): string {
export class LogModel { export class LogModel {
entries: LogEntry[] = [] entries: LogEntry[] = []
timers = new Map<string, number>()
constructor() { constructor() {
makeAutoObservable(this) makeAutoObservable(this)
@ -74,6 +75,21 @@ export class LogModel {
ts: Date.now(), ts: Date.now(),
}) })
} }
time = (label = 'default') => {
this.timers.set(label, performance.now())
}
timeEnd = (label = 'default', warn = false) => {
const endTime = performance.now()
if (this.timers.has(label)) {
const elapsedTime = endTime - this.timers.get(label)!
console.log(`${label}: ${elapsedTime.toFixed(3)}ms`)
this.timers.delete(label)
} else {
warn && console.warn(`Timer with label '${label}' does not exist.`)
}
}
} }
function detailsToStr(details?: any) { function detailsToStr(details?: any) {

View File

@ -8,6 +8,7 @@ import {PostsFeedModel} from './feeds/posts'
import {NotificationsFeedModel} from './feeds/notifications' import {NotificationsFeedModel} from './feeds/notifications'
import {MyFollowsCache} from './cache/my-follows' import {MyFollowsCache} from './cache/my-follows'
import {isObj, hasProp} from 'lib/type-guards' import {isObj, hasProp} from 'lib/type-guards'
import {SavedFeedsModel} from './ui/saved-feeds'
const PROFILE_UPDATE_INTERVAL = 10 * 60 * 1e3 // 10min const PROFILE_UPDATE_INTERVAL = 10 * 60 * 1e3 // 10min
const NOTIFS_UPDATE_INTERVAL = 30 * 1e3 // 30sec const NOTIFS_UPDATE_INTERVAL = 30 * 1e3 // 30sec
@ -21,6 +22,7 @@ export class MeModel {
followsCount: number | undefined followsCount: number | undefined
followersCount: number | undefined followersCount: number | undefined
mainFeed: PostsFeedModel mainFeed: PostsFeedModel
savedFeeds: SavedFeedsModel
notifications: NotificationsFeedModel notifications: NotificationsFeedModel
follows: MyFollowsCache follows: MyFollowsCache
invites: ComAtprotoServerDefs.InviteCode[] = [] invites: ComAtprotoServerDefs.InviteCode[] = []
@ -43,12 +45,14 @@ export class MeModel {
}) })
this.notifications = new NotificationsFeedModel(this.rootStore) this.notifications = new NotificationsFeedModel(this.rootStore)
this.follows = new MyFollowsCache(this.rootStore) this.follows = new MyFollowsCache(this.rootStore)
this.savedFeeds = new SavedFeedsModel(this.rootStore)
} }
clear() { clear() {
this.mainFeed.clear() this.mainFeed.clear()
this.notifications.clear() this.notifications.clear()
this.follows.clear() this.follows.clear()
this.savedFeeds.clear()
this.did = '' this.did = ''
this.handle = '' this.handle = ''
this.displayName = '' this.displayName = ''
@ -110,6 +114,7 @@ export class MeModel {
/* dont await */ this.notifications.setup().catch(e => { /* dont await */ this.notifications.setup().catch(e => {
this.rootStore.log.error('Failed to setup notifications model', e) this.rootStore.log.error('Failed to setup notifications model', e)
}) })
/* dont await */ this.savedFeeds.refresh(true)
this.rootStore.emitSessionLoaded() this.rootStore.emitSessionLoaded()
await this.fetchInviteCodes() await this.fetchInviteCodes()
await this.fetchAppPasswords() await this.fetchAppPasswords()
@ -119,6 +124,7 @@ export class MeModel {
} }
async updateIfNeeded() { async updateIfNeeded() {
/* dont await */ this.savedFeeds.refresh(true)
if (Date.now() - this.lastProfileStateUpdate > PROFILE_UPDATE_INTERVAL) { if (Date.now() - this.lastProfileStateUpdate > PROFILE_UPDATE_INTERVAL) {
this.rootStore.log.debug('Updating me profile information') this.rootStore.log.debug('Updating me profile information')
this.lastProfileStateUpdate = Date.now() this.lastProfileStateUpdate = Date.now()

View File

@ -135,7 +135,7 @@ export class ImageModel implements RNImage {
// Only for mobile // Only for mobile
async crop() { async crop() {
try { try {
const cropped = await openCropper({ const cropped = await openCropper(this.rootStore, {
mediaType: 'photo', mediaType: 'photo',
path: this.path, path: this.path,
freeStyleCropEnabled: true, freeStyleCropEnabled: true,

View File

@ -11,6 +11,7 @@ import {
ALWAYS_FILTER_LABEL_GROUP, ALWAYS_FILTER_LABEL_GROUP,
ALWAYS_WARN_LABEL_GROUP, ALWAYS_WARN_LABEL_GROUP,
} from 'lib/labeling/const' } from 'lib/labeling/const'
import {DEFAULT_FEEDS} from 'lib/constants'
import {isIOS} from 'platform/detection' import {isIOS} from 'platform/detection'
const deviceLocales = getLocales() const deviceLocales = getLocales()
@ -25,6 +26,7 @@ const LABEL_GROUPS = [
'spam', 'spam',
'impersonation', 'impersonation',
] ]
const VISIBILITY_VALUES = ['show', 'warn', 'hide']
export class LabelPreferencesModel { export class LabelPreferencesModel {
nsfw: LabelPreference = 'hide' nsfw: LabelPreference = 'hide'
@ -45,6 +47,8 @@ export class PreferencesModel {
contentLanguages: string[] = contentLanguages: string[] =
deviceLocales?.map?.(locale => locale.languageCode) || [] deviceLocales?.map?.(locale => locale.languageCode) || []
contentLabels = new LabelPreferencesModel() contentLabels = new LabelPreferencesModel()
savedFeeds: string[] = []
pinnedFeeds: string[] = []
constructor(public rootStore: RootStoreModel) { constructor(public rootStore: RootStoreModel) {
makeAutoObservable(this, {}, {autoBind: true}) makeAutoObservable(this, {}, {autoBind: true})
@ -54,9 +58,16 @@ export class PreferencesModel {
return { return {
contentLanguages: this.contentLanguages, contentLanguages: this.contentLanguages,
contentLabels: this.contentLabels, contentLabels: this.contentLabels,
savedFeeds: this.savedFeeds,
pinnedFeeds: this.pinnedFeeds,
} }
} }
/**
* The function hydrates an object with properties related to content languages, labels, saved feeds,
* and pinned feeds that it gets from the parameter `v` (probably local storage)
* @param {unknown} v - the data object to hydrate from
*/
hydrate(v: unknown) { hydrate(v: unknown) {
if (isObj(v)) { if (isObj(v)) {
if ( if (
@ -72,10 +83,29 @@ export class PreferencesModel {
// default to the device languages // default to the device languages
this.contentLanguages = deviceLocales.map(locale => locale.languageCode) this.contentLanguages = deviceLocales.map(locale => locale.languageCode)
} }
if (
hasProp(v, 'savedFeeds') &&
Array.isArray(v.savedFeeds) &&
typeof v.savedFeeds.every(item => typeof item === 'string')
) {
this.savedFeeds = v.savedFeeds
}
if (
hasProp(v, 'pinnedFeeds') &&
Array.isArray(v.pinnedFeeds) &&
typeof v.pinnedFeeds.every(item => typeof item === 'string')
) {
this.pinnedFeeds = v.pinnedFeeds
}
} }
} }
/**
* This function fetches preferences and sets defaults for missing items.
*/
async sync() { async sync() {
// fetch preferences
let hasSavedFeedsPref = false
const res = await this.rootStore.agent.app.bsky.actor.getPreferences({}) const res = await this.rootStore.agent.app.bsky.actor.getPreferences({})
runInAction(() => { runInAction(() => {
for (const pref of res.data.preferences) { for (const pref of res.data.preferences) {
@ -88,22 +118,83 @@ export class PreferencesModel {
AppBskyActorDefs.isContentLabelPref(pref) && AppBskyActorDefs.isContentLabelPref(pref) &&
AppBskyActorDefs.validateAdultContentPref(pref).success AppBskyActorDefs.validateAdultContentPref(pref).success
) { ) {
if (LABEL_GROUPS.includes(pref.label)) { if (
this.contentLabels[pref.label] = pref.visibility LABEL_GROUPS.includes(pref.label) &&
VISIBILITY_VALUES.includes(pref.visibility)
) {
this.contentLabels[pref.label as keyof LabelPreferencesModel] =
pref.visibility as LabelPreference
} }
} else if (
AppBskyActorDefs.isSavedFeedsPref(pref) &&
AppBskyActorDefs.validateSavedFeedsPref(pref).success
) {
this.savedFeeds = pref.saved
this.pinnedFeeds = pref.pinned
hasSavedFeedsPref = true
} }
} }
}) })
// set defaults on missing items
if (!hasSavedFeedsPref) {
const {saved, pinned} = await DEFAULT_FEEDS(
this.rootStore.agent.service.toString(),
(handle: string) =>
this.rootStore.agent
.resolveHandle({handle})
.then(({data}) => data.did),
)
runInAction(() => {
this.savedFeeds = saved
this.pinnedFeeds = pinned
})
res.data.preferences.push({
$type: 'app.bsky.actor.defs#savedFeedsPref',
saved,
pinned,
})
await this.rootStore.agent.app.bsky.actor.putPreferences({
preferences: res.data.preferences,
})
/* dont await */ this.rootStore.me.savedFeeds.refresh()
}
} }
async update(cb: (prefs: AppBskyActorDefs.Preferences) => void) { /**
* This function updates the preferences of a user and allows for a callback function to be executed
* before the update.
* @param cb - cb is a callback function that takes in a single parameter of type
* AppBskyActorDefs.Preferences and returns either a boolean or void. This callback function is used to
* update the preferences of the user. The function is called with the current preferences as an
* argument and if the callback returns false, the preferences are not updated.
* @returns void
*/
async update(cb: (prefs: AppBskyActorDefs.Preferences) => boolean | void) {
const res = await this.rootStore.agent.app.bsky.actor.getPreferences({}) const res = await this.rootStore.agent.app.bsky.actor.getPreferences({})
cb(res.data.preferences) if (cb(res.data.preferences) === false) {
return
}
await this.rootStore.agent.app.bsky.actor.putPreferences({ await this.rootStore.agent.app.bsky.actor.putPreferences({
preferences: res.data.preferences, preferences: res.data.preferences,
}) })
} }
/**
* This function resets the preferences to an empty array of no preferences.
*/
async reset() {
runInAction(() => {
this.contentLabels = new LabelPreferencesModel()
this.contentLanguages = deviceLocales.map(locale => locale.languageCode)
this.savedFeeds = []
this.pinnedFeeds = []
})
await this.rootStore.agent.app.bsky.actor.putPreferences({
preferences: [],
})
}
hasContentLanguage(code2: string) { hasContentLanguage(code2: string) {
return this.contentLanguages.includes(code2) return this.contentLanguages.includes(code2)
} }
@ -200,4 +291,62 @@ export class PreferencesModel {
} }
return res return res
} }
setFeeds(saved: string[], pinned: string[]) {
this.savedFeeds = saved
this.pinnedFeeds = pinned
}
async setSavedFeeds(saved: string[], pinned: string[]) {
const oldSaved = this.savedFeeds
const oldPinned = this.pinnedFeeds
this.setFeeds(saved, pinned)
try {
await this.update((prefs: AppBskyActorDefs.Preferences) => {
const existing = prefs.find(
pref =>
AppBskyActorDefs.isSavedFeedsPref(pref) &&
AppBskyActorDefs.validateSavedFeedsPref(pref).success,
)
if (existing) {
existing.saved = saved
existing.pinned = pinned
} else {
prefs.push({
$type: 'app.bsky.actor.defs#savedFeedsPref',
saved,
pinned,
})
}
})
} catch (e) {
runInAction(() => {
this.savedFeeds = oldSaved
this.pinnedFeeds = oldPinned
})
throw e
}
}
async addSavedFeed(v: string) {
return this.setSavedFeeds([...this.savedFeeds, v], this.pinnedFeeds)
}
async removeSavedFeed(v: string) {
return this.setSavedFeeds(
this.savedFeeds.filter(uri => uri !== v),
this.pinnedFeeds.filter(uri => uri !== v),
)
}
async addPinnedFeed(v: string) {
return this.setSavedFeeds(this.savedFeeds, [...this.pinnedFeeds, v])
}
async removePinnedFeed(v: string) {
return this.setSavedFeeds(
this.savedFeeds,
this.pinnedFeeds.filter(uri => uri !== v),
)
}
} }

View File

@ -2,20 +2,16 @@ import {makeAutoObservable} from 'mobx'
import {RootStoreModel} from '../root-store' import {RootStoreModel} from '../root-store'
import {ProfileModel} from '../content/profile' import {ProfileModel} from '../content/profile'
import {PostsFeedModel} from '../feeds/posts' import {PostsFeedModel} from '../feeds/posts'
import {ActorFeedsModel} from '../lists/actor-feeds'
import {ListsListModel} from '../lists/lists-list' import {ListsListModel} from '../lists/lists-list'
export enum Sections { export enum Sections {
Posts = 'Posts', Posts = 'Posts',
PostsWithReplies = 'Posts & replies', PostsWithReplies = 'Posts & replies',
CustomAlgorithms = 'Feeds',
Lists = 'Lists', Lists = 'Lists',
} }
const USER_SELECTOR_ITEMS = [
Sections.Posts,
Sections.PostsWithReplies,
Sections.Lists,
]
export interface ProfileUiParams { export interface ProfileUiParams {
user: string user: string
} }
@ -28,6 +24,7 @@ export class ProfileUiModel {
// data // data
profile: ProfileModel profile: ProfileModel
feed: PostsFeedModel feed: PostsFeedModel
algos: ActorFeedsModel
lists: ListsListModel lists: ListsListModel
// ui state // ui state
@ -50,10 +47,11 @@ export class ProfileUiModel {
actor: params.user, actor: params.user,
limit: 10, limit: 10,
}) })
this.algos = new ActorFeedsModel(rootStore, {actor: params.user})
this.lists = new ListsListModel(rootStore, params.user) this.lists = new ListsListModel(rootStore, params.user)
} }
get currentView(): PostsFeedModel | ListsListModel { get currentView(): PostsFeedModel | ActorFeedsModel | ListsListModel {
if ( if (
this.selectedView === Sections.Posts || this.selectedView === Sections.Posts ||
this.selectedView === Sections.PostsWithReplies this.selectedView === Sections.PostsWithReplies
@ -62,6 +60,9 @@ export class ProfileUiModel {
} else if (this.selectedView === Sections.Lists) { } else if (this.selectedView === Sections.Lists) {
return this.lists return this.lists
} }
if (this.selectedView === Sections.CustomAlgorithms) {
return this.algos
}
throw new Error(`Invalid selector value: ${this.selectedViewIndex}`) throw new Error(`Invalid selector value: ${this.selectedViewIndex}`)
} }
@ -75,7 +76,14 @@ export class ProfileUiModel {
} }
get selectorItems() { get selectorItems() {
return USER_SELECTOR_ITEMS const items = [Sections.Posts, Sections.PostsWithReplies]
if (this.algos.hasLoaded && !this.algos.isEmpty) {
items.push(Sections.CustomAlgorithms)
}
if (this.lists.hasLoaded && !this.lists.isEmpty) {
items.push(Sections.Lists)
}
return items
} }
get selectedView() { get selectedView() {
@ -84,9 +92,11 @@ export class ProfileUiModel {
get uiItems() { get uiItems() {
let arr: any[] = [] let arr: any[] = []
// if loading, return loading item to show loading spinner
if (this.isInitialLoading) { if (this.isInitialLoading) {
arr = arr.concat([ProfileUiModel.LOADING_ITEM]) arr = arr.concat([ProfileUiModel.LOADING_ITEM])
} else if (this.currentView.hasError) { } else if (this.currentView.hasError) {
// if error, return error item to show error message
arr = arr.concat([ arr = arr.concat([
{ {
_reactKey: '__error__', _reactKey: '__error__',
@ -94,12 +104,16 @@ export class ProfileUiModel {
}, },
]) ])
} else { } else {
// not loading, no error, show content
if ( if (
this.selectedView === Sections.Posts || this.selectedView === Sections.Posts ||
this.selectedView === Sections.PostsWithReplies this.selectedView === Sections.PostsWithReplies ||
this.selectedView === Sections.CustomAlgorithms
) { ) {
if (this.feed.hasContent) { if (this.feed.hasContent) {
if (this.selectedView === Sections.Posts) { if (this.selectedView === Sections.CustomAlgorithms) {
arr = this.algos.feeds
} else if (this.selectedView === Sections.Posts) {
arr = this.feed.nonReplyFeed arr = this.feed.nonReplyFeed
} else { } else {
arr = this.feed.slices.slice() arr = this.feed.slices.slice()
@ -117,6 +131,7 @@ export class ProfileUiModel {
arr = arr.concat([ProfileUiModel.EMPTY_ITEM]) arr = arr.concat([ProfileUiModel.EMPTY_ITEM])
} }
} else { } else {
// fallback, add empty item, to show empty message
arr = arr.concat([ProfileUiModel.EMPTY_ITEM]) arr = arr.concat([ProfileUiModel.EMPTY_ITEM])
} }
} }
@ -151,6 +166,7 @@ export class ProfileUiModel {
.setup() .setup()
.catch(err => this.rootStore.log.error('Failed to fetch feed', err)), .catch(err => this.rootStore.log.error('Failed to fetch feed', err)),
]) ])
this.algos.refresh()
// HACK: need to use the DID as a param, not the username -prf // HACK: need to use the DID as a param, not the username -prf
this.lists.source = this.profile.did this.lists.source = this.profile.did
this.lists this.lists

View File

@ -0,0 +1,185 @@
import {makeAutoObservable, runInAction} from 'mobx'
import {AppBskyFeedDefs} from '@atproto/api'
import {RootStoreModel} from '../root-store'
import {bundleAsync} from 'lib/async/bundle'
import {cleanError} from 'lib/strings/errors'
import {CustomFeedModel} from '../feeds/custom-feed'
export class SavedFeedsModel {
// state
isLoading = false
isRefreshing = false
hasLoaded = false
error = ''
// data
feeds: CustomFeedModel[] = []
constructor(public rootStore: RootStoreModel) {
makeAutoObservable(
this,
{
rootStore: false,
},
{autoBind: true},
)
}
get hasContent() {
return this.feeds.length > 0
}
get hasError() {
return this.error !== ''
}
get isEmpty() {
return this.hasLoaded && !this.hasContent
}
get pinned() {
return this.rootStore.preferences.pinnedFeeds
.map(uri => this.feeds.find(f => f.uri === uri) as CustomFeedModel)
.filter(Boolean)
}
get unpinned() {
return this.feeds.filter(f => !this.isPinned(f))
}
get all() {
return this.pinned.concat(this.unpinned)
}
get pinnedFeedNames() {
return this.pinned.map(f => f.displayName)
}
// public api
// =
clear() {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = false
this.error = ''
this.feeds = []
}
refresh = bundleAsync(async (quietRefresh = false) => {
this._xLoading(!quietRefresh)
try {
let feeds: AppBskyFeedDefs.GeneratorView[] = []
for (
let i = 0;
i < this.rootStore.preferences.savedFeeds.length;
i += 25
) {
const res = await this.rootStore.agent.app.bsky.feed.getFeedGenerators({
feeds: this.rootStore.preferences.savedFeeds.slice(i, 25),
})
feeds = feeds.concat(res.data.feeds)
}
runInAction(() => {
this.feeds = feeds.map(f => new CustomFeedModel(this.rootStore, f))
})
this._xIdle()
} catch (e: any) {
this._xIdle(e)
}
})
async save(feed: CustomFeedModel) {
try {
await feed.save()
runInAction(() => {
this.feeds = [
...this.feeds,
new CustomFeedModel(this.rootStore, feed.data),
]
})
} catch (e: any) {
this.rootStore.log.error('Failed to save feed', e)
}
}
async unsave(feed: CustomFeedModel) {
const uri = feed.uri
try {
if (this.isPinned(feed)) {
await this.rootStore.preferences.removePinnedFeed(uri)
}
await feed.unsave()
runInAction(() => {
this.feeds = this.feeds.filter(f => f.data.uri !== uri)
})
} catch (e: any) {
this.rootStore.log.error('Failed to unsave feed', e)
}
}
async togglePinnedFeed(feed: CustomFeedModel) {
if (!this.isPinned(feed)) {
return this.rootStore.preferences.addPinnedFeed(feed.uri)
} else {
return this.rootStore.preferences.removePinnedFeed(feed.uri)
}
}
async reorderPinnedFeeds(feeds: CustomFeedModel[]) {
return this.rootStore.preferences.setSavedFeeds(
this.rootStore.preferences.savedFeeds,
feeds.filter(feed => this.isPinned(feed)).map(feed => feed.uri),
)
}
isPinned(feedOrUri: CustomFeedModel | string) {
let uri: string
if (typeof feedOrUri === 'string') {
uri = feedOrUri
} else {
uri = feedOrUri.uri
}
return this.rootStore.preferences.pinnedFeeds.includes(uri)
}
async movePinnedFeed(item: CustomFeedModel, direction: 'up' | 'down') {
const pinned = this.rootStore.preferences.pinnedFeeds.slice()
const index = pinned.indexOf(item.uri)
if (index === -1) {
return
}
if (direction === 'up' && index !== 0) {
const temp = pinned[index]
pinned[index] = pinned[index - 1]
pinned[index - 1] = temp
} else if (direction === 'down' && index < pinned.length - 1) {
const temp = pinned[index]
pinned[index] = pinned[index + 1]
pinned[index + 1] = temp
}
await this.rootStore.preferences.setSavedFeeds(
this.rootStore.preferences.savedFeeds,
pinned,
)
}
// state transitions
// =
_xLoading(isRefreshing = false) {
this.isLoading = true
this.isRefreshing = isRefreshing
this.error = ''
}
_xIdle(err?: any) {
this.isLoading = false
this.isRefreshing = false
this.hasLoaded = true
this.error = cleanError(err)
if (err) {
this.rootStore.log.error('Failed to fetch user feeds', err)
}
}
}

View File

@ -119,7 +119,7 @@ export type Modal =
// Moderation // Moderation
| ReportAccountModal | ReportAccountModal
| ReportPostModal | ReportPostModal
| CreateMuteListModal | CreateOrEditMuteListModal
| ListAddRemoveUserModal | ListAddRemoveUserModal
// Posts // Posts

View File

@ -2,9 +2,9 @@ import {useState, useEffect} from 'react'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import * as apilib from 'lib/api/index' import * as apilib from 'lib/api/index'
import {getLinkMeta} from 'lib/link-meta/link-meta' import {getLinkMeta} from 'lib/link-meta/link-meta'
import {getPostAsQuote} from 'lib/link-meta/bsky' import {getPostAsQuote, getFeedAsEmbed} from 'lib/link-meta/bsky'
import {downloadAndResize} from 'lib/media/manip' import {downloadAndResize} from 'lib/media/manip'
import {isBskyPostUrl} from 'lib/strings/url-helpers' import {isBskyPostUrl, isBskyCustomFeedUrl} from 'lib/strings/url-helpers'
import {ComposerOpts} from 'state/models/ui/shell' import {ComposerOpts} from 'state/models/ui/shell'
import {POST_IMG_MAX} from 'lib/constants' import {POST_IMG_MAX} from 'lib/constants'
@ -41,6 +41,24 @@ export function useExternalLinkFetch({
setExtLink(undefined) setExtLink(undefined)
}, },
) )
} else if (isBskyCustomFeedUrl(extLink.uri)) {
getFeedAsEmbed(store, extLink.uri).then(
({embed, meta}) => {
if (aborted) {
return
}
setExtLink({
uri: extLink.uri,
isLoading: false,
meta,
embed,
})
},
err => {
store.log.error('Failed to fetch feed for embedding', {err})
setExtLink(undefined)
},
)
} else { } else {
getLinkMeta(store, extLink.uri).then(meta => { getLinkMeta(store, extLink.uri).then(meta => {
if (aborted) { if (aborted) {

View File

@ -0,0 +1,162 @@
import React from 'react'
import {
Pressable,
StyleProp,
StyleSheet,
View,
ViewStyle,
TouchableOpacity,
} from 'react-native'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {Text} from '../util/text/Text'
import {usePalette} from 'lib/hooks/usePalette'
import {s} from 'lib/styles'
import {UserAvatar} from '../util/UserAvatar'
import {observer} from 'mobx-react-lite'
import {CustomFeedModel} from 'state/models/feeds/custom-feed'
import {useNavigation} from '@react-navigation/native'
import {NavigationProp} from 'lib/routes/types'
import {useStores} from 'state/index'
import {pluralize} from 'lib/strings/helpers'
import {AtUri} from '@atproto/api'
import * as Toast from 'view/com/util/Toast'
export const CustomFeed = observer(
({
item,
style,
showSaveBtn = false,
showDescription = false,
showLikes = false,
}: {
item: CustomFeedModel
style?: StyleProp<ViewStyle>
showSaveBtn?: boolean
showDescription?: boolean
showLikes?: boolean
}) => {
const store = useStores()
const pal = usePalette('default')
const navigation = useNavigation<NavigationProp>()
const onToggleSaved = React.useCallback(async () => {
if (item.isSaved) {
store.shell.openModal({
name: 'confirm',
title: 'Remove from my feeds',
message: `Remove ${item.displayName} from my feeds?`,
onPressConfirm: async () => {
try {
await store.me.savedFeeds.unsave(item)
Toast.show('Removed from my feeds')
} catch (e) {
Toast.show('There was an issue contacting your server')
store.log.error('Failed to unsave feed', {e})
}
},
})
} else {
try {
await store.me.savedFeeds.save(item)
Toast.show('Added to my feeds')
} catch (e) {
Toast.show('There was an issue contacting your server')
store.log.error('Failed to save feed', {e})
}
}
}, [store, item])
return (
<TouchableOpacity
accessibilityRole="button"
style={[styles.container, pal.border, style]}
onPress={() => {
navigation.navigate('CustomFeed', {
name: item.data.creator.did,
rkey: new AtUri(item.data.uri).rkey,
})
}}
key={item.data.uri}>
<View style={[styles.headerContainer]}>
<View style={[s.mr10]}>
<UserAvatar type="algo" size={36} avatar={item.data.avatar} />
</View>
<View style={[styles.headerTextContainer]}>
<Text style={[pal.text, s.bold]} numberOfLines={3}>
{item.displayName}
</Text>
<Text style={[pal.textLight]} numberOfLines={3}>
by @{item.data.creator.handle}
</Text>
</View>
{showSaveBtn && (
<View>
<Pressable
accessibilityRole="button"
accessibilityLabel={
item.isSaved ? 'Remove from my feeds' : 'Add to my feeds'
}
accessibilityHint=""
onPress={onToggleSaved}
hitSlop={15}
style={styles.btn}>
{item.isSaved ? (
<FontAwesomeIcon
icon={['far', 'trash-can']}
size={19}
color={pal.colors.icon}
/>
) : (
<FontAwesomeIcon
icon="plus"
size={18}
color={pal.colors.link}
/>
)}
</Pressable>
</View>
)}
</View>
{showDescription && item.data.description ? (
<Text style={[pal.textLight, styles.description]} numberOfLines={3}>
{item.data.description}
</Text>
) : null}
{showLikes ? (
<Text type="sm-medium" style={[pal.text, pal.textLight]}>
Liked by {item.data.likeCount || 0}{' '}
{pluralize(item.data.likeCount || 0, 'user')}
</Text>
) : null}
</TouchableOpacity>
)
},
)
const styles = StyleSheet.create({
container: {
paddingHorizontal: 18,
paddingVertical: 20,
flexDirection: 'column',
flex: 1,
borderTopWidth: 1,
gap: 14,
},
headerContainer: {
flexDirection: 'row',
},
headerTextContainer: {
flexDirection: 'column',
columnGap: 4,
flex: 1,
},
description: {
flex: 1,
flexWrap: 'wrap',
},
btn: {
paddingVertical: 6,
},
})

View File

@ -60,7 +60,7 @@ export const ListCard = ({
anchorNoUnderline> anchorNoUnderline>
<View style={styles.layout}> <View style={styles.layout}>
<View style={styles.layoutAvi}> <View style={styles.layoutAvi}>
<UserAvatar size={40} avatar={list.avatar} /> <UserAvatar type="list" size={40} avatar={list.avatar} />
</View> </View>
<View style={styles.layoutContent}> <View style={styles.layoutContent}>
<Text <Text

View File

@ -341,7 +341,7 @@ const ListHeader = observer(
)} )}
</View> </View>
<View> <View>
<UserAvatar avatar={list.avatar} size={64} /> <UserAvatar type="list" avatar={list.avatar} size={64} />
</View> </View>
</View> </View>
<View style={[styles.fakeSelector, pal.border]}> <View style={[styles.fakeSelector, pal.border]}>

View File

@ -41,8 +41,8 @@ export function Component({}: {}) {
<View testID="contentLanguagesModal" style={[pal.view, styles.container]}> <View testID="contentLanguagesModal" style={[pal.view, styles.container]}>
<Text style={[pal.text, styles.title]}>Content Languages</Text> <Text style={[pal.text, styles.title]}>Content Languages</Text>
<Text style={[pal.text, styles.description]}> <Text style={[pal.text, styles.description]}>
Which languages would you like to see in the What's Hot feed? (Leave Which languages would you like to see in the your feed? (Leave them all
them all unchecked to see any language.) unchecked to see any language.)
</Text> </Text>
<ScrollView style={styles.scrollContainer}> <ScrollView style={styles.scrollContainer}>
{languages.map(lang => ( {languages.map(lang => (

View File

@ -143,6 +143,7 @@ export function Component({
<Text style={[styles.label, pal.text]}>List Avatar</Text> <Text style={[styles.label, pal.text]}>List Avatar</Text>
<View style={[styles.avi, {borderColor: pal.colors.background}]}> <View style={[styles.avi, {borderColor: pal.colors.background}]}>
<UserAvatar <UserAvatar
type="list"
size={80} size={80}
avatar={avatar} avatar={avatar}
onSelectNewAvatar={onSelectNewAvatar} onSelectNewAvatar={onSelectNewAvatar}

View File

@ -154,6 +154,7 @@ export const Feed = observer(function Feed({
onEndReached={onEndReached} onEndReached={onEndReached}
onEndReachedThreshold={0.6} onEndReachedThreshold={0.6}
onScroll={onScroll} onScroll={onScroll}
scrollEventThrottle={100}
contentContainerStyle={s.contentContainer} contentContainerStyle={s.contentContainer}
/> />
) : null} ) : null}

View File

@ -0,0 +1,15 @@
import {useDraggableScroll} from 'lib/hooks/useDraggableScrollView'
import React, {ComponentProps} from 'react'
import {ScrollView} from 'react-native'
export const DraggableScrollView = React.forwardRef<
ScrollView,
ComponentProps<typeof ScrollView>
>(function DraggableScrollView(props, ref) {
const {refs} = useDraggableScroll<ScrollView>({
outerRef: ref,
cursor: 'grab', // optional, default
})
return <ScrollView ref={refs} horizontal {...props} />
})

View File

@ -1,4 +1,4 @@
import React from 'react' import React, {useMemo} from 'react'
import {Animated, StyleSheet} from 'react-native' import {Animated, StyleSheet} from 'react-native'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import {TabBar} from 'view/com/pager/TabBar' import {TabBar} from 'view/com/pager/TabBar'
@ -27,6 +27,10 @@ const FeedsTabBarDesktop = observer(
props: RenderTabBarFnProps & {testID?: string; onPressSelected: () => void}, props: RenderTabBarFnProps & {testID?: string; onPressSelected: () => void},
) => { ) => {
const store = useStores() const store = useStores()
const items = useMemo(
() => ['Following', ...store.me.savedFeeds.pinnedFeedNames],
[store.me.savedFeeds.pinnedFeedNames],
)
const pal = usePalette('default') const pal = usePalette('default')
const interp = useAnimatedValue(0) const interp = useAnimatedValue(0)
@ -44,13 +48,14 @@ const FeedsTabBarDesktop = observer(
{translateY: Animated.multiply(interp, -100)}, {translateY: Animated.multiply(interp, -100)},
], ],
} }
return ( return (
// @ts-ignore the type signature for transform wrong here, translateX and translateY need to be in separate objects -prf // @ts-ignore the type signature for transform wrong here, translateX and translateY need to be in separate objects -prf
<Animated.View style={[pal.view, styles.tabBar, transform]}> <Animated.View style={[pal.view, styles.tabBar, transform]}>
<TabBar <TabBar
key={items.join(',')}
{...props} {...props}
items={['Following', "What's hot"]} items={items}
indicatorPosition="bottom"
indicatorColor={pal.colors.link} indicatorColor={pal.colors.link}
/> />
</Animated.View> </Animated.View>

View File

@ -1,12 +1,17 @@
import React from 'react' import React, {useMemo} from 'react'
import {Animated, StyleSheet, TouchableOpacity} from 'react-native' import {Animated, StyleSheet, TouchableOpacity, View} from 'react-native'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import {TabBar} from 'view/com/pager/TabBar' import {TabBar} from 'view/com/pager/TabBar'
import {RenderTabBarFnProps} from 'view/com/pager/Pager' import {RenderTabBarFnProps} from 'view/com/pager/Pager'
import {UserAvatar} from '../util/UserAvatar'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {useAnimatedValue} from 'lib/hooks/useAnimatedValue' import {useAnimatedValue} from 'lib/hooks/useAnimatedValue'
import {useColorSchemeStyle} from 'lib/hooks/useColorSchemeStyle'
import {Link} from '../util/Link'
import {Text} from '../util/text/Text'
import {CogIcon} from 'lib/icons'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {s} from 'lib/styles'
export const FeedsTabBar = observer( export const FeedsTabBar = observer(
( (
@ -28,25 +33,51 @@ export const FeedsTabBar = observer(
transform: [{translateY: Animated.multiply(interp, -100)}], transform: [{translateY: Animated.multiply(interp, -100)}],
} }
const brandBlue = useColorSchemeStyle(s.brandBlue, s.blue3)
const onPressAvi = React.useCallback(() => { const onPressAvi = React.useCallback(() => {
store.shell.openDrawer() store.shell.openDrawer()
}, [store]) }, [store])
const items = useMemo(
() => ['Following', ...store.me.savedFeeds.pinnedFeedNames],
[store.me.savedFeeds.pinnedFeedNames],
)
return ( return (
<Animated.View style={[pal.view, pal.border, styles.tabBar, transform]}> <Animated.View style={[pal.view, pal.border, styles.tabBar, transform]}>
<TouchableOpacity <View style={[pal.view, styles.topBar]}>
testID="viewHeaderDrawerBtn" <View style={[pal.view]}>
style={styles.tabBarAvi} <TouchableOpacity
onPress={onPressAvi} testID="viewHeaderDrawerBtn"
accessibilityRole="button" onPress={onPressAvi}
accessibilityLabel="Menu" accessibilityRole="button"
accessibilityHint="Access navigation links and settings"> accessibilityLabel="Open navigation"
<UserAvatar avatar={store.me.avatar} size={30} /> accessibilityHint="Access profile and other navigation links"
</TouchableOpacity> hitSlop={10}>
<FontAwesomeIcon
icon="bars"
size={18}
color={pal.colors.textLight}
/>
</TouchableOpacity>
</View>
<Text style={[brandBlue, s.bold, styles.title]}>Bluesky</Text>
<View style={[pal.view]}>
<Link
href="/settings/saved-feeds"
hitSlop={10}
accessibilityRole="button"
accessibilityLabel="Edit Saved Feeds"
accessibilityHint="Opens screen to edit Saved Feeds">
<CogIcon size={21} strokeWidth={2} style={pal.textLight} />
</Link>
</View>
</View>
<TabBar <TabBar
key={items.join(',')}
{...props} {...props}
items={['Following', "What's hot"]} items={items}
indicatorPosition="bottom"
indicatorColor={pal.colors.link} indicatorColor={pal.colors.link}
/> />
</Animated.View> </Animated.View>
@ -61,13 +92,20 @@ const styles = StyleSheet.create({
left: 0, left: 0,
right: 0, right: 0,
top: 0, top: 0,
flexDirection: 'row', flexDirection: 'column',
alignItems: 'center', alignItems: 'center',
paddingHorizontal: 18,
borderBottomWidth: 1, borderBottomWidth: 1,
}, },
tabBarAvi: { topBar: {
marginTop: 1, flexDirection: 'row',
marginRight: 18, justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 18,
paddingTop: 8,
paddingBottom: 2,
width: '100%',
},
title: {
fontSize: 21,
}, },
}) })

View File

@ -1,16 +1,17 @@
import React from 'react' import React, {forwardRef} from 'react'
import {Animated, View} from 'react-native' import {Animated, View} from 'react-native'
import PagerView, {PagerViewOnPageSelectedEvent} from 'react-native-pager-view' import PagerView, {PagerViewOnPageSelectedEvent} from 'react-native-pager-view'
import {useAnimatedValue} from 'lib/hooks/useAnimatedValue'
import {s} from 'lib/styles' import {s} from 'lib/styles'
export type PageSelectedEvent = PagerViewOnPageSelectedEvent export type PageSelectedEvent = PagerViewOnPageSelectedEvent
const AnimatedPagerView = Animated.createAnimatedComponent(PagerView) const AnimatedPagerView = Animated.createAnimatedComponent(PagerView)
export interface PagerRef {
setPage: (index: number) => void
}
export interface RenderTabBarFnProps { export interface RenderTabBarFnProps {
selectedPage: number selectedPage: number
position: Animated.Value
offset: Animated.Value
onSelect?: (index: number) => void onSelect?: (index: number) => void
} }
export type RenderTabBarFn = (props: RenderTabBarFnProps) => JSX.Element export type RenderTabBarFn = (props: RenderTabBarFnProps) => JSX.Element
@ -22,68 +23,60 @@ interface Props {
onPageSelected?: (index: number) => void onPageSelected?: (index: number) => void
testID?: string testID?: string
} }
export const Pager = ({ export const Pager = forwardRef<PagerRef, React.PropsWithChildren<Props>>(
children, (
tabBarPosition = 'top', {
initialPage = 0, children,
renderTabBar, tabBarPosition = 'top',
onPageSelected, initialPage = 0,
testID, renderTabBar,
}: React.PropsWithChildren<Props>) => { onPageSelected,
const [selectedPage, setSelectedPage] = React.useState(0) testID,
const position = useAnimatedValue(0) }: React.PropsWithChildren<Props>,
const offset = useAnimatedValue(0) ref,
const pagerView = React.useRef<PagerView>() ) => {
const [selectedPage, setSelectedPage] = React.useState(0)
const pagerView = React.useRef<PagerView>()
const onPageSelectedInner = React.useCallback( React.useImperativeHandle(ref, () => ({
(e: PageSelectedEvent) => { setPage: (index: number) => pagerView.current?.setPage(index),
setSelectedPage(e.nativeEvent.position) }))
onPageSelected?.(e.nativeEvent.position)
},
[setSelectedPage, onPageSelected],
)
const onTabBarSelect = React.useCallback( const onPageSelectedInner = React.useCallback(
(index: number) => { (e: PageSelectedEvent) => {
pagerView.current?.setPage(index) setSelectedPage(e.nativeEvent.position)
}, onPageSelected?.(e.nativeEvent.position)
[pagerView], },
) [setSelectedPage, onPageSelected],
)
return ( const onTabBarSelect = React.useCallback(
<View testID={testID}> (index: number) => {
{tabBarPosition === 'top' && pagerView.current?.setPage(index)
renderTabBar({ },
selectedPage, [pagerView],
position, )
offset,
onSelect: onTabBarSelect, return (
})} <View testID={testID}>
<AnimatedPagerView {tabBarPosition === 'top' &&
ref={pagerView} renderTabBar({
style={s.h100pct} selectedPage,
initialPage={initialPage} onSelect: onTabBarSelect,
onPageSelected={onPageSelectedInner} })}
onPageScroll={Animated.event( <AnimatedPagerView
[ ref={pagerView}
{ style={s.h100pct}
nativeEvent: { initialPage={initialPage}
position: position, onPageSelected={onPageSelectedInner}>
offset: offset, {children}
}, </AnimatedPagerView>
}, {tabBarPosition === 'bottom' &&
], renderTabBar({
{useNativeDriver: true}, selectedPage,
)}> onSelect: onTabBarSelect,
{children} })}
</AnimatedPagerView> </View>
{tabBarPosition === 'bottom' && )
renderTabBar({ },
selectedPage, )
position,
offset,
onSelect: onTabBarSelect,
})}
</View>
)
}

View File

@ -1,12 +1,9 @@
import React from 'react' import React from 'react'
import {Animated, View} from 'react-native' import {View} from 'react-native'
import {useAnimatedValue} from 'lib/hooks/useAnimatedValue'
import {s} from 'lib/styles' import {s} from 'lib/styles'
export interface RenderTabBarFnProps { export interface RenderTabBarFnProps {
selectedPage: number selectedPage: number
position: Animated.Value
offset: Animated.Value
onSelect?: (index: number) => void onSelect?: (index: number) => void
} }
export type RenderTabBarFn = (props: RenderTabBarFnProps) => JSX.Element export type RenderTabBarFn = (props: RenderTabBarFnProps) => JSX.Element
@ -17,53 +14,51 @@ interface Props {
renderTabBar: RenderTabBarFn renderTabBar: RenderTabBarFn
onPageSelected?: (index: number) => void onPageSelected?: (index: number) => void
} }
export const Pager = ({ export const Pager = React.forwardRef(
children, (
tabBarPosition = 'top', {
initialPage = 0, children,
renderTabBar, tabBarPosition = 'top',
onPageSelected, initialPage = 0,
}: React.PropsWithChildren<Props>) => { renderTabBar,
const [selectedPage, setSelectedPage] = React.useState(initialPage) onPageSelected,
const position = useAnimatedValue(0) }: React.PropsWithChildren<Props>,
const offset = useAnimatedValue(0) ref,
) => {
const [selectedPage, setSelectedPage] = React.useState(initialPage)
const onTabBarSelect = React.useCallback( React.useImperativeHandle(ref, () => ({
(index: number) => { setPage: (index: number) => setSelectedPage(index),
setSelectedPage(index) }))
onPageSelected?.(index)
Animated.timing(position, {
toValue: index,
duration: 200,
useNativeDriver: true,
}).start()
},
[setSelectedPage, onPageSelected, position],
)
return ( const onTabBarSelect = React.useCallback(
<View> (index: number) => {
{tabBarPosition === 'top' && setSelectedPage(index)
renderTabBar({ onPageSelected?.(index)
selectedPage, },
position, [setSelectedPage, onPageSelected],
offset, )
onSelect: onTabBarSelect,
})} return (
{React.Children.map(children, (child, i) => ( <View>
<View {tabBarPosition === 'top' &&
style={selectedPage === i ? undefined : s.hidden} renderTabBar({
key={`page-${i}`}> selectedPage,
{child} onSelect: onTabBarSelect,
</View> })}
))} {React.Children.map(children, (child, i) => (
{tabBarPosition === 'bottom' && <View
renderTabBar({ style={selectedPage === i ? undefined : s.hidden}
selectedPage, key={`page-${i}`}>
position, {child}
offset, </View>
onSelect: onTabBarSelect, ))}
})} {tabBarPosition === 'bottom' &&
</View> renderTabBar({
) selectedPage,
} onSelect: onTabBarSelect,
})}
</View>
)
},
)

View File

@ -1,22 +1,22 @@
import React, {createRef, useState, useMemo, useRef} from 'react' import React, {
import {Animated, StyleSheet, View} from 'react-native' useRef,
createRef,
useMemo,
useEffect,
useState,
useCallback,
} from 'react'
import {StyleSheet, View, ScrollView} from 'react-native'
import {Text} from '../util/text/Text' import {Text} from '../util/text/Text'
import {PressableWithHover} from '../util/PressableWithHover' import {PressableWithHover} from '../util/PressableWithHover'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {isDesktopWeb} from 'platform/detection' import {isDesktopWeb, isMobileWeb} from 'platform/detection'
import {DraggableScrollView} from './DraggableScrollView'
interface Layout {
x: number
width: number
}
export interface TabBarProps { export interface TabBarProps {
testID?: string testID?: string
selectedPage: number selectedPage: number
items: string[] items: string[]
position: Animated.Value
offset: Animated.Value
indicatorPosition?: 'top' | 'bottom'
indicatorColor?: string indicatorColor?: string
onSelect?: (index: number) => void onSelect?: (index: number) => void
onPressSelected?: () => void onPressSelected?: () => void
@ -26,69 +26,27 @@ export function TabBar({
testID, testID,
selectedPage, selectedPage,
items, items,
position,
offset,
indicatorPosition = 'bottom',
indicatorColor, indicatorColor,
onSelect, onSelect,
onPressSelected, onPressSelected,
}: TabBarProps) { }: TabBarProps) {
const pal = usePalette('default') const pal = usePalette('default')
const [itemLayouts, setItemLayouts] = useState<Layout[]>( const scrollElRef = useRef<ScrollView>(null)
items.map(() => ({x: 0, width: 0})), const [itemXs, setItemXs] = useState<number[]>([])
)
const itemRefs = useMemo( const itemRefs = useMemo(
() => Array.from({length: items.length}).map(() => createRef<View>()), () => Array.from({length: items.length}).map(() => createRef<View>()),
[items.length], [items.length],
) )
const panX = Animated.add(position, offset) const indicatorStyle = useMemo(
const containerRef = useRef<View>(null) () => ({borderBottomColor: indicatorColor || pal.colors.link}),
[indicatorColor, pal],
)
const indicatorStyle = { useEffect(() => {
backgroundColor: indicatorColor || pal.colors.link, scrollElRef.current?.scrollTo({x: itemXs[selectedPage] || 0})
bottom: }, [scrollElRef, itemXs, selectedPage])
indicatorPosition === 'bottom' ? (isDesktopWeb ? 0 : -1) : undefined,
top: indicatorPosition === 'top' ? (isDesktopWeb ? 0 : -1) : undefined,
transform: [
{
translateX: panX.interpolate({
inputRange: items.map((_item, i) => i),
outputRange: itemLayouts.map(l => l.x + l.width / 2),
}),
},
{
scaleX: panX.interpolate({
inputRange: items.map((_item, i) => i),
outputRange: itemLayouts.map(l => l.width),
}),
},
],
}
const onLayout = React.useCallback(() => { const onPressItem = useCallback(
const promises = []
for (let i = 0; i < items.length; i++) {
promises.push(
new Promise<Layout>(resolve => {
if (!containerRef.current || !itemRefs[i].current) {
return resolve({x: 0, width: 0})
}
itemRefs[i].current?.measureLayout(
containerRef.current,
(x: number, _y: number, width: number) => {
resolve({x, width})
},
)
}),
)
}
Promise.all(promises).then((layouts: Layout[]) => {
setItemLayouts(layouts)
})
}, [containerRef, itemRefs, setItemLayouts, items.length])
const onPressItem = React.useCallback(
(index: number) => { (index: number) => {
onSelect?.(index) onSelect?.(index)
if (index === selectedPage) { if (index === selectedPage) {
@ -98,33 +56,51 @@ export function TabBar({
[onSelect, onPressSelected, selectedPage], [onSelect, onPressSelected, selectedPage],
) )
const onLayout = React.useCallback(() => {
const promises = []
for (let i = 0; i < items.length; i++) {
promises.push(
new Promise<number>(resolve => {
if (!itemRefs[i].current) {
return resolve(0)
}
itemRefs[i].current?.measure((x: number) => resolve(x))
}),
)
}
Promise.all(promises).then((Xs: number[]) => {
setItemXs(Xs)
})
}, [itemRefs, setItemXs, items.length])
return ( return (
<View <View testID={testID} style={[pal.view, styles.outer]}>
testID={testID} <DraggableScrollView
style={[pal.view, styles.outer]} horizontal={true}
onLayout={onLayout} showsHorizontalScrollIndicator={false}
ref={containerRef}> ref={scrollElRef}
<Animated.View style={[styles.indicator, indicatorStyle]} /> contentContainerStyle={styles.contentContainer}
{items.map((item, i) => { onLayout={onLayout}>
const selected = i === selectedPage {items.map((item, i) => {
return ( const selected = i === selectedPage
<PressableWithHover return (
ref={itemRefs[i]} <PressableWithHover
key={item} ref={itemRefs[i]}
style={ key={item}
indicatorPosition === 'top' ? styles.itemTop : styles.itemBottom style={[styles.item, selected && indicatorStyle]}
} hoverStyle={pal.viewLight}
hoverStyle={pal.viewLight} onPress={() => onPressItem(i)}>
onPress={() => onPressItem(i)}> <Text
<Text type={isDesktopWeb ? 'xl-bold' : 'lg-bold'}
type="xl-bold" testID={testID ? `${testID}-${item}` : undefined}
testID={testID ? `${testID}-${item}` : undefined} style={selected ? pal.text : pal.textLight}>
style={selected ? pal.text : pal.textLight}> {item}
{item} </Text>
</Text> </PressableWithHover>
</PressableWithHover> )
) })}
})} </DraggableScrollView>
</View> </View>
) )
} }
@ -133,45 +109,39 @@ const styles = isDesktopWeb
? StyleSheet.create({ ? StyleSheet.create({
outer: { outer: {
flexDirection: 'row', flexDirection: 'row',
paddingHorizontal: 18, width: 598,
}, },
itemTop: { contentContainer: {
paddingTop: 16, columnGap: 8,
paddingBottom: 14, marginLeft: 14,
paddingHorizontal: 12, paddingRight: 14,
backgroundColor: 'transparent',
}, },
itemBottom: { item: {
paddingTop: 14, paddingTop: 14,
paddingBottom: 16, paddingBottom: 12,
paddingHorizontal: 12, paddingHorizontal: 10,
}, borderBottomWidth: 3,
indicator: { borderBottomColor: 'transparent',
position: 'absolute',
left: 0,
width: 1,
height: 3,
zIndex: 1,
}, },
}) })
: StyleSheet.create({ : StyleSheet.create({
outer: { outer: {
flex: 1,
flexDirection: 'row', flexDirection: 'row',
paddingHorizontal: 14, backgroundColor: 'transparent',
}, },
itemTop: { contentContainer: {
columnGap: isMobileWeb ? 0 : 20,
marginLeft: isMobileWeb ? 0 : 18,
paddingRight: isMobileWeb ? 0 : 36,
backgroundColor: 'transparent',
},
item: {
paddingTop: 10, paddingTop: 10,
paddingBottom: 10, paddingBottom: 10,
marginRight: 24, paddingHorizontal: isMobileWeb ? 8 : 0,
}, borderBottomWidth: 3,
itemBottom: { borderBottomColor: 'transparent',
paddingTop: 8,
paddingBottom: 12,
marginRight: 24,
},
indicator: {
position: 'absolute',
left: 0,
width: 1,
height: 3,
}, },
}) })

View File

@ -1,5 +1,6 @@
import React from 'react' import React from 'react'
import {StyleSheet, View} from 'react-native' import {StyleSheet, View} from 'react-native'
import {useNavigation} from '@react-navigation/native'
import { import {
FontAwesomeIcon, FontAwesomeIcon,
FontAwesomeIconStyle, FontAwesomeIconStyle,
@ -7,18 +8,19 @@ import {
import {Text} from '../util/text/Text' import {Text} from '../util/text/Text'
import {Button} from '../util/forms/Button' import {Button} from '../util/forms/Button'
import {MagnifyingGlassIcon} from 'lib/icons' import {MagnifyingGlassIcon} from 'lib/icons'
import {useStores} from 'state/index' import {NavigationProp} from 'lib/routes/types'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {s} from 'lib/styles' import {s} from 'lib/styles'
export function WhatsHotEmptyState() { export function CustomFeedEmptyState() {
const pal = usePalette('default') const pal = usePalette('default')
const palInverted = usePalette('inverted') const palInverted = usePalette('inverted')
const store = useStores() const navigation = useNavigation<NavigationProp>()
const onPressSettings = React.useCallback(() => { const onPressFindAccounts = React.useCallback(() => {
store.shell.openModal({name: 'content-languages-settings'}) navigation.navigate('SearchTab')
}, [store]) navigation.popToTop()
}, [navigation])
return ( return (
<View style={styles.emptyContainer}> <View style={styles.emptyContainer}>
@ -26,12 +28,15 @@ export function WhatsHotEmptyState() {
<MagnifyingGlassIcon style={[styles.emptyIcon, pal.text]} size={62} /> <MagnifyingGlassIcon style={[styles.emptyIcon, pal.text]} size={62} />
</View> </View>
<Text type="xl-medium" style={[s.textCenter, pal.text]}> <Text type="xl-medium" style={[s.textCenter, pal.text]}>
Your What's Hot feed is empty! This is because there aren't enough users This feed is empty! You may need to follow more users or tune your
posting in your selected language. language settings.
</Text> </Text>
<Button type="inverted" style={styles.emptyBtn} onPress={onPressSettings}> <Button
type="inverted"
style={styles.emptyBtn}
onPress={onPressFindAccounts}>
<Text type="lg-medium" style={palInverted.text}> <Text type="lg-medium" style={palInverted.text}>
Update my settings Find accounts to follow
</Text> </Text>
<FontAwesomeIcon <FontAwesomeIcon
icon="angle-right" icon="angle-right"

View File

@ -18,6 +18,7 @@ import {OnScrollCb} from 'lib/hooks/useOnMainScroll'
import {s} from 'lib/styles' import {s} from 'lib/styles'
import {useAnalytics} from 'lib/analytics' import {useAnalytics} from 'lib/analytics'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {useTheme} from 'lib/ThemeContext'
const LOADING_ITEM = {_reactKey: '__loading__'} const LOADING_ITEM = {_reactKey: '__loading__'}
const EMPTY_FEED_ITEM = {_reactKey: '__empty__'} const EMPTY_FEED_ITEM = {_reactKey: '__empty__'}
@ -31,9 +32,12 @@ export const Feed = observer(function Feed({
scrollElRef, scrollElRef,
onPressTryAgain, onPressTryAgain,
onScroll, onScroll,
scrollEventThrottle,
renderEmptyState, renderEmptyState,
testID, testID,
headerOffset = 0, headerOffset = 0,
ListHeaderComponent,
extraData,
}: { }: {
feed: PostsFeedModel feed: PostsFeedModel
style?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle>
@ -41,11 +45,15 @@ export const Feed = observer(function Feed({
scrollElRef?: MutableRefObject<FlatList<any> | null> scrollElRef?: MutableRefObject<FlatList<any> | null>
onPressTryAgain?: () => void onPressTryAgain?: () => void
onScroll?: OnScrollCb onScroll?: OnScrollCb
scrollEventThrottle?: number
renderEmptyState?: () => JSX.Element renderEmptyState?: () => JSX.Element
testID?: string testID?: string
headerOffset?: number headerOffset?: number
ListHeaderComponent?: () => JSX.Element
extraData?: any
}) { }) {
const pal = usePalette('default') const pal = usePalette('default')
const theme = useTheme()
const {track} = useAnalytics() const {track} = useAnalytics()
const [isRefreshing, setIsRefreshing] = React.useState(false) const [isRefreshing, setIsRefreshing] = React.useState(false)
@ -163,6 +171,7 @@ export const Feed = observer(function Feed({
keyExtractor={item => item._reactKey} keyExtractor={item => item._reactKey}
renderItem={renderItem} renderItem={renderItem}
ListFooterComponent={FeedFooter} ListFooterComponent={FeedFooter}
ListHeaderComponent={ListHeaderComponent}
refreshControl={ refreshControl={
<RefreshControl <RefreshControl
refreshing={isRefreshing} refreshing={isRefreshing}
@ -175,10 +184,13 @@ export const Feed = observer(function Feed({
contentContainerStyle={s.contentContainer} contentContainerStyle={s.contentContainer}
style={{paddingTop: headerOffset}} style={{paddingTop: headerOffset}}
onScroll={onScroll} onScroll={onScroll}
scrollEventThrottle={scrollEventThrottle}
indicatorStyle={theme.colorScheme === 'dark' ? 'white' : 'black'}
onEndReached={onEndReached} onEndReached={onEndReached}
onEndReachedThreshold={0.6} onEndReachedThreshold={0.6}
removeClippedSubviews={true} removeClippedSubviews={true}
contentOffset={{x: 0, y: headerOffset * -1}} contentOffset={{x: 0, y: headerOffset * -1}}
extraData={extraData}
// @ts-ignore our .web version only -prf // @ts-ignore our .web version only -prf
desktopFixedHeight desktopFixedHeight
/> />

View File

@ -1,6 +1,6 @@
import React from 'react' import React from 'react'
import {StyleSheet, View} from 'react-native' import {StyleSheet, View} from 'react-native'
import {PostsFeedSliceModel} from 'state/models/feeds/posts' import {PostsFeedSliceModel} from 'state/models/feeds/post'
import {AtUri} from '@atproto/api' import {AtUri} 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'

View File

@ -0,0 +1,246 @@
import React, {MutableRefObject} from 'react'
import {observer} from 'mobx-react-lite'
import {
ActivityIndicator,
RefreshControl,
StyleProp,
StyleSheet,
View,
ViewStyle,
} from 'react-native'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {FlatList} from '../util/Views'
import {PostFeedLoadingPlaceholder} from '../util/LoadingPlaceholder'
import {ErrorMessage} from '../util/error/ErrorMessage'
import {PostsMultiFeedModel, MultiFeedItem} from 'state/models/feeds/multi-feed'
import {FeedSlice} from './FeedSlice'
import {Text} from '../util/text/Text'
import {Link} from '../util/Link'
import {UserAvatar} from '../util/UserAvatar'
import {OnScrollCb} from 'lib/hooks/useOnMainScroll'
import {s} from 'lib/styles'
import {useAnalytics} from 'lib/analytics'
import {usePalette} from 'lib/hooks/usePalette'
import {useTheme} from 'lib/ThemeContext'
import {isDesktopWeb} from 'platform/detection'
import {CogIcon} from 'lib/icons'
export const MultiFeed = observer(function Feed({
multifeed,
style,
showPostFollowBtn,
scrollElRef,
onScroll,
scrollEventThrottle,
testID,
headerOffset = 0,
extraData,
}: {
multifeed: PostsMultiFeedModel
style?: StyleProp<ViewStyle>
showPostFollowBtn?: boolean
scrollElRef?: MutableRefObject<FlatList<any> | null>
onPressTryAgain?: () => void
onScroll?: OnScrollCb
scrollEventThrottle?: number
renderEmptyState?: () => JSX.Element
testID?: string
headerOffset?: number
extraData?: any
}) {
const pal = usePalette('default')
const theme = useTheme()
const {track} = useAnalytics()
const [isRefreshing, setIsRefreshing] = React.useState(false)
// events
// =
const onRefresh = React.useCallback(async () => {
track('MultiFeed:onRefresh')
setIsRefreshing(true)
try {
await multifeed.refresh()
} catch (err) {
multifeed.rootStore.log.error('Failed to refresh posts feed', err)
}
setIsRefreshing(false)
}, [multifeed, track, setIsRefreshing])
const onEndReached = React.useCallback(async () => {
track('MultiFeed:onEndReached')
try {
await multifeed.loadMore()
} catch (err) {
multifeed.rootStore.log.error('Failed to load more posts', err)
}
}, [multifeed, track])
// rendering
// =
const renderItem = React.useCallback(
({item}: {item: MultiFeedItem}) => {
if (item.type === 'header') {
if (isDesktopWeb) {
return (
<View style={[pal.view, pal.border, styles.headerDesktop]}>
<Text type="2xl-bold" style={pal.text}>
My Feeds
</Text>
<Link href="/settings/saved-feeds">
<CogIcon strokeWidth={1.5} style={pal.icon} size={28} />
</Link>
</View>
)
}
return <View style={[styles.header, pal.border]} />
} else if (item.type === 'feed-header') {
return (
<View style={styles.feedHeader}>
<UserAvatar type="algo" avatar={item.avatar} size={28} />
<Text type="title-lg" style={[pal.text, styles.feedHeaderTitle]}>
{item.title}
</Text>
</View>
)
} else if (item.type === 'feed-slice') {
return (
<FeedSlice slice={item.slice} showFollowBtn={showPostFollowBtn} />
)
} else if (item.type === 'feed-loading') {
return <PostFeedLoadingPlaceholder />
} else if (item.type === 'feed-error') {
return <ErrorMessage message={item.error} />
} else if (item.type === 'feed-footer') {
return (
<Link
href={item.uri}
style={[styles.feedFooter, pal.border, pal.view]}>
<Text type="lg" style={pal.link}>
See more from {item.title}
</Text>
<FontAwesomeIcon
icon="angle-right"
size={18}
color={pal.colors.link}
/>
</Link>
)
} else if (item.type === 'footer') {
return (
<Link style={[styles.footerLink, pal.viewLight]} href="/search/feeds">
<FontAwesomeIcon icon="search" size={18} color={pal.colors.text} />
<Text type="xl-medium" style={pal.text}>
Discover new feeds
</Text>
</Link>
)
}
return null
},
[showPostFollowBtn, pal],
)
const FeedFooter = React.useCallback(
() =>
multifeed.isLoading && !isRefreshing ? (
<View style={styles.loadMore}>
<ActivityIndicator color={pal.colors.text} />
</View>
) : (
<View />
),
[multifeed.isLoading, isRefreshing, pal],
)
return (
<View testID={testID} style={style}>
{multifeed.items.length > 0 && (
<FlatList
testID={testID ? `${testID}-flatlist` : undefined}
ref={scrollElRef}
data={multifeed.items}
keyExtractor={item => item._reactKey}
renderItem={renderItem}
ListFooterComponent={FeedFooter}
refreshControl={
<RefreshControl
refreshing={isRefreshing}
onRefresh={onRefresh}
tintColor={pal.colors.text}
titleColor={pal.colors.text}
progressViewOffset={headerOffset}
/>
}
contentContainerStyle={s.contentContainer}
style={[{paddingTop: headerOffset}, pal.view, styles.container]}
onScroll={onScroll}
scrollEventThrottle={scrollEventThrottle}
indicatorStyle={theme.colorScheme === 'dark' ? 'white' : 'black'}
onEndReached={onEndReached}
onEndReachedThreshold={0.6}
removeClippedSubviews={true}
contentOffset={{x: 0, y: headerOffset * -1}}
extraData={extraData}
// @ts-ignore our .web version only -prf
desktopFixedHeight
/>
)}
</View>
)
})
const styles = StyleSheet.create({
container: {
height: '100%',
},
header: {
borderTopWidth: 1,
marginBottom: 4,
},
headerDesktop: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
borderBottomWidth: 1,
marginBottom: 4,
paddingHorizontal: 16,
paddingVertical: 8,
},
feedHeader: {
flexDirection: 'row',
gap: 8,
alignItems: 'center',
paddingHorizontal: 16,
paddingBottom: 8,
marginTop: 12,
},
feedHeaderTitle: {
fontWeight: 'bold',
},
feedFooter: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 16,
paddingVertical: 16,
marginBottom: 12,
borderTopWidth: 1,
borderBottomWidth: 1,
},
footerLink: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 8,
paddingHorizontal: 14,
paddingVertical: 12,
marginHorizontal: 8,
marginBottom: 8,
gap: 8,
},
loadMore: {
paddingTop: 10,
},
})

View File

@ -4,7 +4,6 @@ import {
FontAwesomeIcon, FontAwesomeIcon,
FontAwesomeIconStyle, FontAwesomeIconStyle,
} from '@fortawesome/react-native-fontawesome' } from '@fortawesome/react-native-fontawesome'
import {UserAvatar} from 'view/com/util/UserAvatar'
import {Text} from 'view/com/util/text/Text' import {Text} from 'view/com/util/text/Text'
import {MagnifyingGlassIcon} from 'lib/icons' import {MagnifyingGlassIcon} from 'lib/icons'
import {useTheme} from 'lib/ThemeContext' import {useTheme} from 'lib/ThemeContext'
@ -58,7 +57,7 @@ export function HeaderWithInput({
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel="Menu" accessibilityLabel="Menu"
accessibilityHint="Access navigation links and settings"> accessibilityHint="Access navigation links and settings">
<UserAvatar size={30} avatar={store.me.avatar} /> <FontAwesomeIcon icon="bars" size={18} color={pal.colors.textLight} />
</TouchableOpacity> </TouchableOpacity>
<View <View
style={[ style={[
@ -87,6 +86,8 @@ export function HeaderWithInput({
accessibilityRole="search" accessibilityRole="search"
accessibilityLabel="Search" accessibilityLabel="Search"
accessibilityHint="" accessibilityHint=""
autoCorrect={false}
autoCapitalize="none"
/> />
{query ? ( {query ? (
<TouchableOpacity <TouchableOpacity
@ -119,6 +120,7 @@ const styles = StyleSheet.create({
header: { header: {
flexDirection: 'row', flexDirection: 'row',
alignItems: 'center', alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: 12, paddingHorizontal: 12,
paddingVertical: 4, paddingVertical: 4,
}, },
@ -126,7 +128,10 @@ const styles = StyleSheet.create({
width: 30, width: 30,
height: 30, height: 30,
borderRadius: 30, borderRadius: 30,
marginHorizontal: 6, marginRight: 6,
paddingBottom: 2,
alignItems: 'center',
justifyContent: 'center',
}, },
headerSearchContainer: { headerSearchContainer: {
flex: 1, flex: 1,

View File

@ -1,6 +1,6 @@
import React, {useMemo} from 'react' import React, {useMemo} from 'react'
import {StyleSheet, View} from 'react-native' import {StyleSheet, View} from 'react-native'
import Svg, {Circle, Path} from 'react-native-svg' import Svg, {Circle, Rect, Path} from 'react-native-svg'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome' import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {IconProp} from '@fortawesome/fontawesome-svg-core' import {IconProp} from '@fortawesome/fontawesome-svg-core'
import {HighPriorityImage} from 'view/com/util/images/Image' import {HighPriorityImage} from 'view/com/util/images/Image'
@ -17,9 +17,54 @@ import {isWeb, isAndroid} from 'platform/detection'
import {Image as RNImage} from 'react-native-image-crop-picker' import {Image as RNImage} from 'react-native-image-crop-picker'
import {AvatarModeration} from 'lib/labeling/types' import {AvatarModeration} from 'lib/labeling/types'
type Type = 'user' | 'algo' | 'list'
const BLUR_AMOUNT = isWeb ? 5 : 100 const BLUR_AMOUNT = isWeb ? 5 : 100
function DefaultAvatar({size}: {size: number}) { function DefaultAvatar({type, size}: {type: Type; size: number}) {
if (type === 'algo') {
// Font Awesome Pro 6.4.0 by @fontawesome -https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc.
return (
<Svg
testID="userAvatarFallback"
width={size}
height={size}
viewBox="0 0 32 32"
fill="none"
stroke="none">
<Rect width="32" height="32" rx="4" fill="#0070FF" />
<Path
d="M13.5 7.25C13.5 6.55859 14.0586 6 14.75 6C20.9648 6 26 11.0352 26 17.25C26 17.9414 25.4414 18.5 24.75 18.5C24.0586 18.5 23.5 17.9414 23.5 17.25C23.5 12.418 19.582 8.5 14.75 8.5C14.0586 8.5 13.5 7.94141 13.5 7.25ZM8.36719 14.6172L12.4336 18.6836L13.543 17.5742C13.5156 17.4727 13.5 17.3633 13.5 17.25C13.5 16.5586 14.0586 16 14.75 16C15.4414 16 16 16.5586 16 17.25C16 17.9414 15.4414 18.5 14.75 18.5C14.6367 18.5 14.5312 18.4844 14.4258 18.457L13.3164 19.5664L17.3828 23.6328C17.9492 24.1992 17.8438 25.1484 17.0977 25.4414C16.1758 25.8008 15.1758 26 14.125 26C9.63672 26 6 22.3633 6 17.875C6 16.8242 6.19922 15.8242 6.5625 14.9023C6.85547 14.1602 7.80469 14.0508 8.37109 14.6172H8.36719ZM14.75 9.75C18.8906 9.75 22.25 13.1094 22.25 17.25C22.25 17.9414 21.6914 18.5 21 18.5C20.3086 18.5 19.75 17.9414 19.75 17.25C19.75 14.4883 17.5117 12.25 14.75 12.25C14.0586 12.25 13.5 11.6914 13.5 11C13.5 10.3086 14.0586 9.75 14.75 9.75Z"
fill="white"
/>
</Svg>
)
}
if (type === 'list') {
// Font Awesome Pro 6.4.0 by @fontawesome -https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc.
return (
<Svg
testID="userAvatarFallback"
width={size}
height={size}
viewBox="0 0 32 32"
fill="none"
stroke="none">
<Path
d="M28 0H4C1.79086 0 0 1.79086 0 4V28C0 30.2091 1.79086 32 4 32H28C30.2091 32 32 30.2091 32 28V4C32 1.79086 30.2091 0 28 0Z"
fill="#0070FF"
/>
<Path
d="M22.1529 22.3542C23.4522 22.4603 24.7593 22.293 25.9899 21.8629C26.0369 21.2838 25.919 20.7032 25.6497 20.1884C25.3805 19.6735 24.9711 19.2454 24.4687 18.9535C23.9663 18.6617 23.3916 18.518 22.8109 18.5392C22.2303 18.5603 21.6676 18.7454 21.1878 19.0731M22.1529 22.3542C22.1489 21.1917 21.8142 20.0534 21.1878 19.0741ZM10.8111 19.0741C10.3313 18.7468 9.7687 18.5619 9.18826 18.5409C8.60781 18.5199 8.03327 18.6636 7.53107 18.9554C7.02888 19.2472 6.61953 19.6752 6.35036 20.1899C6.08119 20.7046 5.96319 21.285 6.01001 21.8639C7.23969 22.2964 8.5461 22.4632 9.84497 22.3531M10.8111 19.0741C10.1851 20.0535 9.84865 21.1908 9.84497 22.3531ZM19.0759 10.077C19.0759 10.8931 18.7518 11.6757 18.1747 12.2527C17.5977 12.8298 16.815 13.154 15.9989 13.154C15.1829 13.154 14.4002 12.8298 13.8232 12.2527C13.2461 11.6757 12.922 10.8931 12.922 10.077C12.922 9.26092 13.2461 8.47828 13.8232 7.90123C14.4002 7.32418 15.1829 7 15.9989 7C16.815 7 17.5977 7.32418 18.1747 7.90123C18.7518 8.47828 19.0759 9.26092 19.0759 10.077ZM25.2299 13.154C25.2299 13.457 25.1702 13.7571 25.0542 14.0371C24.9383 14.3171 24.7683 14.5715 24.554 14.7858C24.3397 15.0001 24.0853 15.1701 23.8053 15.2861C23.5253 15.402 23.2252 15.4617 22.9222 15.4617C22.6191 15.4617 22.319 15.402 22.039 15.2861C21.759 15.1701 21.5046 15.0001 21.2903 14.7858C21.0761 14.5715 20.9061 14.3171 20.7901 14.0371C20.6741 13.7571 20.6144 13.457 20.6144 13.154C20.6144 12.5419 20.8576 11.9549 21.2903 11.5222C21.7231 11.0894 22.3101 10.8462 22.9222 10.8462C23.5342 10.8462 24.1212 11.0894 24.554 11.5222C24.9868 11.9549 25.2299 12.5419 25.2299 13.154ZM11.3835 13.154C11.3835 13.457 11.3238 13.7571 11.2078 14.0371C11.0918 14.3171 10.9218 14.5715 10.7075 14.7858C10.4932 15.0001 10.2388 15.1701 9.95886 15.2861C9.67887 15.402 9.37878 15.4617 9.07572 15.4617C8.77266 15.4617 8.47257 15.402 8.19259 15.2861C7.9126 15.1701 7.6582 15.0001 7.4439 14.7858C7.22961 14.5715 7.05962 14.3171 6.94365 14.0371C6.82767 13.7571 6.76798 13.457 6.76798 13.154C6.76798 12.5419 7.01112 11.9549 7.4439 11.5222C7.87669 11.0894 8.46367 10.8462 9.07572 10.8462C9.68777 10.8462 10.2748 11.0894 10.7075 11.5222C11.1403 11.9549 11.3835 12.5419 11.3835 13.154Z"
fill="white"
/>
<Path
d="M22 22C22 25.3137 19.3137 25.5 16 25.5C12.6863 25.5 10 25.3137 10 22C10 18.6863 12.6863 16 16 16C19.3137 16 22 18.6863 22 22Z"
fill="white"
/>
</Svg>
)
}
return ( return (
<Svg <Svg
testID="userAvatarFallback" testID="userAvatarFallback"
@ -41,11 +86,13 @@ function DefaultAvatar({size}: {size: number}) {
} }
export function UserAvatar({ export function UserAvatar({
type = 'user',
size, size,
avatar, avatar,
moderation, moderation,
onSelectNewAvatar, onSelectNewAvatar,
}: { }: {
type?: Type
size: number size: number
avatar?: string | null avatar?: string | null
moderation?: AvatarModeration moderation?: AvatarModeration
@ -56,6 +103,21 @@ export function UserAvatar({
const {requestCameraAccessIfNeeded} = useCameraPermission() const {requestCameraAccessIfNeeded} = useCameraPermission()
const {requestPhotoAccessIfNeeded} = usePhotoLibraryPermission() const {requestPhotoAccessIfNeeded} = usePhotoLibraryPermission()
const aviStyle = useMemo(() => {
if (type === 'algo' || type === 'list') {
return {
width: size,
height: size,
borderRadius: 8,
}
}
return {
width: size,
height: size,
borderRadius: Math.floor(size / 2),
}
}, [type, size])
const dropdownItems = useMemo( const dropdownItems = useMemo(
() => [ () => [
!isWeb && { !isWeb && {
@ -146,16 +208,12 @@ export function UserAvatar({
{avatar ? ( {avatar ? (
<HighPriorityImage <HighPriorityImage
testID="userAvatarImage" testID="userAvatarImage"
style={{ style={aviStyle}
width: size,
height: size,
borderRadius: Math.floor(size / 2),
}}
source={{uri: avatar}} source={{uri: avatar}}
accessibilityRole="image" accessibilityRole="image"
/> />
) : ( ) : (
<DefaultAvatar size={size} /> <DefaultAvatar type={type} size={size} />
)} )}
<View style={[styles.editButtonContainer, pal.btn]}> <View style={[styles.editButtonContainer, pal.btn]}>
<FontAwesomeIcon <FontAwesomeIcon
@ -170,11 +228,7 @@ export function UserAvatar({
<View style={{width: size, height: size}}> <View style={{width: size, height: size}}>
<HighPriorityImage <HighPriorityImage
testID="userAvatarImage" testID="userAvatarImage"
style={{ style={aviStyle}
width: size,
height: size,
borderRadius: Math.floor(size / 2),
}}
contentFit="cover" contentFit="cover"
source={{uri: avatar}} source={{uri: avatar}}
blurRadius={moderation?.blur ? BLUR_AMOUNT : 0} blurRadius={moderation?.blur ? BLUR_AMOUNT : 0}
@ -183,7 +237,7 @@ export function UserAvatar({
</View> </View>
) : ( ) : (
<View style={{width: size, height: size}}> <View style={{width: size, height: size}}>
<DefaultAvatar size={size} /> <DefaultAvatar type={type} size={size} />
{warning} {warning}
</View> </View>
) )
@ -201,11 +255,6 @@ const styles = StyleSheet.create({
justifyContent: 'center', justifyContent: 'center',
backgroundColor: colors.gray5, backgroundColor: colors.gray5,
}, },
avatarImage: {
width: 80,
height: 80,
borderRadius: 40,
},
warningIconContainer: { warningIconContainer: {
position: 'absolute', position: 'absolute',
right: 0, right: 0,

View File

@ -4,7 +4,6 @@ import {Animated, StyleSheet, TouchableOpacity, View} from 'react-native'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome' import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {useNavigation} from '@react-navigation/native' import {useNavigation} from '@react-navigation/native'
import {CenteredView} from './Views' import {CenteredView} from './Views'
import {UserAvatar} from './UserAvatar'
import {Text} from './text/Text' import {Text} from './text/Text'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
@ -20,12 +19,14 @@ export const ViewHeader = observer(function ({
canGoBack, canGoBack,
hideOnScroll, hideOnScroll,
showOnDesktop, showOnDesktop,
showBorder,
renderButton, renderButton,
}: { }: {
title: string title: string
canGoBack?: boolean canGoBack?: boolean
hideOnScroll?: boolean hideOnScroll?: boolean
showOnDesktop?: boolean showOnDesktop?: boolean
showBorder?: boolean
renderButton?: () => JSX.Element renderButton?: () => JSX.Element
}) { }) {
const pal = usePalette('default') const pal = usePalette('default')
@ -57,7 +58,7 @@ export const ViewHeader = observer(function ({
} }
return ( return (
<Container hideOnScroll={hideOnScroll || false}> <Container hideOnScroll={hideOnScroll || false} showBorder={showBorder}>
<TouchableOpacity <TouchableOpacity
testID="viewHeaderDrawerBtn" testID="viewHeaderDrawerBtn"
onPress={canGoBack ? onPressBack : onPressMenu} onPress={canGoBack ? onPressBack : onPressMenu}
@ -75,7 +76,11 @@ export const ViewHeader = observer(function ({
style={[styles.backIcon, pal.text]} style={[styles.backIcon, pal.text]}
/> />
) : ( ) : (
<UserAvatar size={30} avatar={store.me.avatar} /> <FontAwesomeIcon
size={18}
icon="bars"
style={[styles.backIcon, pal.textLight]}
/>
)} )}
</TouchableOpacity> </TouchableOpacity>
<View style={styles.titleContainer} pointerEvents="none"> <View style={styles.titleContainer} pointerEvents="none">
@ -117,9 +122,11 @@ const Container = observer(
({ ({
children, children,
hideOnScroll, hideOnScroll,
showBorder,
}: { }: {
children: React.ReactNode children: React.ReactNode
hideOnScroll: boolean hideOnScroll: boolean
showBorder?: boolean
}) => { }) => {
const store = useStores() const store = useStores()
const pal = usePalette('default') const pal = usePalette('default')
@ -147,11 +154,28 @@ const Container = observer(
} }
if (!hideOnScroll) { if (!hideOnScroll) {
return <View style={[styles.header, pal.view]}>{children}</View> return (
<View
style={[
styles.header,
pal.view,
pal.border,
showBorder && styles.border,
]}>
{children}
</View>
)
} }
return ( return (
<Animated.View <Animated.View
style={[styles.header, pal.view, styles.headerFloating, transform]}> style={[
styles.header,
pal.view,
pal.border,
styles.headerFloating,
transform,
showBorder && styles.border,
]}>
{children} {children}
</Animated.View> </Animated.View>
) )
@ -174,6 +198,9 @@ const styles = StyleSheet.create({
borderBottomWidth: 1, borderBottomWidth: 1,
paddingVertical: 12, paddingVertical: 12,
}, },
border: {
borderBottomWidth: 1,
},
titleContainer: { titleContainer: {
marginLeft: 'auto', marginLeft: 'auto',

View File

@ -1,5 +1,5 @@
import React, {useEffect, useState} from 'react' import React, {useEffect, useState} from 'react'
import {Pressable, StyleSheet, View} from 'react-native' import {Pressable, RefreshControl, StyleSheet, View} from 'react-native'
import {FlatList} from './Views' import {FlatList} from './Views'
import {OnScrollCb} from 'lib/hooks/useOnMainScroll' import {OnScrollCb} from 'lib/hooks/useOnMainScroll'
import {useColorSchemeStyle} from 'lib/hooks/useColorSchemeStyle' import {useColorSchemeStyle} from 'lib/hooks/useColorSchemeStyle'
@ -41,6 +41,7 @@ export function ViewSelector({
onRefresh?: () => void onRefresh?: () => void
onEndReached?: (info: {distanceFromEnd: number}) => void onEndReached?: (info: {distanceFromEnd: number}) => void
}) { }) {
const pal = usePalette('default')
const [selectedIndex, setSelectedIndex] = useState<number>(0) const [selectedIndex, setSelectedIndex] = useState<number>(0)
// events // events
@ -93,10 +94,15 @@ export function ViewSelector({
ListFooterComponent={ListFooterComponent} ListFooterComponent={ListFooterComponent}
// NOTE sticky header disabled on android due to major performance issues -prf // NOTE sticky header disabled on android due to major performance issues -prf
stickyHeaderIndices={isAndroid ? undefined : STICKY_HEADER_INDICES} stickyHeaderIndices={isAndroid ? undefined : STICKY_HEADER_INDICES}
refreshing={refreshing}
onScroll={onScroll} onScroll={onScroll}
onRefresh={onRefresh}
onEndReached={onEndReached} onEndReached={onEndReached}
refreshControl={
<RefreshControl
refreshing={refreshing!}
onRefresh={onRefresh}
tintColor={pal.colors.text}
/>
}
onEndReachedThreshold={0.6} onEndReachedThreshold={0.6}
contentContainerStyle={s.contentContainer} contentContainerStyle={s.contentContainer}
removeClippedSubviews={true} removeClippedSubviews={true}

View File

@ -126,5 +126,6 @@ const styles = StyleSheet.create({
}, },
fixedHeight: { fixedHeight: {
height: '100vh', height: '100vh',
scrollbarGutter: 'stable both-edges',
}, },
}) })

View File

@ -47,7 +47,7 @@ const styles = StyleSheet.create({
outer: { outer: {
position: 'absolute', position: 'absolute',
zIndex: 1, zIndex: 1,
right: 28, right: 24,
bottom: 94, bottom: 94,
width: 60, width: 60,
height: 60, height: 60,

View File

@ -136,7 +136,12 @@ export function DropdownButton({
} }
return ( return (
<View ref={ref2}> <View ref={ref2}>
<Button testID={testID} onPress={onPress} style={style} label={label}> <Button
type={type}
testID={testID}
onPress={onPress}
style={style}
label={label}>
{children} {children}
</Button> </Button>
</View> </View>

View File

@ -1,8 +1,8 @@
import React from 'react' import React from 'react'
import {StyleSheet, TouchableOpacity} from 'react-native' import {StyleSheet, TouchableOpacity} from 'react-native'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {Text} from '../text/Text' import {Text} from '../text/Text'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {UpIcon} from 'lib/icons'
import {LoadLatestBtn as LoadLatestBtnMobile} from './LoadLatestBtnMobile' import {LoadLatestBtn as LoadLatestBtnMobile} from './LoadLatestBtnMobile'
import {isMobileWeb} from 'platform/detection' import {isMobileWeb} from 'platform/detection'
@ -11,51 +11,97 @@ const HITSLOP = {left: 20, top: 20, right: 20, bottom: 20}
export const LoadLatestBtn = ({ export const LoadLatestBtn = ({
onPress, onPress,
label, label,
showIndicator,
minimalShellMode,
}: { }: {
onPress: () => void onPress: () => void
label: string label: string
showIndicator: boolean
minimalShellMode?: boolean
}) => { }) => {
const pal = usePalette('default') const pal = usePalette('default')
if (isMobileWeb) { if (isMobileWeb) {
return <LoadLatestBtnMobile onPress={onPress} label={label} /> return (
<LoadLatestBtnMobile
onPress={onPress}
label={label}
showIndicator={showIndicator}
/>
)
} }
return ( return (
<TouchableOpacity <>
style={[pal.view, pal.borderDark, styles.loadLatest]} {showIndicator && (
onPress={onPress} <TouchableOpacity
hitSlop={HITSLOP} style={[
accessibilityRole="button" pal.view,
accessibilityLabel={`Load new ${label}`} pal.borderDark,
accessibilityHint=""> styles.loadLatestCentered,
<Text type="md-bold" style={pal.text}> minimalShellMode && styles.loadLatestCenteredMinimal,
<UpIcon size={16} strokeWidth={1} style={[pal.text, styles.icon]} /> ]}
Load new {label} onPress={onPress}
</Text> hitSlop={HITSLOP}
</TouchableOpacity> accessibilityRole="button"
accessibilityLabel={label}
accessibilityHint="">
<Text type="md-bold" style={pal.text}>
{label}
</Text>
</TouchableOpacity>
)}
<TouchableOpacity
style={[pal.view, pal.borderDark, styles.loadLatest]}
onPress={onPress}
hitSlop={HITSLOP}
accessibilityRole="button"
accessibilityLabel={label}
accessibilityHint="">
<Text type="md-bold" style={pal.text}>
<FontAwesomeIcon
icon="angle-up"
size={21}
style={[pal.text, styles.icon]}
/>
</Text>
</TouchableOpacity>
</>
) )
} }
const styles = StyleSheet.create({ const styles = StyleSheet.create({
loadLatest: { loadLatest: {
flexDirection: 'row', flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
position: 'absolute', position: 'absolute',
left: '50vw', left: '50vw',
// @ts-ignore web only -prf // @ts-ignore web only -prf
transform: 'translateX(-50%)', transform: 'translateX(-282px)',
top: 60, bottom: 40,
shadowColor: '#000', width: 54,
shadowOpacity: 0.2, height: 54,
shadowOffset: {width: 0, height: 2},
shadowRadius: 4,
paddingLeft: 20,
paddingRight: 24,
paddingVertical: 10,
borderRadius: 30, borderRadius: 30,
borderWidth: 1, borderWidth: 1,
}, },
icon: { icon: {
position: 'relative', position: 'relative',
top: 2, top: 2,
marginRight: 5, },
loadLatestCentered: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
left: '50vw',
// @ts-ignore web only -prf
transform: 'translateX(-50%)',
top: 60,
paddingHorizontal: 24,
paddingVertical: 14,
borderRadius: 30,
borderWidth: 1,
},
loadLatestCenteredMinimal: {
top: 20,
}, },
}) })

View File

@ -1,23 +1,35 @@
import React from 'react' import React from 'react'
import {StyleSheet, TouchableOpacity} from 'react-native' import {StyleSheet, TouchableOpacity, View} from 'react-native'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import LinearGradient from 'react-native-linear-gradient' import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {useSafeAreaInsets} from 'react-native-safe-area-context' import {useSafeAreaInsets} from 'react-native-safe-area-context'
import {Text} from '../text/Text'
import {colors, gradients} from 'lib/styles'
import {clamp} from 'lodash' import {clamp} from 'lodash'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import {usePalette} from 'lib/hooks/usePalette'
import {colors} from 'lib/styles'
const HITSLOP = {left: 20, top: 20, right: 20, bottom: 20} const HITSLOP = {left: 20, top: 20, right: 20, bottom: 20}
export const LoadLatestBtn = observer( export const LoadLatestBtn = observer(
({onPress, label}: {onPress: () => void; label: string}) => { ({
onPress,
label,
showIndicator,
}: {
onPress: () => void
label: string
showIndicator: boolean
minimalShellMode?: boolean // NOTE not used on mobile -prf
}) => {
const store = useStores() const store = useStores()
const pal = usePalette('default')
const safeAreaInsets = useSafeAreaInsets() const safeAreaInsets = useSafeAreaInsets()
return ( return (
<TouchableOpacity <TouchableOpacity
style={[ style={[
styles.loadLatest, styles.loadLatest,
pal.borderDark,
pal.view,
!store.shell.minimalShellMode && { !store.shell.minimalShellMode && {
bottom: 60 + clamp(safeAreaInsets.bottom, 15, 30), bottom: 60 + clamp(safeAreaInsets.bottom, 15, 30),
}, },
@ -25,17 +37,10 @@ export const LoadLatestBtn = observer(
onPress={onPress} onPress={onPress}
hitSlop={HITSLOP} hitSlop={HITSLOP}
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel={`Load new ${label}`} accessibilityLabel={label}
accessibilityHint={`Loads new ${label}`}> accessibilityHint="">
<LinearGradient <FontAwesomeIcon icon="angle-up" color={pal.colors.text} size={19} />
colors={[gradients.blueLight.start, gradients.blueLight.end]} {showIndicator && <View style={[styles.indicator, pal.borderDark]} />}
start={{x: 0, y: 0}}
end={{x: 1, y: 1}}
style={styles.loadLatestInner}>
<Text type="md-bold" style={styles.loadLatestText}>
Load new {label}
</Text>
</LinearGradient>
</TouchableOpacity> </TouchableOpacity>
) )
}, },
@ -44,19 +49,24 @@ export const LoadLatestBtn = observer(
const styles = StyleSheet.create({ const styles = StyleSheet.create({
loadLatest: { loadLatest: {
position: 'absolute', position: 'absolute',
left: 20, left: 18,
bottom: 35, bottom: 35,
shadowColor: '#000', borderWidth: 1,
shadowOpacity: 0.3, width: 52,
shadowOffset: {width: 0, height: 1}, height: 52,
}, borderRadius: 26,
loadLatestInner: {
flexDirection: 'row', flexDirection: 'row',
paddingHorizontal: 14, alignItems: 'center',
paddingVertical: 10, justifyContent: 'center',
borderRadius: 30,
}, },
loadLatestText: { indicator: {
color: colors.white, position: 'absolute',
top: 3,
right: 3,
backgroundColor: colors.blue3,
width: 12,
height: 12,
borderRadius: 6,
borderWidth: 1,
}, },
}) })

View File

@ -27,6 +27,10 @@ export function ImageHider({
setOverride(false) setOverride(false)
}, [setOverride]) }, [setOverride])
if (moderation.behavior === ModerationBehaviorCode.Hide) {
return null
}
if (moderation.behavior !== ModerationBehaviorCode.WarnImages) { if (moderation.behavior !== ModerationBehaviorCode.WarnImages) {
return ( return (
<View testID={testID} style={style}> <View testID={testID} style={style}>
@ -35,10 +39,6 @@ export function ImageHider({
) )
} }
if (moderation.behavior === ModerationBehaviorCode.Hide) {
return null
}
return ( return (
<View style={[styles.container, containerStyle]}> <View style={[styles.container, containerStyle]}>
<View testID={testID} style={style}> <View testID={testID} style={style}>

View File

@ -3,3 +3,13 @@ export const formatCount = (num: number) =>
notation: 'compact', notation: 'compact',
maximumFractionDigits: 1, maximumFractionDigits: 1,
}).format(num) }).format(num)
export function formatCountShortOnly(num: number): string {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M'
}
if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K'
}
return String(num)
}

View File

@ -10,9 +10,6 @@ import {
FontAwesomeIcon, FontAwesomeIcon,
FontAwesomeIconStyle, FontAwesomeIconStyle,
} from '@fortawesome/react-native-fontawesome' } from '@fortawesome/react-native-fontawesome'
import ReactNativeHapticFeedback, {
HapticFeedbackTypes,
} from 'react-native-haptic-feedback'
// DISABLED see #135 // DISABLED see #135
// import { // import {
// TriggerableAnimated, // TriggerableAnimated,
@ -24,8 +21,8 @@ import {HeartIcon, HeartIconSolid, CommentBottomArrow} from 'lib/icons'
import {s, colors} from 'lib/styles' import {s, colors} from 'lib/styles'
import {useTheme} from 'lib/ThemeContext' import {useTheme} from 'lib/ThemeContext'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import {isIOS, isNative} from 'platform/detection'
import {RepostButton} from './RepostButton' import {RepostButton} from './RepostButton'
import {Haptics} from 'lib/haptics'
interface PostCtrlsOpts { interface PostCtrlsOpts {
itemUri: string itemUri: string
@ -58,7 +55,6 @@ interface PostCtrlsOpts {
} }
const HITSLOP = {top: 5, left: 5, bottom: 5, right: 5} const HITSLOP = {top: 5, left: 5, bottom: 5, right: 5}
const hapticImpact: HapticFeedbackTypes = isIOS ? 'impactMedium' : 'impactLight' // Users said the medium impact was too strong on Android; see APP-537
// DISABLED see #135 // DISABLED see #135
/* /*
@ -111,9 +107,7 @@ export function PostCtrls(opts: PostCtrlsOpts) {
const onRepost = useCallback(() => { const onRepost = useCallback(() => {
store.shell.closeModal() store.shell.closeModal()
if (!opts.isReposted) { if (!opts.isReposted) {
if (isNative) { Haptics.default()
ReactNativeHapticFeedback.trigger(hapticImpact)
}
opts.onPressToggleRepost().catch(_e => undefined) opts.onPressToggleRepost().catch(_e => undefined)
// DISABLED see #135 // DISABLED see #135
// repostRef.current?.trigger( // repostRef.current?.trigger(
@ -139,10 +133,7 @@ export function PostCtrls(opts: PostCtrlsOpts) {
indexedAt: opts.indexedAt, indexedAt: opts.indexedAt,
}, },
}) })
Haptics.default()
if (isNative) {
ReactNativeHapticFeedback.trigger(hapticImpact)
}
}, [ }, [
opts.author, opts.author,
opts.indexedAt, opts.indexedAt,
@ -154,7 +145,7 @@ export function PostCtrls(opts: PostCtrlsOpts) {
const onPressToggleLikeWrapper = async () => { const onPressToggleLikeWrapper = async () => {
if (!opts.isLiked) { if (!opts.isLiked) {
ReactNativeHapticFeedback.trigger(hapticImpact) Haptics.default()
await opts.onPressToggleLike().catch(_e => undefined) await opts.onPressToggleLike().catch(_e => undefined)
// DISABLED see #135 // DISABLED see #135
// likeRef.current?.trigger( // likeRef.current?.trigger(
@ -201,11 +192,11 @@ export function PostCtrls(opts: PostCtrlsOpts) {
accessibilityRole="button" accessibilityRole="button"
accessibilityLabel={opts.isLiked ? 'Unlike' : 'Like'} accessibilityLabel={opts.isLiked ? 'Unlike' : 'Like'}
accessibilityHint={ accessibilityHint={
opts.isReposted ? `Removes like from the post` : `Like the post` opts.isReposted ? 'Removes like from the post' : 'Like the post'
}> }>
{opts.isLiked ? ( {opts.isLiked ? (
<HeartIconSolid <HeartIconSolid
style={styles.ctrlIconLiked as StyleProp<ViewStyle>} style={styles.ctrlIconLiked}
size={opts.big ? 22 : 16} size={opts.big ? 22 : 16}
/> />
) : ( ) : (

View File

@ -13,6 +13,7 @@ import {
AppBskyEmbedRecord, AppBskyEmbedRecord,
AppBskyEmbedRecordWithMedia, AppBskyEmbedRecordWithMedia,
AppBskyFeedPost, AppBskyFeedPost,
AppBskyFeedDefs,
} from '@atproto/api' } from '@atproto/api'
import {Link} from '../Link' import {Link} from '../Link'
import {ImageLayoutGrid} from '../images/ImageLayoutGrid' import {ImageLayoutGrid} from '../images/ImageLayoutGrid'
@ -24,6 +25,8 @@ import {ExternalLinkEmbed} from './ExternalLinkEmbed'
import {getYoutubeVideoId} from 'lib/strings/url-helpers' import {getYoutubeVideoId} from 'lib/strings/url-helpers'
import QuoteEmbed from './QuoteEmbed' import QuoteEmbed from './QuoteEmbed'
import {AutoSizedImage} from '../images/AutoSizedImage' import {AutoSizedImage} from '../images/AutoSizedImage'
import {CustomFeed} from 'view/com/feeds/CustomFeed'
import {CustomFeedModel} from 'state/models/feeds/custom-feed'
type Embed = type Embed =
| AppBskyEmbedRecord.View | AppBskyEmbedRecord.View
@ -42,6 +45,8 @@ export function PostEmbeds({
const pal = usePalette('default') const pal = usePalette('default')
const store = useStores() const store = useStores()
// quote post with media
// =
if ( if (
AppBskyEmbedRecordWithMedia.isView(embed) && AppBskyEmbedRecordWithMedia.isView(embed) &&
AppBskyEmbedRecord.isViewRecord(embed.record.record) && AppBskyEmbedRecord.isViewRecord(embed.record.record) &&
@ -65,6 +70,8 @@ export function PostEmbeds({
) )
} }
// quote post
// =
if (AppBskyEmbedRecord.isView(embed)) { if (AppBskyEmbedRecord.isView(embed)) {
if ( if (
AppBskyEmbedRecord.isViewRecord(embed.record) && AppBskyEmbedRecord.isViewRecord(embed.record) &&
@ -87,6 +94,8 @@ export function PostEmbeds({
} }
} }
// image embed
// =
if (AppBskyEmbedImages.isView(embed)) { if (AppBskyEmbedImages.isView(embed)) {
const {images} = embed const {images} = embed
@ -132,10 +141,11 @@ export function PostEmbeds({
/> />
</View> </View>
) )
// }
} }
} }
// external link embed
// =
if (AppBskyEmbedExternal.isView(embed)) { if (AppBskyEmbedExternal.isView(embed)) {
const link = embed.external const link = embed.external
const youtubeVideoId = getYoutubeVideoId(link.uri) const youtubeVideoId = getYoutubeVideoId(link.uri)
@ -153,9 +163,35 @@ export function PostEmbeds({
</Link> </Link>
) )
} }
// custom feed embed (i.e. generator view)
// =
if (
AppBskyEmbedRecord.isView(embed) &&
AppBskyFeedDefs.isGeneratorView(embed.record)
) {
return <CustomFeedEmbed record={embed.record} />
}
return <View /> return <View />
} }
function CustomFeedEmbed({record}: {record: AppBskyFeedDefs.GeneratorView}) {
const pal = usePalette('default')
const store = useStores()
const item = React.useMemo(
() => new CustomFeedModel(store, record),
[store, record],
)
return (
<CustomFeed
item={item}
style={[pal.view, pal.border, styles.customFeedOuter]}
showLikes
/>
)
}
const styles = StyleSheet.create({ const styles = StyleSheet.create({
stackContainer: { stackContainer: {
gap: 6, gap: 6,
@ -172,6 +208,13 @@ const styles = StyleSheet.create({
borderRadius: 8, borderRadius: 8,
marginTop: 4, marginTop: 4,
}, },
customFeedOuter: {
borderWidth: 1,
borderRadius: 8,
marginTop: 4,
paddingHorizontal: 12,
paddingVertical: 12,
},
alt: { alt: {
backgroundColor: 'rgba(0, 0, 0, 0.75)', backgroundColor: 'rgba(0, 0, 0, 0.75)',
borderRadius: 6, borderRadius: 6,

View File

@ -8,6 +8,7 @@ import {faAngleUp} from '@fortawesome/free-solid-svg-icons/faAngleUp'
import {faArrowLeft} from '@fortawesome/free-solid-svg-icons/faArrowLeft' import {faArrowLeft} from '@fortawesome/free-solid-svg-icons/faArrowLeft'
import {faArrowRight} from '@fortawesome/free-solid-svg-icons/faArrowRight' import {faArrowRight} from '@fortawesome/free-solid-svg-icons/faArrowRight'
import {faArrowUp} from '@fortawesome/free-solid-svg-icons/faArrowUp' import {faArrowUp} from '@fortawesome/free-solid-svg-icons/faArrowUp'
import {faArrowDown} from '@fortawesome/free-solid-svg-icons/faArrowDown'
import {faArrowRightFromBracket} from '@fortawesome/free-solid-svg-icons/faArrowRightFromBracket' import {faArrowRightFromBracket} from '@fortawesome/free-solid-svg-icons/faArrowRightFromBracket'
import {faArrowUpFromBracket} from '@fortawesome/free-solid-svg-icons/faArrowUpFromBracket' import {faArrowUpFromBracket} from '@fortawesome/free-solid-svg-icons/faArrowUpFromBracket'
import {faArrowUpRightFromSquare} from '@fortawesome/free-solid-svg-icons/faArrowUpRightFromSquare' import {faArrowUpRightFromSquare} from '@fortawesome/free-solid-svg-icons/faArrowUpRightFromSquare'
@ -59,14 +60,17 @@ import {faPenNib} from '@fortawesome/free-solid-svg-icons/faPenNib'
import {faPenToSquare} from '@fortawesome/free-solid-svg-icons/faPenToSquare' import {faPenToSquare} from '@fortawesome/free-solid-svg-icons/faPenToSquare'
import {faPlus} from '@fortawesome/free-solid-svg-icons/faPlus' import {faPlus} from '@fortawesome/free-solid-svg-icons/faPlus'
import {faQuoteLeft} from '@fortawesome/free-solid-svg-icons/faQuoteLeft' import {faQuoteLeft} from '@fortawesome/free-solid-svg-icons/faQuoteLeft'
import {faReply} from '@fortawesome/free-solid-svg-icons/faReply'
import {faRetweet} from '@fortawesome/free-solid-svg-icons/faRetweet'
import {faRss} from '@fortawesome/free-solid-svg-icons/faRss'
import {faSatelliteDish} from '@fortawesome/free-solid-svg-icons/faSatelliteDish'
import {faShare} from '@fortawesome/free-solid-svg-icons/faShare' import {faShare} from '@fortawesome/free-solid-svg-icons/faShare'
import {faShareFromSquare} from '@fortawesome/free-solid-svg-icons/faShareFromSquare' import {faShareFromSquare} from '@fortawesome/free-solid-svg-icons/faShareFromSquare'
import {faShield} from '@fortawesome/free-solid-svg-icons/faShield' import {faShield} from '@fortawesome/free-solid-svg-icons/faShield'
import {faSquarePlus} from '@fortawesome/free-regular-svg-icons/faSquarePlus' import {faSquarePlus} from '@fortawesome/free-regular-svg-icons/faSquarePlus'
import {faSignal} from '@fortawesome/free-solid-svg-icons/faSignal' import {faSignal} from '@fortawesome/free-solid-svg-icons/faSignal'
import {faReply} from '@fortawesome/free-solid-svg-icons/faReply' import {faTicket} from '@fortawesome/free-solid-svg-icons/faTicket'
import {faRetweet} from '@fortawesome/free-solid-svg-icons/faRetweet' import {faTrashCan} from '@fortawesome/free-regular-svg-icons/faTrashCan'
import {faRss} from '@fortawesome/free-solid-svg-icons/faRss'
import {faUser} from '@fortawesome/free-regular-svg-icons/faUser' import {faUser} from '@fortawesome/free-regular-svg-icons/faUser'
import {faUsers} from '@fortawesome/free-solid-svg-icons/faUsers' import {faUsers} from '@fortawesome/free-solid-svg-icons/faUsers'
import {faUserCheck} from '@fortawesome/free-solid-svg-icons/faUserCheck' import {faUserCheck} from '@fortawesome/free-solid-svg-icons/faUserCheck'
@ -74,12 +78,11 @@ import {faUserSlash} from '@fortawesome/free-solid-svg-icons/faUserSlash'
import {faUserPlus} from '@fortawesome/free-solid-svg-icons/faUserPlus' import {faUserPlus} from '@fortawesome/free-solid-svg-icons/faUserPlus'
import {faUserXmark} from '@fortawesome/free-solid-svg-icons/faUserXmark' import {faUserXmark} from '@fortawesome/free-solid-svg-icons/faUserXmark'
import {faUsersSlash} from '@fortawesome/free-solid-svg-icons/faUsersSlash' import {faUsersSlash} from '@fortawesome/free-solid-svg-icons/faUsersSlash'
import {faTicket} from '@fortawesome/free-solid-svg-icons/faTicket'
import {faTrashCan} from '@fortawesome/free-regular-svg-icons/faTrashCan'
import {faX} from '@fortawesome/free-solid-svg-icons/faX' import {faX} from '@fortawesome/free-solid-svg-icons/faX'
import {faXmark} from '@fortawesome/free-solid-svg-icons/faXmark' import {faXmark} from '@fortawesome/free-solid-svg-icons/faXmark'
import {faPlay} from '@fortawesome/free-solid-svg-icons/faPlay' import {faPlay} from '@fortawesome/free-solid-svg-icons/faPlay'
import {faPause} from '@fortawesome/free-solid-svg-icons/faPause' import {faPause} from '@fortawesome/free-solid-svg-icons/faPause'
import {faThumbtack} from '@fortawesome/free-solid-svg-icons/faThumbtack'
export function setup() { export function setup() {
library.add( library.add(
@ -91,6 +94,7 @@ export function setup() {
faArrowLeft, faArrowLeft,
faArrowRight, faArrowRight,
faArrowUp, faArrowUp,
faArrowDown,
faArrowRightFromBracket, faArrowRightFromBracket,
faArrowUpFromBracket, faArrowUpFromBracket,
faArrowUpRightFromSquare, faArrowUpRightFromSquare,
@ -145,6 +149,7 @@ export function setup() {
faReply, faReply,
faRetweet, faRetweet,
faRss, faRss,
faSatelliteDish,
faShare, faShare,
faShareFromSquare, faShareFromSquare,
faShield, faShield,
@ -159,6 +164,7 @@ export function setup() {
faUsersSlash, faUsersSlash,
faTicket, faTicket,
faTrashCan, faTrashCan,
faThumbtack,
faX, faX,
faXmark, faXmark,
faPlay, faPlay,

View File

@ -0,0 +1,418 @@
import React, {useMemo, useRef} from 'react'
import {NativeStackScreenProps} from '@react-navigation/native-stack'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {usePalette} from 'lib/hooks/usePalette'
import {HeartIcon, HeartIconSolid} from 'lib/icons'
import {CommonNavigatorParams} from 'lib/routes/types'
import {makeRecordUri} from 'lib/strings/url-helpers'
import {colors, s} from 'lib/styles'
import {observer} from 'mobx-react-lite'
import {FlatList, StyleSheet, View} from 'react-native'
import {useStores} from 'state/index'
import {PostsFeedModel} from 'state/models/feeds/posts'
import {useCustomFeed} from 'lib/hooks/useCustomFeed'
import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {Feed} from 'view/com/posts/Feed'
import {pluralize} from 'lib/strings/helpers'
import {TextLink} from 'view/com/util/Link'
import {UserAvatar} from 'view/com/util/UserAvatar'
import {ViewHeader} from 'view/com/util/ViewHeader'
import {Button} from 'view/com/util/forms/Button'
import {Text} from 'view/com/util/text/Text'
import * as Toast from 'view/com/util/Toast'
import {isDesktopWeb} from 'platform/detection'
import {useSetTitle} from 'lib/hooks/useSetTitle'
import {shareUrl} from 'lib/sharing'
import {toShareUrl} from 'lib/strings/url-helpers'
import {Haptics} from 'lib/haptics'
import {ComposeIcon2} from 'lib/icons'
import {FAB} from '../com/util/fab/FAB'
import {LoadLatestBtn} from 'view/com/util/load-latest/LoadLatestBtn'
import {DropdownButton, DropdownItem} from 'view/com/util/forms/DropdownButton'
import {useOnMainScroll} from 'lib/hooks/useOnMainScroll'
import {EmptyState} from 'view/com/util/EmptyState'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'CustomFeed'>
export const CustomFeedScreen = withAuthRequired(
observer(({route}: Props) => {
const store = useStores()
const pal = usePalette('default')
const {rkey, name} = route.params
const uri = useMemo(
() => makeRecordUri(name, 'app.bsky.feed.generator', rkey),
[rkey, name],
)
const scrollElRef = useRef<FlatList>(null)
const currentFeed = useCustomFeed(uri)
const algoFeed: PostsFeedModel = useMemo(() => {
const feed = new PostsFeedModel(store, 'custom', {
feed: uri,
})
feed.setup()
return feed
}, [store, uri])
const isPinned = store.me.savedFeeds.isPinned(uri)
const [onMainScroll, isScrolledDown, resetMainScroll] =
useOnMainScroll(store)
useSetTitle(currentFeed?.displayName)
const onToggleSaved = React.useCallback(async () => {
try {
Haptics.default()
if (currentFeed?.isSaved) {
await currentFeed?.unsave()
} else {
await currentFeed?.save()
}
} catch (err) {
Toast.show(
'There was an an issue updating your feeds, please check your internet connection and try again.',
)
store.log.error('Failed up update feeds', {err})
}
}, [store, currentFeed])
const onToggleLiked = React.useCallback(async () => {
Haptics.default()
try {
if (currentFeed?.isLiked) {
await currentFeed?.unlike()
} else {
await currentFeed?.like()
}
} catch (err) {
Toast.show(
'There was an an issue contacting the server, please check your internet connection and try again.',
)
store.log.error('Failed up toggle like', {err})
}
}, [store, currentFeed])
const onTogglePinned = React.useCallback(async () => {
Haptics.default()
store.me.savedFeeds.togglePinnedFeed(currentFeed!).catch(e => {
Toast.show('There was an issue contacting the server')
store.log.error('Failed to toggle pinned feed', {e})
})
}, [store, currentFeed])
const onPressShare = React.useCallback(() => {
const url = toShareUrl(`/profile/${name}/feed/${rkey}`)
shareUrl(url)
}, [name, rkey])
const onScrollToTop = React.useCallback(() => {
scrollElRef.current?.scrollToOffset({offset: 0, animated: true})
resetMainScroll()
}, [scrollElRef, resetMainScroll])
const onPressCompose = React.useCallback(() => {
store.shell.openComposer({})
}, [store])
const dropdownItems: DropdownItem[] = React.useMemo(() => {
let items: DropdownItem[] = [
{
testID: 'feedHeaderDropdownRemoveBtn',
label: 'Remove from my feeds',
onPress: onToggleSaved,
},
{
testID: 'feedHeaderDropdownShareBtn',
label: 'Share link',
onPress: onPressShare,
},
]
return items
}, [onToggleSaved, onPressShare])
const renderHeaderBtns = React.useCallback(() => {
return (
<View style={styles.headerBtns}>
<Button
type="default-light"
testID="toggleLikeBtn"
accessibilityLabel="Like this feed"
accessibilityHint=""
onPress={onToggleLiked}>
{currentFeed?.isLiked ? (
<HeartIconSolid size={19} style={styles.liked} />
) : (
<HeartIcon strokeWidth={3} size={19} style={pal.textLight} />
)}
</Button>
{currentFeed?.isSaved ? (
<Button
type="default-light"
accessibilityLabel={
isPinned ? 'Unpin this feed' : 'Pin this feed'
}
accessibilityHint=""
onPress={onTogglePinned}>
<FontAwesomeIcon
icon="thumb-tack"
size={17}
color={isPinned ? colors.blue3 : pal.colors.textLight}
style={styles.top1}
/>
</Button>
) : undefined}
{currentFeed?.isSaved ? (
<DropdownButton
testID="feedHeaderDropdownBtn"
type="default-light"
items={dropdownItems}
menuWidth={250}>
<FontAwesomeIcon
icon="ellipsis"
color={pal.colors.textLight}
size={18}
/>
</DropdownButton>
) : (
<Button
type="default-light"
onPress={onToggleSaved}
accessibilityLabel="Add to my feeds"
accessibilityHint=""
style={styles.headerAddBtn}>
<FontAwesomeIcon icon="plus" color={pal.colors.link} size={19} />
<Text type="xl-medium" style={pal.link}>
Add to My Feeds
</Text>
</Button>
)}
</View>
)
}, [
pal,
currentFeed?.isSaved,
currentFeed?.isLiked,
isPinned,
onToggleSaved,
onTogglePinned,
onToggleLiked,
dropdownItems,
])
const renderListHeaderComponent = React.useCallback(() => {
return (
<>
<View style={[styles.header, pal.border]}>
<View style={s.flex1}>
<Text
testID="feedName"
type="title-xl"
style={[pal.text, s.bold]}>
{currentFeed?.displayName}
</Text>
{currentFeed && (
<Text type="md" style={[pal.textLight]} numberOfLines={1}>
by{' '}
{currentFeed.data.creator.did === store.me.did ? (
'you'
) : (
<TextLink
text={`@${currentFeed.data.creator.handle}`}
href={`/profile/${currentFeed.data.creator.did}`}
style={[pal.textLight]}
/>
)}
</Text>
)}
{isDesktopWeb && (
<View style={[styles.headerBtns, styles.headerBtnsDesktop]}>
<Button
type={currentFeed?.isSaved ? 'default' : 'inverted'}
onPress={onToggleSaved}
accessibilityLabel={
currentFeed?.isSaved
? 'Unsave this feed'
: 'Save this feed'
}
accessibilityHint=""
label={
currentFeed?.isSaved
? 'Remove from My Feeds'
: 'Add to My Feeds'
}
/>
<Button
type="default"
accessibilityLabel={
isPinned ? 'Unpin this feed' : 'Pin this feed'
}
accessibilityHint=""
onPress={onTogglePinned}>
<FontAwesomeIcon
icon="thumb-tack"
size={15}
color={isPinned ? colors.blue3 : pal.colors.icon}
style={styles.top2}
/>
</Button>
<Button
type="default"
accessibilityLabel="Like this feed"
accessibilityHint=""
onPress={onToggleLiked}>
{currentFeed?.isLiked ? (
<HeartIconSolid size={18} style={styles.liked} />
) : (
<HeartIcon strokeWidth={3} size={18} style={pal.icon} />
)}
</Button>
<Button
type="default"
accessibilityLabel="Share this feed"
accessibilityHint=""
onPress={onPressShare}>
<FontAwesomeIcon
icon="share"
size={18}
color={pal.colors.icon}
/>
</Button>
</View>
)}
</View>
<View>
<UserAvatar
type="algo"
avatar={currentFeed?.data.avatar}
size={64}
/>
</View>
</View>
<View style={styles.headerDetails}>
{currentFeed?.data.description ? (
<Text style={[pal.text, s.mb10]} numberOfLines={6}>
{currentFeed.data.description}
</Text>
) : null}
<View style={styles.headerDetailsFooter}>
{currentFeed ? (
<TextLink
type="md-medium"
style={pal.textLight}
href={`/profile/${name}/feed/${rkey}/liked-by`}
text={`Liked by ${currentFeed.data.likeCount} ${pluralize(
currentFeed?.data.likeCount || 0,
'user',
)}`}
/>
) : null}
</View>
</View>
<View style={[styles.fakeSelector, pal.border]}>
<View
style={[styles.fakeSelectorItem, {borderColor: pal.colors.link}]}>
<Text type="md-medium" style={[pal.text]}>
Feed
</Text>
</View>
</View>
</>
)
}, [
pal,
currentFeed,
store.me.did,
onToggleSaved,
onToggleLiked,
onPressShare,
name,
rkey,
isPinned,
onTogglePinned,
])
const renderEmptyState = React.useCallback(() => {
return <EmptyState icon="feed" message="This list is empty!" />
}, [])
return (
<View style={s.hContentRegion}>
<ViewHeader title="" renderButton={currentFeed && renderHeaderBtns} />
<Feed
scrollElRef={scrollElRef}
feed={algoFeed}
onScroll={onMainScroll}
scrollEventThrottle={100}
ListHeaderComponent={renderListHeaderComponent}
renderEmptyState={renderEmptyState}
extraData={[uri, isPinned]}
/>
{isScrolledDown ? (
<LoadLatestBtn
onPress={onScrollToTop}
label="Scroll to top"
showIndicator={false}
/>
) : null}
<FAB
testID="composeFAB"
onPress={onPressCompose}
icon={<ComposeIcon2 strokeWidth={1.5} size={29} style={s.white} />}
accessibilityRole="button"
accessibilityLabel="Compose post"
accessibilityHint=""
/>
</View>
)
}),
)
const styles = StyleSheet.create({
header: {
flexDirection: 'row',
gap: 12,
paddingHorizontal: 16,
paddingTop: 12,
paddingBottom: 16,
borderTopWidth: 1,
},
headerBtns: {
flexDirection: 'row',
alignItems: 'center',
},
headerBtnsDesktop: {
marginTop: 8,
gap: 4,
},
headerAddBtn: {
flexDirection: 'row',
alignItems: 'center',
gap: 4,
paddingLeft: 4,
},
headerDetails: {
paddingHorizontal: 16,
paddingBottom: 16,
},
headerDetailsFooter: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
fakeSelector: {
flexDirection: 'row',
paddingHorizontal: isDesktopWeb ? 16 : 6,
},
fakeSelectorItem: {
paddingHorizontal: 12,
paddingBottom: 8,
borderBottomWidth: 3,
},
liked: {
color: colors.red3,
},
top1: {
position: 'relative',
top: 1,
},
top2: {
position: 'relative',
top: 2,
},
})

View File

@ -0,0 +1,29 @@
import React from 'react'
import {View} from 'react-native'
import {useFocusEffect} from '@react-navigation/native'
import {NativeStackScreenProps, CommonNavigatorParams} from 'lib/routes/types'
import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {ViewHeader} from '../com/util/ViewHeader'
import {PostLikedBy as PostLikedByComponent} from '../com/post-thread/PostLikedBy'
import {useStores} from 'state/index'
import {makeRecordUri} from 'lib/strings/url-helpers'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'CustomFeedLikedBy'>
export const CustomFeedLikedByScreen = withAuthRequired(({route}: Props) => {
const store = useStores()
const {name, rkey} = route.params
const uri = makeRecordUri(name, 'app.bsky.feed.generator', rkey)
useFocusEffect(
React.useCallback(() => {
store.shell.setMinimalShellMode(false)
}, [store]),
)
return (
<View>
<ViewHeader title="Liked by" />
<PostLikedByComponent uri={uri} />
</View>
)
})

View File

@ -0,0 +1,112 @@
import React from 'react'
import {RefreshControl, StyleSheet, View} from 'react-native'
import {observer} from 'mobx-react-lite'
import {useFocusEffect} from '@react-navigation/native'
import {NativeStackScreenProps, CommonNavigatorParams} from 'lib/routes/types'
import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {ViewHeader} from '../com/util/ViewHeader'
import {useStores} from 'state/index'
import {FeedsDiscoveryModel} from 'state/models/discovery/feeds'
import {CenteredView, FlatList} from 'view/com/util/Views'
import {CustomFeed} from 'view/com/feeds/CustomFeed'
import {Text} from 'view/com/util/text/Text'
import {isDesktopWeb} from 'platform/detection'
import {usePalette} from 'lib/hooks/usePalette'
import {s} from 'lib/styles'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'DiscoverFeeds'>
export const DiscoverFeedsScreen = withAuthRequired(
observer(({}: Props) => {
const store = useStores()
const pal = usePalette('default')
const feeds = React.useMemo(() => new FeedsDiscoveryModel(store), [store])
useFocusEffect(
React.useCallback(() => {
store.shell.setMinimalShellMode(false)
feeds.refresh()
}, [store, feeds]),
)
const onRefresh = React.useCallback(() => {
store.me.savedFeeds.refresh()
}, [store])
const renderListEmptyComponent = React.useCallback(() => {
return (
<View
style={[
pal.border,
!isDesktopWeb && s.flex1,
pal.viewLight,
styles.empty,
]}>
<Text type="lg" style={[pal.text]}>
{feeds.isLoading
? 'Loading...'
: `We can't find any feeds for some reason. This is probably an error - try refreshing!`}
</Text>
</View>
)
}, [pal, feeds.isLoading])
const renderItem = React.useCallback(
({item}) => (
<CustomFeed
key={item.data.uri}
item={item}
showSaveBtn
showDescription
showLikes
/>
),
[],
)
return (
<CenteredView style={[styles.container, pal.view]}>
<View style={[isDesktopWeb && styles.containerDesktop, pal.border]}>
<ViewHeader title="Discover Feeds" showOnDesktop />
</View>
<FlatList
style={[!isDesktopWeb && s.flex1]}
data={feeds.feeds}
keyExtractor={item => item.data.uri}
contentContainerStyle={styles.contentContainer}
refreshControl={
<RefreshControl
refreshing={feeds.isRefreshing}
onRefresh={onRefresh}
tintColor={pal.colors.text}
titleColor={pal.colors.text}
/>
}
renderItem={renderItem}
initialNumToRender={10}
ListEmptyComponent={renderListEmptyComponent}
extraData={feeds.isLoading}
/>
</CenteredView>
)
}),
)
const styles = StyleSheet.create({
container: {
flex: 1,
},
contentContainer: {
paddingBottom: 100,
},
containerDesktop: {
borderLeftWidth: 1,
borderRightWidth: 1,
},
empty: {
paddingHorizontal: 18,
paddingVertical: 16,
borderRadius: 8,
marginHorizontal: 18,
marginTop: 10,
},
})

View File

@ -0,0 +1,126 @@
import React from 'react'
import {StyleSheet, View} from 'react-native'
import {useFocusEffect} from '@react-navigation/native'
import isEqual from 'lodash.isequal'
import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {FlatList} from 'view/com/util/Views'
import {ViewHeader} from 'view/com/util/ViewHeader'
import {LoadLatestBtn} from 'view/com/util/load-latest/LoadLatestBtn'
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 {PostsMultiFeedModel} from 'state/models/feeds/multi-feed'
import {MultiFeed} from 'view/com/posts/MultiFeed'
import {isDesktopWeb} from 'platform/detection'
import {usePalette} from 'lib/hooks/usePalette'
import {useStores} from 'state/index'
import {useOnMainScroll} from 'lib/hooks/useOnMainScroll'
import {ComposeIcon2, CogIcon} from 'lib/icons'
import {s} from 'lib/styles'
const HEADER_OFFSET = isDesktopWeb ? 0 : 40
type Props = NativeStackScreenProps<FeedsTabNavigatorParams, 'Feeds'>
export const FeedsScreen = withAuthRequired(
observer<Props>(({}: Props) => {
const pal = usePalette('default')
const store = useStores()
const flatListRef = React.useRef<FlatList>(null)
const multifeed = React.useMemo<PostsMultiFeedModel>(
() => new PostsMultiFeedModel(store),
[store],
)
const [onMainScroll, isScrolledDown, resetMainScroll] =
useOnMainScroll(store)
const onSoftReset = React.useCallback(() => {
flatListRef.current?.scrollToOffset({offset: 0})
resetMainScroll()
}, [flatListRef, resetMainScroll])
useFocusEffect(
React.useCallback(() => {
const softResetSub = store.onScreenSoftReset(onSoftReset)
const multifeedCleanup = multifeed.registerListeners()
const cleanup = () => {
softResetSub.remove()
multifeedCleanup()
}
store.shell.setMinimalShellMode(false)
return cleanup
}, [store, multifeed, onSoftReset]),
)
React.useEffect(() => {
if (
isEqual(
multifeed.feedInfos.map(f => f.uri),
store.me.savedFeeds.all.map(f => f.uri),
)
) {
// no changes
return
}
multifeed.refresh()
}, [multifeed, store.me.savedFeeds.all])
const onPressCompose = React.useCallback(() => {
store.shell.openComposer({})
}, [store])
const renderHeaderBtn = React.useCallback(() => {
return (
<Link
href="/settings/saved-feeds"
hitSlop={10}
accessibilityRole="button"
accessibilityLabel="Edit Saved Feeds"
accessibilityHint="Opens screen to edit Saved Feeds">
<CogIcon size={22} strokeWidth={2} style={pal.textLight} />
</Link>
)
}, [pal])
return (
<View style={[pal.view, styles.container]}>
<MultiFeed
scrollElRef={flatListRef}
multifeed={multifeed}
onScroll={onMainScroll}
scrollEventThrottle={100}
headerOffset={HEADER_OFFSET}
showPostFollowBtn
/>
<ViewHeader
title="My Feeds"
canGoBack={false}
hideOnScroll
renderButton={renderHeaderBtn}
/>
{isScrolledDown ? (
<LoadLatestBtn
onPress={onSoftReset}
label="Scroll to top"
showIndicator={false}
/>
) : null}
<FAB
testID="composeFAB"
onPress={onPressCompose}
icon={<ComposeIcon2 strokeWidth={1.5} size={29} style={s.white} />}
accessibilityRole="button"
accessibilityLabel="Compose post"
accessibilityHint=""
/>
</View>
)
}),
)
const styles = StyleSheet.create({
container: {
flex: 1,
},
})

View File

@ -1,18 +1,20 @@
import React from 'react' import React from 'react'
import {FlatList, View} from 'react-native' import {FlatList, View} from 'react-native'
import {useFocusEffect, useIsFocused} from '@react-navigation/native' import {useFocusEffect, useIsFocused} from '@react-navigation/native'
import {AppBskyFeedGetFeed as GetCustomFeed} from '@atproto/api'
import {observer} from 'mobx-react-lite' import {observer} from 'mobx-react-lite'
import useAppState from 'react-native-appstate-hook' import useAppState from 'react-native-appstate-hook'
import isEqual from 'lodash.isequal'
import {NativeStackScreenProps, HomeTabNavigatorParams} from 'lib/routes/types' import {NativeStackScreenProps, HomeTabNavigatorParams} from 'lib/routes/types'
import {PostsFeedModel} from 'state/models/feeds/posts' import {PostsFeedModel} from 'state/models/feeds/posts'
import {withAuthRequired} from 'view/com/auth/withAuthRequired' import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {useTabFocusEffect} from 'lib/hooks/useTabFocusEffect' import {useTabFocusEffect} from 'lib/hooks/useTabFocusEffect'
import {Feed} from '../com/posts/Feed' import {Feed} from '../com/posts/Feed'
import {FollowingEmptyState} from 'view/com/posts/FollowingEmptyState' import {FollowingEmptyState} from 'view/com/posts/FollowingEmptyState'
import {WhatsHotEmptyState} from 'view/com/posts/WhatsHotEmptyState' import {CustomFeedEmptyState} from 'view/com/posts/CustomFeedEmptyState'
import {LoadLatestBtn} from '../com/util/load-latest/LoadLatestBtn' import {LoadLatestBtn} from '../com/util/load-latest/LoadLatestBtn'
import {FeedsTabBar} from '../com/pager/FeedsTabBar' import {FeedsTabBar} from '../com/pager/FeedsTabBar'
import {Pager, RenderTabBarFnProps} from 'view/com/pager/Pager' import {Pager, PagerRef, RenderTabBarFnProps} from 'view/com/pager/Pager'
import {FAB} from '../com/util/fab/FAB' import {FAB} from '../com/util/fab/FAB'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import {s} from 'lib/styles' import {s} from 'lib/styles'
@ -21,30 +23,37 @@ import {useAnalytics} from 'lib/analytics'
import {ComposeIcon2} from 'lib/icons' import {ComposeIcon2} from 'lib/icons'
import {isDesktopWeb} from 'platform/detection' import {isDesktopWeb} from 'platform/detection'
const HEADER_OFFSET = isDesktopWeb ? 50 : 40 const HEADER_OFFSET = isDesktopWeb ? 50 : 78
const POLL_FREQ = 30e3 // 30sec const POLL_FREQ = 30e3 // 30sec
type Props = NativeStackScreenProps<HomeTabNavigatorParams, 'Home'> type Props = NativeStackScreenProps<HomeTabNavigatorParams, 'Home'>
export const HomeScreen = withAuthRequired( export const HomeScreen = withAuthRequired(
observer((_opts: Props) => { observer((_opts: Props) => {
const store = useStores() const store = useStores()
const pagerRef = React.useRef<PagerRef>(null)
const [selectedPage, setSelectedPage] = React.useState(0) const [selectedPage, setSelectedPage] = React.useState(0)
const [initialLanguages] = React.useState( const [customFeeds, setCustomFeeds] = React.useState<PostsFeedModel[]>([])
store.preferences.contentLanguages,
)
const algoFeed: PostsFeedModel = React.useMemo(() => {
const feed = new PostsFeedModel(store, 'goodstuff', {})
feed.setup()
return feed
}, [store])
React.useEffect(() => { React.useEffect(() => {
// refresh whats hot when lang preferences change const {pinned} = store.me.savedFeeds
if (initialLanguages !== store.preferences.contentLanguages) { if (
algoFeed.refresh() isEqual(
pinned.map(p => p.uri),
customFeeds.map(f => (f.params as GetCustomFeed.QueryParams).feed),
)
) {
// no changes
return
} }
}, [initialLanguages, store.preferences.contentLanguages, algoFeed])
const feeds = []
for (const feed of pinned) {
const model = new PostsFeedModel(store, 'custom', {feed: feed.uri})
model.setup()
feeds.push(model)
}
setCustomFeeds(feeds)
}, [store, store.me.savedFeeds.pinned, customFeeds, setCustomFeeds])
useFocusEffect( useFocusEffect(
React.useCallback(() => { React.useCallback(() => {
@ -86,18 +95,17 @@ export const HomeScreen = withAuthRequired(
return <FollowingEmptyState /> return <FollowingEmptyState />
}, []) }, [])
const renderWhatsHotEmptyState = React.useCallback(() => { const renderCustomFeedEmptyState = React.useCallback(() => {
return <WhatsHotEmptyState /> return <CustomFeedEmptyState />
}, []) }, [])
const initialPage = store.me.followsCount === 0 ? 1 : 0
return ( return (
<Pager <Pager
ref={pagerRef}
testID="homeScreen" testID="homeScreen"
onPageSelected={onPageSelected} onPageSelected={onPageSelected}
renderTabBar={renderTabBar} renderTabBar={renderTabBar}
tabBarPosition="top" tabBarPosition="top">
initialPage={initialPage}>
<FeedPage <FeedPage
key="1" key="1"
testID="followingFeedPage" testID="followingFeedPage"
@ -105,13 +113,17 @@ export const HomeScreen = withAuthRequired(
feed={store.me.mainFeed} feed={store.me.mainFeed}
renderEmptyState={renderFollowingEmptyState} renderEmptyState={renderFollowingEmptyState}
/> />
<FeedPage {customFeeds.map((f, index) => {
key="2" return (
testID="whatshotFeedPage" <FeedPage
isPageFocused={selectedPage === 1} key={(f.params as GetCustomFeed.QueryParams).feed}
feed={algoFeed} testID="customFeedPage"
renderEmptyState={renderWhatsHotEmptyState} isPageFocused={selectedPage === 1 + index}
/> feed={f}
renderEmptyState={renderCustomFeedEmptyState}
/>
)
})}
</Pager> </Pager>
) )
}), }),
@ -130,7 +142,8 @@ const FeedPage = observer(
renderEmptyState?: () => JSX.Element renderEmptyState?: () => JSX.Element
}) => { }) => {
const store = useStores() const store = useStores()
const onMainScroll = useOnMainScroll(store) const [onMainScroll, isScrolledDown, resetMainScroll] =
useOnMainScroll(store)
const {screen, track} = useAnalytics() const {screen, track} = useAnalytics()
const scrollElRef = React.useRef<FlatList>(null) const scrollElRef = React.useRef<FlatList>(null)
const {appState} = useAppState({ const {appState} = useAppState({
@ -158,12 +171,13 @@ const FeedPage = observer(
const scrollToTop = React.useCallback(() => { const scrollToTop = React.useCallback(() => {
scrollElRef.current?.scrollToOffset({offset: -HEADER_OFFSET}) scrollElRef.current?.scrollToOffset({offset: -HEADER_OFFSET})
}, [scrollElRef]) resetMainScroll()
}, [scrollElRef, resetMainScroll])
const onSoftReset = React.useCallback(() => { const onSoftReset = React.useCallback(() => {
if (isPageFocused) { if (isPageFocused) {
feed.refresh()
scrollToTop() scrollToTop()
feed.refresh()
} }
}, [isPageFocused, scrollToTop, feed]) }, [isPageFocused, scrollToTop, feed])
@ -224,6 +238,7 @@ const FeedPage = observer(
feed.refresh() feed.refresh()
}, [feed, scrollToTop]) }, [feed, scrollToTop])
const hasNew = feed.hasNewLatest && !feed.isRefreshing
return ( return (
<View testID={testID} style={s.h100pct}> <View testID={testID} style={s.h100pct}>
<Feed <Feed
@ -234,11 +249,17 @@ const FeedPage = observer(
showPostFollowBtn showPostFollowBtn
onPressTryAgain={onPressTryAgain} onPressTryAgain={onPressTryAgain}
onScroll={onMainScroll} onScroll={onMainScroll}
scrollEventThrottle={100}
renderEmptyState={renderEmptyState} renderEmptyState={renderEmptyState}
headerOffset={HEADER_OFFSET} headerOffset={HEADER_OFFSET}
/> />
{feed.hasNewLatest && !feed.isRefreshing && ( {(isScrolledDown || hasNew) && (
<LoadLatestBtn onPress={onPressLoadLatest} label="posts" /> <LoadLatestBtn
onPress={onPressLoadLatest}
label="Load new posts"
showIndicator={hasNew}
minimalShellMode={store.shell.minimalShellMode}
/>
)} )}
<FAB <FAB
testID="composeFAB" testID="composeFAB"

View File

@ -100,7 +100,7 @@ export const ModerationMutedAccounts = withAuthRequired(
<FlatList <FlatList
style={[!isDesktopWeb && styles.flex1]} style={[!isDesktopWeb && styles.flex1]}
data={mutedAccounts.mutes} data={mutedAccounts.mutes}
keyExtractor={(item: ActorDefs.ProfileView) => item.did} keyExtractor={item => item.did}
refreshControl={ refreshControl={
<RefreshControl <RefreshControl
refreshing={mutedAccounts.isRefreshing} refreshing={mutedAccounts.isRefreshing}

View File

@ -25,7 +25,8 @@ type Props = NativeStackScreenProps<
export const NotificationsScreen = withAuthRequired( export const NotificationsScreen = withAuthRequired(
observer(({}: Props) => { observer(({}: Props) => {
const store = useStores() const store = useStores()
const onMainScroll = useOnMainScroll(store) const [onMainScroll, isScrolledDown, resetMainScroll] =
useOnMainScroll(store)
const scrollElRef = React.useRef<FlatList>(null) const scrollElRef = React.useRef<FlatList>(null)
const {screen} = useAnalytics() const {screen} = useAnalytics()
@ -37,7 +38,8 @@ export const NotificationsScreen = withAuthRequired(
const scrollToTop = React.useCallback(() => { const scrollToTop = React.useCallback(() => {
scrollElRef.current?.scrollToOffset({offset: 0}) scrollElRef.current?.scrollToOffset({offset: 0})
}, [scrollElRef]) resetMainScroll()
}, [scrollElRef, resetMainScroll])
const onPressLoadLatest = React.useCallback(() => { const onPressLoadLatest = React.useCallback(() => {
scrollToTop() scrollToTop()
@ -86,6 +88,9 @@ export const NotificationsScreen = withAuthRequired(
), ),
) )
const hasNew =
store.me.notifications.hasNewLatest &&
!store.me.notifications.isRefreshing
return ( return (
<View testID="notificationsScreen" style={s.hContentRegion}> <View testID="notificationsScreen" style={s.hContentRegion}>
<ViewHeader title="Notifications" canGoBack={false} /> <ViewHeader title="Notifications" canGoBack={false} />
@ -96,10 +101,14 @@ export const NotificationsScreen = withAuthRequired(
onScroll={onMainScroll} onScroll={onMainScroll}
scrollElRef={scrollElRef} scrollElRef={scrollElRef}
/> />
{store.me.notifications.hasNewLatest && {(isScrolledDown || hasNew) && (
!store.me.notifications.isRefreshing && ( <LoadLatestBtn
<LoadLatestBtn onPress={onPressLoadLatest} label="notifications" /> onPress={onPressLoadLatest}
)} label="Load new notifications"
showIndicator={hasNew}
minimalShellMode={true}
/>
)}
</View> </View>
) )
}), }),

View File

@ -9,7 +9,7 @@ import {CenteredView} from '../com/util/Views'
import {ScreenHider} from 'view/com/util/moderation/ScreenHider' import {ScreenHider} from 'view/com/util/moderation/ScreenHider'
import {ProfileUiModel, Sections} from 'state/models/ui/profile' import {ProfileUiModel, Sections} from 'state/models/ui/profile'
import {useStores} from 'state/index' import {useStores} from 'state/index'
import {PostsFeedSliceModel} from 'state/models/feeds/posts' import {PostsFeedSliceModel} from 'state/models/feeds/post'
import {ProfileHeader} from '../com/profile/ProfileHeader' import {ProfileHeader} from '../com/profile/ProfileHeader'
import {FeedSlice} from '../com/posts/FeedSlice' import {FeedSlice} from '../com/posts/FeedSlice'
import {ListCard} from 'view/com/lists/ListCard' import {ListCard} from 'view/com/lists/ListCard'
@ -25,6 +25,8 @@ import {FAB} from '../com/util/fab/FAB'
import {s, colors} from 'lib/styles' import {s, colors} from 'lib/styles'
import {useAnalytics} from 'lib/analytics' import {useAnalytics} from 'lib/analytics'
import {ComposeIcon2} from 'lib/icons' import {ComposeIcon2} from 'lib/icons'
import {CustomFeed} from 'view/com/feeds/CustomFeed'
import {CustomFeedModel} from 'state/models/feeds/custom-feed'
import {useSetTitle} from 'lib/hooks/useSetTitle' import {useSetTitle} from 'lib/hooks/useSetTitle'
import {combinedDisplayName} from 'lib/strings/display-names' import {combinedDisplayName} from 'lib/strings/display-names'
@ -118,6 +120,7 @@ export const ProfileScreen = withAuthRequired(
}, [uiState.showLoadingMoreFooter]) }, [uiState.showLoadingMoreFooter])
const renderItem = React.useCallback( const renderItem = React.useCallback(
(item: any) => { (item: any) => {
// if section is lists
if (uiState.selectedView === Sections.Lists) { if (uiState.selectedView === Sections.Lists) {
if (item === ProfileUiModel.LOADING_ITEM) { if (item === ProfileUiModel.LOADING_ITEM) {
return <ProfileCardFeedLoadingPlaceholder /> return <ProfileCardFeedLoadingPlaceholder />
@ -142,6 +145,32 @@ export const ProfileScreen = withAuthRequired(
} else { } else {
return <ListCard testID={`list-${item.name}`} list={item} /> return <ListCard testID={`list-${item.name}`} list={item} />
} }
// if section is custom algorithms
} else if (uiState.selectedView === Sections.CustomAlgorithms) {
if (item === ProfileUiModel.LOADING_ITEM) {
return <ProfileCardFeedLoadingPlaceholder />
} else if (item._reactKey === '__error__') {
return (
<View style={s.p5}>
<ErrorMessage
message={item.error}
onPressTryAgain={onPressTryAgain}
/>
</View>
)
} else if (item === ProfileUiModel.EMPTY_ITEM) {
return (
<EmptyState
testID="customAlgorithmsEmpty"
icon="list-ul"
message="No custom algorithms yet!"
style={styles.emptyState}
/>
)
} else if (item instanceof CustomFeedModel) {
return <CustomFeed item={item} showSaveBtn showLikes />
}
// if section is posts or posts & replies
} else { } else {
if (item === ProfileUiModel.END_ITEM) { if (item === ProfileUiModel.END_ITEM) {
return <Text style={styles.endItem}>- end of feed -</Text> return <Text style={styles.endItem}>- end of feed -</Text>

View File

@ -87,7 +87,7 @@ export const ProfileListScreen = withAuthRequired(
return <EmptyState icon="users-slash" message="This list is empty!" /> return <EmptyState icon="users-slash" message="This list is empty!" />
}, []) }, [])
const renderHeaderBtn = React.useCallback(() => { const renderHeaderBtns = React.useCallback(() => {
return ( return (
<View style={styles.headerBtns}> <View style={styles.headerBtns}>
{list?.isOwner && ( {list?.isOwner && (
@ -148,7 +148,7 @@ export const ProfileListScreen = withAuthRequired(
pal.border, pal.border,
]} ]}
testID="moderationMutelistsScreen"> testID="moderationMutelistsScreen">
<ViewHeader title="" renderButton={renderHeaderBtn} /> <ViewHeader title="" renderButton={renderHeaderBtns} />
<ListItems <ListItems
list={list} list={list}
renderEmptyState={renderEmptyState} renderEmptyState={renderEmptyState}

View File

@ -0,0 +1,293 @@
import React, {useCallback, useMemo} from 'react'
import {
RefreshControl,
StyleSheet,
View,
ActivityIndicator,
Pressable,
TouchableOpacity,
} from 'react-native'
import {useFocusEffect} from '@react-navigation/native'
import {NativeStackScreenProps} from '@react-navigation/native-stack'
import {useAnalytics} from 'lib/analytics'
import {usePalette} from 'lib/hooks/usePalette'
import {CommonNavigatorParams} from 'lib/routes/types'
import {observer} from 'mobx-react-lite'
import {useStores} from 'state/index'
import {withAuthRequired} from 'view/com/auth/withAuthRequired'
import {ViewHeader} from 'view/com/util/ViewHeader'
import {CenteredView} from 'view/com/util/Views'
import {Text} from 'view/com/util/text/Text'
import {isDesktopWeb, isWeb} from 'platform/detection'
import {s, colors} from 'lib/styles'
import DraggableFlatList, {
ShadowDecorator,
ScaleDecorator,
} from 'react-native-draggable-flatlist'
import {CustomFeed} from 'view/com/feeds/CustomFeed'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {CustomFeedModel} from 'state/models/feeds/custom-feed'
import * as Toast from 'view/com/util/Toast'
import {Haptics} from 'lib/haptics'
import {Link, TextLink} from 'view/com/util/Link'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'SavedFeeds'>
export const SavedFeeds = withAuthRequired(
observer(({}: Props) => {
const pal = usePalette('default')
const store = useStores()
const {screen} = useAnalytics()
const savedFeeds = useMemo(() => store.me.savedFeeds, [store])
useFocusEffect(
useCallback(() => {
screen('SavedFeeds')
store.shell.setMinimalShellMode(false)
savedFeeds.refresh()
}, [screen, store, savedFeeds]),
)
const renderListEmptyComponent = useCallback(() => {
return (
<View
style={[
pal.border,
!isDesktopWeb && s.flex1,
pal.viewLight,
styles.empty,
]}>
<Text type="lg" style={[pal.text]}>
You don't have any saved feeds.
</Text>
</View>
)
}, [pal])
const renderListFooterComponent = useCallback(() => {
return (
<>
<View style={[styles.footerLinks, pal.border]}>
<Link style={styles.footerLink} href="/search/feeds">
<FontAwesomeIcon
icon="search"
size={18}
color={pal.colors.icon}
/>
<Text type="lg-medium" style={pal.textLight}>
Discover new feeds
</Text>
</Link>
</View>
<View style={styles.footerText}>
<Text type="sm" style={pal.textLight}>
Feeds are custom algorithms that users build with a little coding
expertise.{' '}
<TextLink
type="sm"
style={pal.link}
href="https://github.com/bluesky-social/feed-generator"
text="See this guide"
/>{' '}
for more information.
</Text>
</View>
{savedFeeds.isLoading && <ActivityIndicator />}
</>
)
}, [pal, savedFeeds.isLoading])
const onRefresh = useCallback(() => savedFeeds.refresh(), [savedFeeds])
const onDragEnd = useCallback(
async ({data}) => {
try {
await savedFeeds.reorderPinnedFeeds(data)
} catch (e) {
Toast.show('There was an issue contacting the server')
store.log.error('Failed to save pinned feed order', {e})
}
},
[savedFeeds, store],
)
return (
<CenteredView
style={[
s.hContentRegion,
pal.border,
isDesktopWeb && styles.desktopContainer,
]}>
<ViewHeader
title="Edit My Feeds"
showOnDesktop
showBorder={!isDesktopWeb}
/>
<DraggableFlatList
containerStyle={[!isDesktopWeb && s.flex1]}
data={savedFeeds.all}
keyExtractor={item => item.data.uri}
refreshing={savedFeeds.isRefreshing}
refreshControl={
<RefreshControl
refreshing={savedFeeds.isRefreshing}
onRefresh={onRefresh}
tintColor={pal.colors.text}
titleColor={pal.colors.text}
/>
}
renderItem={({item, drag}) => <ListItem item={item} drag={drag} />}
getItemLayout={(data, index) => ({
length: 77,
offset: 77 * index,
index,
})}
initialNumToRender={10}
ListFooterComponent={renderListFooterComponent}
ListEmptyComponent={renderListEmptyComponent}
extraData={savedFeeds.isLoading}
onDragEnd={onDragEnd}
/>
</CenteredView>
)
}),
)
const ListItem = observer(
({item, drag}: {item: CustomFeedModel; drag: () => void}) => {
const pal = usePalette('default')
const store = useStores()
const savedFeeds = useMemo(() => store.me.savedFeeds, [store])
const isPinned = savedFeeds.isPinned(item)
const onTogglePinned = useCallback(() => {
Haptics.default()
savedFeeds.togglePinnedFeed(item).catch(e => {
Toast.show('There was an issue contacting the server')
store.log.error('Failed to toggle pinned feed', {e})
})
}, [savedFeeds, item, store])
const onPressUp = useCallback(
() =>
savedFeeds.movePinnedFeed(item, 'up').catch(e => {
Toast.show('There was an issue contacting the server')
store.log.error('Failed to set pinned feed order', {e})
}),
[store, savedFeeds, item],
)
const onPressDown = useCallback(
() =>
savedFeeds.movePinnedFeed(item, 'down').catch(e => {
Toast.show('There was an issue contacting the server')
store.log.error('Failed to set pinned feed order', {e})
}),
[store, savedFeeds, item],
)
return (
<ScaleDecorator>
<ShadowDecorator>
<Pressable
accessibilityRole="button"
onLongPress={isPinned ? drag : undefined}
delayLongPress={200}
style={[styles.itemContainer, pal.border]}>
{isPinned && isWeb ? (
<View style={styles.webArrowButtonsContainer}>
<TouchableOpacity
accessibilityRole="button"
onPress={onPressUp}>
<FontAwesomeIcon
icon="arrow-up"
size={12}
style={[pal.text, styles.webArrowUpButton]}
/>
</TouchableOpacity>
<TouchableOpacity
accessibilityRole="button"
onPress={onPressDown}>
<FontAwesomeIcon
icon="arrow-down"
size={12}
style={[pal.text]}
/>
</TouchableOpacity>
</View>
) : isPinned ? (
<FontAwesomeIcon
icon="bars"
size={20}
color={pal.colors.text}
style={s.ml20}
/>
) : null}
<CustomFeed
key={item.data.uri}
item={item}
showSaveBtn
style={styles.noBorder}
/>
<TouchableOpacity
accessibilityRole="button"
hitSlop={10}
onPress={onTogglePinned}>
<FontAwesomeIcon
icon="thumb-tack"
size={20}
color={isPinned ? colors.blue3 : pal.colors.icon}
/>
</TouchableOpacity>
</Pressable>
</ShadowDecorator>
</ScaleDecorator>
)
},
)
const styles = StyleSheet.create({
desktopContainer: {
borderLeftWidth: 1,
borderRightWidth: 1,
minHeight: '100vh',
},
empty: {
paddingHorizontal: 20,
paddingVertical: 20,
borderRadius: 16,
marginHorizontal: 24,
marginTop: 10,
},
itemContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
borderBottomWidth: 1,
paddingRight: 16,
},
webArrowButtonsContainer: {
paddingLeft: 16,
flexDirection: 'column',
justifyContent: 'space-around',
},
webArrowUpButton: {
marginBottom: 10,
},
noBorder: {
borderTopWidth: 0,
},
footerText: {
paddingHorizontal: 26,
paddingTop: 22,
paddingBottom: 100,
},
footerLinks: {
borderBottomWidth: 1,
borderTopWidth: 0,
},
footerLink: {
flexDirection: 'row',
paddingHorizontal: 26,
paddingVertical: 18,
gap: 18,
},
})

View File

@ -35,7 +35,7 @@ export const SearchScreen = withAuthRequired(
const store = useStores() const store = useStores()
const scrollViewRef = React.useRef<ScrollView>(null) const scrollViewRef = React.useRef<ScrollView>(null)
const flatListRef = React.useRef<FlatList>(null) const flatListRef = React.useRef<FlatList>(null)
const onMainScroll = useOnMainScroll(store) const [onMainScroll] = useOnMainScroll(store)
const [isInputFocused, setIsInputFocused] = React.useState<boolean>(false) const [isInputFocused, setIsInputFocused] = React.useState<boolean>(false)
const [query, setQuery] = React.useState<string>('') const [query, setQuery] = React.useState<string>('')
const autocompleteView = React.useMemo<UserAutocompleteModel>( const autocompleteView = React.useMemo<UserAutocompleteModel>(

View File

@ -141,6 +141,11 @@ export const SettingsScreen = withAuthRequired(
store.shell.openModal({name: 'delete-account'}) store.shell.openModal({name: 'delete-account'})
}, [store]) }, [store])
const onPressResetPreferences = React.useCallback(async () => {
await store.preferences.reset()
Toast.show('Preferences reset')
}, [store])
return ( return (
<View style={[s.hContentRegion]} testID="settingsScreen"> <View style={[s.hContentRegion]} testID="settingsScreen">
<ViewHeader title="Settings" /> <ViewHeader title="Settings" />
@ -301,6 +306,22 @@ export const SettingsScreen = withAuthRequired(
App passwords App passwords
</Text> </Text>
</Link> </Link>
<Link
testID="savedFeedsBtn"
style={[styles.linkCard, pal.view, isSwitching && styles.dimmed]}
accessibilityHint="Saved Feeds"
accessibilityLabel="Opens screen with all saved feeds"
href="/settings/saved-feeds">
<View style={[styles.iconContainer, pal.btn]}>
<FontAwesomeIcon
icon="satellite-dish"
style={pal.text as FontAwesomeIconStyle}
/>
</View>
<Text type="lg" style={pal.text}>
Saved Feeds
</Text>
</Link>
<TouchableOpacity <TouchableOpacity
testID="contentLanguagesBtn" testID="contentLanguagesBtn"
style={[styles.linkCard, pal.view, isSwitching && styles.dimmed]} style={[styles.linkCard, pal.view, isSwitching && styles.dimmed]}
@ -377,6 +398,16 @@ export const SettingsScreen = withAuthRequired(
Storybook Storybook
</Text> </Text>
</Link> </Link>
{__DEV__ ? (
<Link
style={[pal.view, styles.linkCardNoIcon]}
onPress={onPressResetPreferences}
title="Debug tools">
<Text type="lg" style={pal.text}>
Reset preferences state
</Text>
</Link>
) : null}
<Text type="sm" style={[styles.buildInfo, pal.textLight]}> <Text type="sm" style={[styles.buildInfo, pal.textLight]}>
Build version {AppInfo.appVersion} ({AppInfo.buildVersion}) Build version {AppInfo.appVersion} ({AppInfo.buildVersion})
</Text> </Text>

View File

@ -2,6 +2,7 @@ import React, {ComponentProps} from 'react'
import { import {
Linking, Linking,
SafeAreaView, SafeAreaView,
ScrollView,
StyleProp, StyleProp,
StyleSheet, StyleSheet,
TouchableOpacity, TouchableOpacity,
@ -28,6 +29,8 @@ import {
MagnifyingGlassIcon2Solid, MagnifyingGlassIcon2Solid,
MoonIcon, MoonIcon,
UserIconSolid, UserIconSolid,
SatelliteDishIcon,
SatelliteDishIconSolid,
HandIcon, HandIcon,
} from 'lib/icons' } from 'lib/icons'
import {UserAvatar} from 'view/com/util/UserAvatar' import {UserAvatar} from 'view/com/util/UserAvatar'
@ -40,7 +43,7 @@ import {getTabState, TabState} from 'lib/routes/helpers'
import {NavigationProp} from 'lib/routes/types' import {NavigationProp} from 'lib/routes/types'
import {useNavigationTabState} from 'lib/hooks/useNavigationTabState' import {useNavigationTabState} from 'lib/hooks/useNavigationTabState'
import {isWeb} from 'platform/detection' import {isWeb} from 'platform/detection'
import {formatCount} from 'view/com/util/numeric/format' import {formatCount, formatCountShortOnly} from 'view/com/util/numeric/format'
export const DrawerContent = observer(() => { export const DrawerContent = observer(() => {
const theme = useTheme() const theme = useTheme()
@ -48,7 +51,7 @@ export const DrawerContent = observer(() => {
const store = useStores() const store = useStores()
const navigation = useNavigation<NavigationProp>() const navigation = useNavigation<NavigationProp>()
const {track} = useAnalytics() const {track} = useAnalytics()
const {isAtHome, isAtSearch, isAtNotifications, isAtMyProfile} = const {isAtHome, isAtSearch, isAtFeeds, isAtNotifications, isAtMyProfile} =
useNavigationTabState() useNavigationTabState()
const {notifications} = store.me const {notifications} = store.me
@ -95,6 +98,11 @@ export const DrawerContent = observer(() => {
onPressTab('MyProfile') onPressTab('MyProfile')
}, [onPressTab]) }, [onPressTab])
const onPressMyFeeds = React.useCallback(
() => onPressTab('Feeds'),
[onPressTab],
)
const onPressModeration = React.useCallback(() => { const onPressModeration = React.useCallback(() => {
track('Menu:ItemClicked', {url: 'Moderation'}) track('Menu:ItemClicked', {url: 'Moderation'})
navigation.navigate('Moderation') navigation.navigate('Moderation')
@ -147,19 +155,18 @@ export const DrawerContent = observer(() => {
type="xl" type="xl"
style={[pal.textLight, styles.profileCardFollowers]}> style={[pal.textLight, styles.profileCardFollowers]}>
<Text type="xl-medium" style={pal.text}> <Text type="xl-medium" style={pal.text}>
{formatCount(store.me.followersCount ?? 0)} {formatCountShortOnly(store.me.followersCount ?? 0)}
</Text>{' '} </Text>{' '}
{pluralize(store.me.followersCount || 0, 'follower')} &middot;{' '} {pluralize(store.me.followersCount || 0, 'follower')} &middot;{' '}
<Text type="xl-medium" style={pal.text}> <Text type="xl-medium" style={pal.text}>
{formatCount(store.me.followsCount ?? 0)} {formatCountShortOnly(store.me.followsCount ?? 0)}
</Text>{' '} </Text>{' '}
following following
</Text> </Text>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
<InviteCodes /> <InviteCodes />
<View style={s.flex1} /> <ScrollView style={styles.main}>
<View style={styles.main}>
<MenuItem <MenuItem
icon={ icon={
isAtSearch ? ( isAtSearch ? (
@ -233,12 +240,27 @@ export const DrawerContent = observer(() => {
/> />
<MenuItem <MenuItem
icon={ icon={
<HandIcon isAtFeeds ? (
strokeWidth={5} <SatelliteDishIconSolid
style={pal.text as FontAwesomeIconStyle} strokeWidth={1.5}
size={24} style={pal.text as FontAwesomeIconStyle}
/> size={24}
/>
) : (
<SatelliteDishIcon
strokeWidth={1.5}
style={pal.text as FontAwesomeIconStyle}
size={24}
/>
)
} }
label="My Feeds"
accessibilityLabel="My Feeds"
accessibilityHint=""
onPress={onPressMyFeeds}
/>
<MenuItem
icon={<HandIcon strokeWidth={5} style={pal.text} size={24} />}
label="Moderation" label="Moderation"
accessibilityLabel="Moderation" accessibilityLabel="Moderation"
accessibilityHint="" accessibilityHint=""
@ -278,8 +300,8 @@ export const DrawerContent = observer(() => {
accessibilityHint="" accessibilityHint=""
onPress={onPressSettings} onPress={onPressSettings}
/> />
</View> <View style={styles.smallSpacer} />
<View style={s.flex1} /> </ScrollView>
<View style={styles.footer}> <View style={styles.footer}>
{!isWeb && ( {!isWeb && (
<TouchableOpacity <TouchableOpacity
@ -435,6 +457,10 @@ const styles = StyleSheet.create({
}, },
main: { main: {
paddingLeft: 20, paddingLeft: 20,
paddingTop: 20,
},
smallSpacer: {
height: 20,
}, },
profileCardDisplayName: { profileCardDisplayName: {

View File

@ -18,23 +18,24 @@ import {
HomeIconSolid, HomeIconSolid,
MagnifyingGlassIcon2, MagnifyingGlassIcon2,
MagnifyingGlassIcon2Solid, MagnifyingGlassIcon2Solid,
SatelliteDishIcon,
SatelliteDishIconSolid,
BellIcon, BellIcon,
BellIconSolid, BellIconSolid,
UserIcon,
UserIconSolid,
} from 'lib/icons' } from 'lib/icons'
import {usePalette} from 'lib/hooks/usePalette' import {usePalette} from 'lib/hooks/usePalette'
import {getTabState, TabState} from 'lib/routes/helpers' import {getTabState, TabState} from 'lib/routes/helpers'
import {styles} from './BottomBarStyles' import {styles} from './BottomBarStyles'
import {useMinimalShellMode} from 'lib/hooks/useMinimalShellMode' import {useMinimalShellMode} from 'lib/hooks/useMinimalShellMode'
import {useNavigationTabState} from 'lib/hooks/useNavigationTabState' import {useNavigationTabState} from 'lib/hooks/useNavigationTabState'
import {UserAvatar} from 'view/com/util/UserAvatar'
export const BottomBar = observer(({navigation}: BottomTabBarProps) => { export const BottomBar = observer(({navigation}: BottomTabBarProps) => {
const store = useStores() const store = useStores()
const pal = usePalette('default') const pal = usePalette('default')
const safeAreaInsets = useSafeAreaInsets() const safeAreaInsets = useSafeAreaInsets()
const {track} = useAnalytics() const {track} = useAnalytics()
const {isAtHome, isAtSearch, isAtNotifications, isAtMyProfile} = const {isAtHome, isAtSearch, isAtFeeds, isAtNotifications, isAtMyProfile} =
useNavigationTabState() useNavigationTabState()
const {footerMinimalShellTransform} = useMinimalShellMode() const {footerMinimalShellTransform} = useMinimalShellMode()
@ -60,6 +61,10 @@ export const BottomBar = observer(({navigation}: BottomTabBarProps) => {
() => onPressTab('Search'), () => onPressTab('Search'),
[onPressTab], [onPressTab],
) )
const onPressFeeds = React.useCallback(
() => onPressTab('Feeds'),
[onPressTab],
)
const onPressNotifications = React.useCallback( const onPressNotifications = React.useCallback(
() => onPressTab('Notifications'), () => onPressTab('Notifications'),
[onPressTab], [onPressTab],
@ -121,6 +126,28 @@ export const BottomBar = observer(({navigation}: BottomTabBarProps) => {
accessibilityLabel="Search" accessibilityLabel="Search"
accessibilityHint="" accessibilityHint=""
/> />
<Btn
testID="bottomBarFeedsBtn"
icon={
isAtFeeds ? (
<SatelliteDishIconSolid
size={25}
style={[styles.ctrlIcon, pal.text, styles.searchIcon]}
strokeWidth={1.8}
/>
) : (
<SatelliteDishIcon
size={25}
style={[styles.ctrlIcon, pal.text, styles.searchIcon]}
strokeWidth={1.8}
/>
)
}
onPress={onPressFeeds}
accessibilityRole="tab"
accessibilityLabel="Feeds"
accessibilityHint=""
/>
<Btn <Btn
testID="bottomBarNotificationsBtn" testID="bottomBarNotificationsBtn"
icon={ icon={
@ -154,17 +181,19 @@ export const BottomBar = observer(({navigation}: BottomTabBarProps) => {
icon={ icon={
<View style={styles.ctrlIconSizingWrapper}> <View style={styles.ctrlIconSizingWrapper}>
{isAtMyProfile ? ( {isAtMyProfile ? (
<UserIconSolid <View
size={28} style={[
strokeWidth={1.5} styles.ctrlIcon,
style={[styles.ctrlIcon, pal.text, styles.profileIcon]} pal.text,
/> styles.profileIcon,
styles.onProfile,
]}>
<UserAvatar avatar={store.me.avatar} size={27} />
</View>
) : ( ) : (
<UserIcon <View style={[styles.ctrlIcon, pal.text, styles.profileIcon]}>
size={28} <UserAvatar avatar={store.me.avatar} size={28} />
strokeWidth={1.5} </View>
style={[styles.ctrlIcon, pal.text, styles.profileIcon]}
/>
)} )}
</View> </View>
} }

View File

@ -58,4 +58,9 @@ export const styles = StyleSheet.create({
profileIcon: { profileIcon: {
top: -4, top: -4,
}, },
onProfile: {
borderColor: colors.black,
borderWidth: 1,
borderRadius: 100,
},
}) })

View File

@ -15,6 +15,8 @@ import {
HomeIconSolid, HomeIconSolid,
MagnifyingGlassIcon2, MagnifyingGlassIcon2,
MagnifyingGlassIcon2Solid, MagnifyingGlassIcon2Solid,
SatelliteDishIcon,
SatelliteDishIconSolid,
UserIcon, UserIcon,
} from 'lib/icons' } from 'lib/icons'
import {Link} from 'view/com/util/Link' import {Link} from 'view/com/util/Link'
@ -61,6 +63,18 @@ export const BottomBarWeb = observer(() => {
) )
}} }}
</NavItem> </NavItem>
<NavItem routeName="Feeds" href="/feeds">
{({isActive}) => {
const Icon = isActive ? SatelliteDishIconSolid : SatelliteDishIcon
return (
<Icon
size={25}
style={[styles.ctrlIcon, pal.text, styles.searchIcon]}
strokeWidth={1.8}
/>
)
}}
</NavItem>
<NavItem routeName="Notifications" href="/notifications"> <NavItem routeName="Notifications" href="/notifications">
{({isActive}) => { {({isActive}) => {
const Icon = isActive ? BellIconSolid : BellIcon const Icon = isActive ? BellIconSolid : BellIcon

View File

@ -30,6 +30,8 @@ import {
CogIconSolid, CogIconSolid,
ComposeIcon2, ComposeIcon2,
HandIcon, HandIcon,
SatelliteDishIcon,
SatelliteDishIconSolid,
} from 'lib/icons' } from 'lib/icons'
import {getCurrentRoute, isTab, isStateAtTabRoot} from 'lib/routes/helpers' import {getCurrentRoute, isTab, isStateAtTabRoot} from 'lib/routes/helpers'
import {NavigationProp} from 'lib/routes/types' import {NavigationProp} from 'lib/routes/types'
@ -195,6 +197,24 @@ export const DesktopLeftNav = observer(function DesktopLeftNav() {
} }
label="Search" label="Search"
/> />
<NavItem
href="/feeds"
icon={
<SatelliteDishIcon
strokeWidth={1.75}
style={pal.text as FontAwesomeIconStyle}
size={24}
/>
}
iconFilled={
<SatelliteDishIconSolid
strokeWidth={1.75}
style={pal.text as FontAwesomeIconStyle}
size={24}
/>
}
label="My Feeds"
/>
<NavItem <NavItem
href="/notifications" href="/notifications"
count={store.me.notifications.unreadCountLabel} count={store.me.notifications.unreadCountLabel}

1017
yarn.lock

File diff suppressed because it is too large Load Diff