Merge remote-tracking branch 'upstream/main' into Improve-notification-localization

This commit is contained in:
Minseo Lee
2024-07-08 11:33:53 +09:00
199 changed files with 33068 additions and 14477 deletions
+11 -4
View File
@@ -45,6 +45,7 @@ import {
import {readLastActiveAccount} from '#/state/session/util'
import {Provider as ShellStateProvider} from '#/state/shell'
import {Provider as LoggedOutViewProvider} from '#/state/shell/logged-out'
import {Provider as ProgressGuideProvider} from '#/state/shell/progress-guide'
import {Provider as SelectedFeedProvider} from '#/state/shell/selected-feed'
import {Provider as StarterPackProvider} from '#/state/shell/starter-pack'
import {TestCtrls} from '#/view/com/testing/TestCtrls'
@@ -55,6 +56,7 @@ import {useColorModeTheme} from '#/alf/util/useColorModeTheme'
import {useStarterPackEntry} from '#/components/hooks/useStarterPackEntry'
import {Provider as PortalProvider} from '#/components/Portal'
import {Splash} from '#/Splash'
import {Provider as TourProvider} from '#/tours'
import {BackgroundNotificationPreferencesProvider} from '../modules/expo-background-notification-handler/src/BackgroundNotificationHandlerProvider'
import I18nProvider from './locale/i18nProvider'
import {listenSessionDropped} from './state/events'
@@ -117,10 +119,15 @@ function InnerApp() {
<UnreadNotifsProvider>
<BackgroundNotificationPreferencesProvider>
<MutedThreadsProvider>
<GestureHandlerRootView style={s.h100pct}>
<TestCtrls />
<Shell />
</GestureHandlerRootView>
<TourProvider>
<ProgressGuideProvider>
<GestureHandlerRootView
style={s.h100pct}>
<TestCtrls />
<Shell />
</GestureHandlerRootView>
</ProgressGuideProvider>
</TourProvider>
</MutedThreadsProvider>
</BackgroundNotificationPreferencesProvider>
</UnreadNotifsProvider>
+7 -1
View File
@@ -34,6 +34,7 @@ import {
import {readLastActiveAccount} from '#/state/session/util'
import {Provider as ShellStateProvider} from '#/state/shell'
import {Provider as LoggedOutViewProvider} from '#/state/shell/logged-out'
import {Provider as ProgressGuideProvider} from '#/state/shell/progress-guide'
import {Provider as SelectedFeedProvider} from '#/state/shell/selected-feed'
import {Provider as StarterPackProvider} from '#/state/shell/starter-pack'
import * as Toast from '#/view/com/util/Toast'
@@ -43,6 +44,7 @@ import {ThemeProvider as Alf} from '#/alf'
import {useColorModeTheme} from '#/alf/util/useColorModeTheme'
import {useStarterPackEntry} from '#/components/hooks/useStarterPackEntry'
import {Provider as PortalProvider} from '#/components/Portal'
import {Provider as TourProvider} from '#/tours'
import {BackgroundNotificationPreferencesProvider} from '../modules/expo-background-notification-handler/src/BackgroundNotificationHandlerProvider'
import I18nProvider from './locale/i18nProvider'
import {listenSessionDropped} from './state/events'
@@ -102,7 +104,11 @@ function InnerApp() {
<BackgroundNotificationPreferencesProvider>
<MutedThreadsProvider>
<SafeAreaProvider>
<Shell />
<TourProvider>
<ProgressGuideProvider>
<Shell />
</ProgressGuideProvider>
</TourProvider>
</SafeAreaProvider>
</MutedThreadsProvider>
</BackgroundNotificationPreferencesProvider>
+10 -2
View File
@@ -43,7 +43,10 @@ import HashtagScreen from '#/screens/Hashtag'
import {ModerationScreen} from '#/screens/Moderation'
import {ProfileKnownFollowersScreen} from '#/screens/Profile/KnownFollowers'
import {ProfileLabelerLikedByScreen} from '#/screens/Profile/ProfileLabelerLikedBy'
import {StarterPackScreen} from '#/screens/StarterPack/StarterPackScreen'
import {
StarterPackScreen,
StarterPackScreenShort,
} from '#/screens/StarterPack/StarterPackScreen'
import {Wizard} from '#/screens/StarterPack/Wizard'
import {init as initAnalytics} from './lib/analytics/analytics'
import {useWebScrollRestoration} from './lib/hooks/useWebScrollRestoration'
@@ -322,7 +325,12 @@ function commonScreens(Stack: typeof HomeTab, unreadCountLabel?: string) {
<Stack.Screen
name="StarterPack"
getComponent={() => StarterPackScreen}
options={{title: title(msg`Starter Pack`), requireAuth: true}}
options={{title: title(msg`Starter Pack`)}}
/>
<Stack.Screen
name="StarterPackShort"
getComponent={() => StarterPackScreenShort}
options={{title: title(msg`Starter Pack`)}}
/>
<Stack.Screen
name="StarterPackWizard"
+71
View File
@@ -21,6 +21,7 @@ export type ButtonVariant = 'solid' | 'outline' | 'ghost' | 'gradient'
export type ButtonColor =
| 'primary'
| 'secondary'
| 'secondary_inverted'
| 'negative'
| 'gradient_sky'
| 'gradient_midnight'
@@ -217,6 +218,43 @@ export const Button = React.forwardRef<View, ButtonProps>(
borderWidth: 1,
})
if (!disabled) {
baseStyles.push(a.border, {
borderColor: t.palette.contrast_300,
})
hoverStyles.push(t.atoms.bg_contrast_50)
} else {
baseStyles.push(a.border, {
borderColor: t.palette.contrast_200,
})
}
} else if (variant === 'ghost') {
if (!disabled) {
baseStyles.push(t.atoms.bg)
hoverStyles.push({
backgroundColor: t.palette.contrast_25,
})
}
}
} else if (color === 'secondary_inverted') {
if (variant === 'solid') {
if (!disabled) {
baseStyles.push({
backgroundColor: t.palette.contrast_900,
})
hoverStyles.push({
backgroundColor: t.palette.contrast_950,
})
} else {
baseStyles.push({
backgroundColor: t.palette.contrast_700,
})
}
} else if (variant === 'outline') {
baseStyles.push(a.border, t.atoms.bg, {
borderWidth: 1,
})
if (!disabled) {
baseStyles.push(a.border, {
borderColor: t.palette.contrast_300,
@@ -344,6 +382,7 @@ export const Button = React.forwardRef<View, ButtonProps>(
const gradient = {
primary: tokens.gradients.sky,
secondary: tokens.gradients.sky,
secondary_inverted: tokens.gradients.sky,
negative: tokens.gradients.sky,
gradient_sky: tokens.gradients.sky,
gradient_midnight: tokens.gradients.midnight,
@@ -499,6 +538,38 @@ export function useSharedButtonTextStyles() {
})
}
}
} else if (color === 'secondary_inverted') {
if (variant === 'solid' || variant === 'gradient') {
if (!disabled) {
baseStyles.push({
color: t.palette.contrast_100,
})
} else {
baseStyles.push({
color: t.palette.contrast_400,
})
}
} else if (variant === 'outline') {
if (!disabled) {
baseStyles.push({
color: t.palette.contrast_600,
})
} else {
baseStyles.push({
color: t.palette.contrast_300,
})
}
} else if (variant === 'ghost') {
if (!disabled) {
baseStyles.push({
color: t.palette.contrast_600,
})
} else {
baseStyles.push({
color: t.palette.contrast_300,
})
}
}
} else if (color === 'negative') {
if (variant === 'solid' || variant === 'gradient') {
if (!disabled) {
+4 -1
View File
@@ -88,7 +88,10 @@ export function Outer({
if (!isOpen) return
function handler(e: KeyboardEvent) {
if (e.key === 'Escape') close()
if (e.key === 'Escape') {
e.stopPropagation()
close()
}
}
document.addEventListener('keydown', handler)
+67 -81
View File
@@ -5,6 +5,7 @@ import {
AppBskyFeedDefs,
AppBskyGraphDefs,
AtUri,
RichText as RichTextApi,
} from '@atproto/api'
import {msg, plural, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
@@ -17,61 +18,46 @@ import {
useRemoveFeedMutation,
} from '#/state/queries/preferences'
import {sanitizeHandle} from 'lib/strings/handles'
import {precacheFeedFromGeneratorView, precacheList} from 'state/queries/feed'
import {precacheFeedFromGeneratorView} from 'state/queries/feed'
import {useSession} from 'state/session'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import * as Toast from 'view/com/util/Toast'
import {useTheme} from '#/alf'
import {atoms as a} from '#/alf'
import {Button, ButtonIcon} from '#/components/Button'
import {useRichText} from '#/components/hooks/useRichText'
import {PlusLarge_Stroke2_Corner0_Rounded as Plus} from '#/components/icons/Plus'
import {Trash_Stroke2_Corner0_Rounded as Trash} from '#/components/icons/Trash'
import {Link as InternalLink, LinkProps} from '#/components/Link'
import {Loader} from '#/components/Loader'
import * as Prompt from '#/components/Prompt'
import {RichText} from '#/components/RichText'
import {RichText, RichTextProps} from '#/components/RichText'
import {Text} from '#/components/Typography'
type Props =
| {
type: 'feed'
view: AppBskyFeedDefs.GeneratorView
}
| {
type: 'list'
view: AppBskyGraphDefs.ListView
}
type Props = {
view: AppBskyFeedDefs.GeneratorView
}
export function Default(props: Props) {
const {type, view} = props
const displayName = type === 'feed' ? view.displayName : view.name
const purpose = type === 'list' ? view.purpose : undefined
const {view} = props
return (
<Link label={displayName} {...props}>
<Link label={view.displayName} {...props}>
<Outer>
<Header>
<Avatar src={view.avatar} />
<TitleAndByline
title={displayName}
creator={view.creator}
type={type}
purpose={purpose}
/>
<Action uri={view.uri} pin type={type} purpose={purpose} />
<TitleAndByline title={view.displayName} creator={view.creator} />
<SaveButton view={view} pin />
</Header>
<Description description={view.description} />
{type === 'feed' && <Likes count={view.likeCount || 0} />}
<Likes count={view.likeCount || 0} />
</Outer>
</Link>
)
}
export function Link({
type,
view,
label,
children,
...props
}: Props & Omit<LinkProps, 'to'>) {
const queryClient = useQueryClient()
@@ -79,32 +65,23 @@ export function Link({
return createProfileFeedHref({feed: view})
}, [view])
React.useEffect(() => {
precacheFeedFromGeneratorView(queryClient, view)
}, [view, queryClient])
return (
<InternalLink
to={href}
label={label}
onPress={() => {
if (type === 'feed') {
precacheFeedFromGeneratorView(queryClient, view)
} else {
precacheList(queryClient, view)
}
}}>
<InternalLink to={href} style={[a.flex_col]} {...props}>
{children}
</InternalLink>
)
}
export function Outer({children}: {children: React.ReactNode}) {
return <View style={[a.flex_1, a.gap_md]}>{children}</View>
return <View style={[a.w_full, a.gap_md]}>{children}</View>
}
export function Header({children}: {children: React.ReactNode}) {
return (
<View style={[a.flex_1, a.flex_row, a.align_center, a.gap_md]}>
{children}
</View>
)
return <View style={[a.flex_row, a.align_center, a.gap_md]}>{children}</View>
}
export type AvatarProps = {src: string | undefined; size?: number}
@@ -132,13 +109,9 @@ export function AvatarPlaceholder({size = 40}: Omit<AvatarProps, 'src'>) {
export function TitleAndByline({
title,
creator,
type,
purpose,
}: {
title: string
creator?: AppBskyActorDefs.ProfileViewBasic
type: 'feed' | 'list'
purpose?: AppBskyGraphDefs.ListView['purpose']
}) {
const t = useTheme()
@@ -151,15 +124,7 @@ export function TitleAndByline({
<Text
style={[a.leading_snug, t.atoms.text_contrast_medium]}
numberOfLines={1}>
{type === 'list' && purpose === 'app.bsky.graph.defs#curatelist' ? (
<Trans>List by {sanitizeHandle(creator.handle, '@')}</Trans>
) : type === 'list' && purpose === 'app.bsky.graph.defs#modlist' ? (
<Trans>
Moderation list by {sanitizeHandle(creator.handle, '@')}
</Trans>
) : (
<Trans>Feed by {sanitizeHandle(creator.handle, '@')}</Trans>
)}
<Trans>Feed by {sanitizeHandle(creator.handle, '@')}</Trans>
</Text>
)}
</View>
@@ -198,13 +163,39 @@ export function TitleAndBylinePlaceholder({creator}: {creator?: boolean}) {
)
}
export function Description({description}: {description?: string}) {
const [rt, isResolving] = useRichText(description || '')
if (!description) return null
return isResolving ? (
<RichText value={description} style={[a.leading_snug]} />
) : (
<RichText value={rt} style={[a.leading_snug]} />
export function Description({
description,
...rest
}: {description?: string} & Partial<RichTextProps>) {
const rt = React.useMemo(() => {
if (!description) return
const rt = new RichTextApi({text: description || ''})
rt.detectFacetsWithoutResolution()
return rt
}, [description])
if (!rt) return null
return <RichText value={rt} style={[a.leading_snug]} disableLinks {...rest} />
}
export function DescriptionPlaceholder() {
const t = useTheme()
return (
<View style={[a.gap_xs]}>
<View
style={[a.rounded_xs, a.w_full, t.atoms.bg_contrast_50, {height: 12}]}
/>
<View
style={[a.rounded_xs, a.w_full, t.atoms.bg_contrast_50, {height: 12}]}
/>
<View
style={[
a.rounded_xs,
a.w_full,
t.atoms.bg_contrast_50,
{height: 12, width: 100},
]}
/>
</View>
)
}
@@ -220,30 +211,24 @@ export function Likes({count}: {count: number}) {
)
}
export function Action({
uri,
export function SaveButton({
view,
pin,
type,
purpose,
}: {
uri: string
view: AppBskyFeedDefs.GeneratorView | AppBskyGraphDefs.ListView
pin?: boolean
type: 'feed' | 'list'
purpose?: AppBskyGraphDefs.ListView['purpose']
}) {
const {hasSession} = useSession()
if (!hasSession || purpose !== 'app.bsky.graph.defs#curatelist') return null
return <ActionInner uri={uri} pin={pin} type={type} />
if (!hasSession) return null
return <SaveButtonInner view={view} pin={pin} />
}
function ActionInner({
uri,
function SaveButtonInner({
view,
pin,
type,
}: {
uri: string
view: AppBskyFeedDefs.GeneratorView | AppBskyGraphDefs.ListView
pin?: boolean
type: 'feed' | 'list'
}) {
const {_} = useLingui()
const {data: preferences} = usePreferencesQuery()
@@ -251,6 +236,10 @@ function ActionInner({
useAddSavedFeedsMutation()
const {isPending: isRemovePending, mutateAsync: removeFeed} =
useRemoveFeedMutation()
const uri = view.uri
const type = view.uri.includes('app.bsky.feed.generator') ? 'feed' : 'list'
const savedFeedConfig = React.useMemo(() => {
return preferences?.savedFeeds?.find(feed => feed.value === uri)
}, [preferences?.savedFeeds, uri])
@@ -327,12 +316,9 @@ function ActionInner({
export function createProfileFeedHref({
feed,
}: {
feed: AppBskyFeedDefs.GeneratorView | AppBskyGraphDefs.ListView
feed: AppBskyFeedDefs.GeneratorView
}) {
const urip = new AtUri(feed.uri)
const type = urip.collection === 'app.bsky.feed.generator' ? 'feed' : 'list'
const handleOrDid = feed.creator.handle || feed.creator.did
return `/profile/${handleOrDid}/${type === 'feed' ? 'feed' : 'lists'}/${
urip.rkey
}`
return `/profile/${handleOrDid}/feed/${urip.rkey}`
}
+456
View File
@@ -0,0 +1,456 @@
import React from 'react'
import {View} from 'react-native'
import {ScrollView} from 'react-native-gesture-handler'
import {AppBskyFeedDefs, AtUri} from '@atproto/api'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useNavigation} from '@react-navigation/native'
import {useWebMediaQueries} from '#/lib/hooks/useWebMediaQueries'
import {NavigationProp} from '#/lib/routes/types'
import {logEvent} from '#/lib/statsig/statsig'
import {logger} from '#/logger'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {useGetPopularFeedsQuery} from '#/state/queries/feed'
import {useProfilesQuery} from '#/state/queries/profile'
import {useProgressGuide} from '#/state/shell/progress-guide'
import * as userActionHistory from '#/state/userActionHistory'
import {SeenPost} from '#/state/userActionHistory'
import {atoms as a, useBreakpoints, useTheme, ViewStyleProp, web} from '#/alf'
import {Button} from '#/components/Button'
import * as FeedCard from '#/components/FeedCard'
import {ArrowRight_Stroke2_Corner0_Rounded as Arrow} from '#/components/icons/Arrow'
import {Hashtag_Stroke2_Corner0_Rounded as Hashtag} from '#/components/icons/Hashtag'
import {PersonPlus_Stroke2_Corner0_Rounded as Person} from '#/components/icons/Person'
import {InlineLinkText} from '#/components/Link'
import * as ProfileCard from '#/components/ProfileCard'
import {Text} from '#/components/Typography'
import {ProgressGuideList} from './ProgressGuide/List'
const MOBILE_CARD_WIDTH = 300
function CardOuter({
children,
style,
}: {children: React.ReactNode | React.ReactNode[]} & ViewStyleProp) {
const t = useTheme()
const {gtMobile} = useBreakpoints()
return (
<View
style={[
a.w_full,
a.p_lg,
a.rounded_md,
a.border,
t.atoms.bg,
t.atoms.border_contrast_low,
!gtMobile && {
width: MOBILE_CARD_WIDTH,
},
style,
]}>
{children}
</View>
)
}
export function SuggestedFollowPlaceholder() {
const t = useTheme()
return (
<CardOuter style={[a.gap_sm, t.atoms.border_contrast_low]}>
<ProfileCard.Header>
<ProfileCard.AvatarPlaceholder />
</ProfileCard.Header>
<View style={[a.py_xs]}>
<ProfileCard.NameAndHandlePlaceholder />
</View>
<ProfileCard.DescriptionPlaceholder />
</CardOuter>
)
}
export function SuggestedFeedsCardPlaceholder() {
const t = useTheme()
return (
<CardOuter style={[a.gap_sm, t.atoms.border_contrast_low]}>
<FeedCard.Header>
<FeedCard.AvatarPlaceholder />
<FeedCard.TitleAndBylinePlaceholder creator />
</FeedCard.Header>
<FeedCard.DescriptionPlaceholder />
</CardOuter>
)
}
function getRank(seenPost: SeenPost): string {
let tier: string
if (seenPost.feedContext === 'popfriends') {
tier = 'a'
} else if (seenPost.feedContext?.startsWith('cluster')) {
tier = 'b'
} else if (seenPost.feedContext?.startsWith('ntpc')) {
tier = 'c'
} else if (seenPost.feedContext?.startsWith('t-')) {
tier = 'd'
} else if (seenPost.feedContext === 'nettop') {
tier = 'e'
} else {
tier = 'f'
}
let score = Math.round(
Math.log(
1 + seenPost.likeCount + seenPost.repostCount + seenPost.replyCount,
),
)
if (seenPost.isFollowedBy || Math.random() > 0.9) {
score *= 2
}
const rank = 100 - score
return `${tier}-${rank}`
}
function sortSeenPosts(postA: SeenPost, postB: SeenPost): 0 | 1 | -1 {
const rankA = getRank(postA)
const rankB = getRank(postB)
// Yes, we're comparing strings here.
// The "larger" string means a worse rank.
if (rankA > rankB) {
return 1
} else if (rankA < rankB) {
return -1
} else {
return 0
}
}
function useExperimentalSuggestedUsersQuery() {
const userActionSnapshot = userActionHistory.useActionHistorySnapshot()
const dids = React.useMemo(() => {
const {likes, follows, seen} = userActionSnapshot
const likeDids = likes
.map(l => new AtUri(l))
.map(uri => uri.host)
.filter(did => !follows.includes(did))
const seenDids = seen
.sort(sortSeenPosts)
.map(l => new AtUri(l.uri))
.map(uri => uri.host)
return [...new Set([...likeDids, ...seenDids])]
}, [userActionSnapshot])
const {data, isLoading, error} = useProfilesQuery({
handles: dids.slice(0, 16),
})
const profiles = data
? data.profiles.filter(profile => {
return !profile.viewer?.following
})
: []
return {
isLoading,
error,
profiles: profiles.slice(0, 6),
}
}
export function SuggestedFollows() {
const t = useTheme()
const {_} = useLingui()
const {
isLoading: isSuggestionsLoading,
profiles,
error,
} = useExperimentalSuggestedUsersQuery()
const moderationOpts = useModerationOpts()
const navigation = useNavigation<NavigationProp>()
const {gtMobile} = useBreakpoints()
const isLoading = isSuggestionsLoading || !moderationOpts
const maxLength = gtMobile ? 4 : 6
const content = isLoading ? (
Array(maxLength)
.fill(0)
.map((_, i) => (
<View
key={i}
style={[gtMobile && web([a.flex_0, {width: 'calc(50% - 6px)'}])]}>
<SuggestedFollowPlaceholder />
</View>
))
) : error || !profiles.length ? null : (
<>
{profiles.slice(0, maxLength).map(profile => (
<ProfileCard.Link
key={profile.did}
did={profile.handle}
onPress={() => {
logEvent('feed:interstitial:profileCard:press', {})
}}
style={[
a.flex_1,
gtMobile && web([a.flex_0, {width: 'calc(50% - 6px)'}]),
]}>
{({hovered, pressed}) => (
<CardOuter
style={[
a.flex_1,
(hovered || pressed) && t.atoms.border_contrast_high,
]}>
<ProfileCard.Outer>
<ProfileCard.Header>
<ProfileCard.Avatar
profile={profile}
moderationOpts={moderationOpts}
/>
<ProfileCard.NameAndHandle
profile={profile}
moderationOpts={moderationOpts}
/>
<ProfileCard.FollowButton
profile={profile}
moderationOpts={moderationOpts}
logContext="FeedInterstitial"
color="secondary_inverted"
shape="round"
/>
</ProfileCard.Header>
<ProfileCard.Description profile={profile} />
</ProfileCard.Outer>
</CardOuter>
)}
</ProfileCard.Link>
))}
</>
)
if (error || (!isLoading && profiles.length < 4)) {
logger.debug(`Not enough profiles to show suggested follows`)
return null
}
return (
<View
style={[a.border_t, t.atoms.border_contrast_low, t.atoms.bg_contrast_25]}>
<View style={[a.pt_2xl, a.px_lg, a.flex_row, a.pb_xs]}>
<Text
style={[
a.flex_1,
a.text_lg,
a.font_bold,
t.atoms.text_contrast_medium,
]}>
<Trans>Suggested for you</Trans>
</Text>
<Person fill={t.atoms.text_contrast_low.color} />
</View>
{gtMobile ? (
<View style={[a.flex_1, a.px_lg, a.pt_md, a.pb_xl, a.gap_md]}>
<View style={[a.flex_1, a.flex_row, a.flex_wrap, a.gap_md]}>
{content}
</View>
<View
style={[
a.flex_row,
a.justify_end,
a.align_center,
a.pt_xs,
a.gap_md,
]}>
<InlineLinkText to="/search" style={[t.atoms.text_contrast_medium]}>
<Trans>Browse more suggestions</Trans>
</InlineLinkText>
<Arrow size="sm" fill={t.atoms.text_contrast_medium.color} />
</View>
</View>
) : (
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
snapToInterval={MOBILE_CARD_WIDTH + a.gap_md.gap}
decelerationRate="fast">
<View style={[a.px_lg, a.pt_md, a.pb_xl, a.flex_row, a.gap_md]}>
{content}
<Button
label={_(msg`Browse more accounts on the Explore page`)}
onPress={() => {
navigation.navigate('SearchTab')
}}>
<CardOuter style={[a.flex_1, {borderWidth: 0}]}>
<View style={[a.flex_1, a.justify_center]}>
<View style={[a.flex_row, a.px_lg]}>
<Text style={[a.pr_xl, a.flex_1, a.leading_snug]}>
<Trans>Browse more suggestions on the Explore page</Trans>
</Text>
<Arrow size="xl" />
</View>
</View>
</CardOuter>
</Button>
</View>
</ScrollView>
)}
</View>
)
}
export function SuggestedFeeds() {
const numFeedsToDisplay = 3
const t = useTheme()
const {_} = useLingui()
const {data, isLoading, error} = useGetPopularFeedsQuery({
limit: numFeedsToDisplay,
})
const navigation = useNavigation<NavigationProp>()
const {gtMobile} = useBreakpoints()
const feeds = React.useMemo(() => {
const items: AppBskyFeedDefs.GeneratorView[] = []
if (!data) return items
for (const page of data.pages) {
for (const feed of page.feeds) {
items.push(feed)
}
}
return items
}, [data])
const content = isLoading ? (
Array(numFeedsToDisplay)
.fill(0)
.map((_, i) => <SuggestedFeedsCardPlaceholder key={i} />)
) : error || !feeds ? null : (
<>
{feeds.slice(0, numFeedsToDisplay).map(feed => (
<FeedCard.Link
key={feed.uri}
view={feed}
onPress={() => {
logEvent('feed:interstitial:feedCard:press', {})
}}>
{({hovered, pressed}) => (
<CardOuter
style={[
a.flex_1,
(hovered || pressed) && t.atoms.border_contrast_high,
]}>
<FeedCard.Outer>
<FeedCard.Header>
<FeedCard.Avatar src={feed.avatar} />
<FeedCard.TitleAndByline
title={feed.displayName}
creator={feed.creator}
/>
</FeedCard.Header>
<FeedCard.Description
description={feed.description}
numberOfLines={3}
/>
</FeedCard.Outer>
</CardOuter>
)}
</FeedCard.Link>
))}
</>
)
return error ? null : (
<View
style={[a.border_t, t.atoms.border_contrast_low, t.atoms.bg_contrast_25]}>
<View style={[a.pt_2xl, a.px_lg, a.flex_row, a.pb_xs]}>
<Text
style={[
a.flex_1,
a.text_lg,
a.font_bold,
t.atoms.text_contrast_medium,
]}>
<Trans>Some other feeds you might like</Trans>
</Text>
<Hashtag fill={t.atoms.text_contrast_low.color} />
</View>
{gtMobile ? (
<View style={[a.flex_1, a.px_lg, a.pt_md, a.pb_xl, a.gap_md]}>
{content}
<View
style={[
a.flex_row,
a.justify_end,
a.align_center,
a.pt_xs,
a.gap_md,
]}>
<InlineLinkText to="/search" style={[t.atoms.text_contrast_medium]}>
<Trans>Browse more suggestions</Trans>
</InlineLinkText>
<Arrow size="sm" fill={t.atoms.text_contrast_medium.color} />
</View>
</View>
) : (
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
snapToInterval={MOBILE_CARD_WIDTH + a.gap_md.gap}
decelerationRate="fast">
<View style={[a.px_lg, a.pt_md, a.pb_xl, a.flex_row, a.gap_md]}>
{content}
<Button
label={_(msg`Browse more feeds on the Explore page`)}
onPress={() => {
navigation.navigate('SearchTab')
}}
style={[a.flex_col]}>
<CardOuter style={[a.flex_1]}>
<View style={[a.flex_1, a.justify_center]}>
<View style={[a.flex_row, a.px_lg]}>
<Text style={[a.pr_xl, a.flex_1, a.leading_snug]}>
<Trans>Browse more suggestions on the Explore page</Trans>
</Text>
<Arrow size="xl" />
</View>
</View>
</CardOuter>
</Button>
</View>
</ScrollView>
)}
</View>
)
}
export function ProgressGuide() {
const t = useTheme()
const {isDesktop} = useWebMediaQueries()
const guide = useProgressGuide('like-10-and-follow-7')
if (isDesktop) {
return null
}
return guide ? (
<View
style={[
a.border_t,
t.atoms.border_contrast_low,
a.px_lg,
a.py_lg,
a.pb_lg,
]}>
<ProgressGuideList />
</View>
) : null
}
+48 -1
View File
@@ -1,5 +1,10 @@
import React from 'react'
import {GestureResponderEvent} from 'react-native'
import {
GestureResponderEvent,
Pressable,
StyleProp,
ViewStyle,
} from 'react-native'
import {sanitizeUrl} from '@braintree/sanitize-url'
import {StackActions, useLinkProps} from '@react-navigation/native'
@@ -323,3 +328,45 @@ export function InlineLinkText({
</Text>
)
}
/**
* A Pressable that uses useLink to handle navigation. It is unstyled, so can be used in cases where the Button styles
* in Link are not desired.
* @param displayText
* @param style
* @param children
* @param rest
* @constructor
*/
export function BaseLink({
displayText,
onPress: onPressOuter,
style,
children,
...rest
}: {
style?: StyleProp<ViewStyle>
children: React.ReactNode
to: string
action: 'push' | 'replace' | 'navigate'
onPress?: () => false | void
shareOnLongPress?: boolean
label: string
displayText?: string
}) {
const {onPress, ...btnProps} = useLink({
displayText: displayText ?? rest.to,
...rest,
})
return (
<Pressable
style={style}
onPress={e => {
onPressOuter?.()
onPress(e)
}}
{...btnProps}>
{children}
</Pressable>
)
}
+129
View File
@@ -0,0 +1,129 @@
import React from 'react'
import {View} from 'react-native'
import {AppBskyActorDefs, AppBskyGraphDefs, AtUri} from '@atproto/api'
import {Trans} from '@lingui/macro'
import {useQueryClient} from '@tanstack/react-query'
import {sanitizeHandle} from 'lib/strings/handles'
import {precacheList} from 'state/queries/feed'
import {useTheme} from '#/alf'
import {atoms as a} from '#/alf'
import {
Avatar,
Description,
Header,
Outer,
SaveButton,
} from '#/components/FeedCard'
import {Link as InternalLink, LinkProps} from '#/components/Link'
import {Text} from '#/components/Typography'
/*
* This component is based on `FeedCard` and is tightly coupled with that
* component. Please refer to `FeedCard` for more context.
*/
export {
Avatar,
AvatarPlaceholder,
Description,
Header,
Outer,
SaveButton,
TitleAndBylinePlaceholder,
} from '#/components/FeedCard'
const CURATELIST = 'app.bsky.graph.defs#curatelist'
const MODLIST = 'app.bsky.graph.defs#modlist'
type Props = {
view: AppBskyGraphDefs.ListView
showPinButton?: boolean
}
export function Default(props: Props) {
const {view, showPinButton} = props
return (
<Link label={view.name} {...props}>
<Outer>
<Header>
<Avatar src={view.avatar} />
<TitleAndByline
title={view.name}
creator={view.creator}
purpose={view.purpose}
/>
{showPinButton && view.purpose === CURATELIST && (
<SaveButton view={view} pin />
)}
</Header>
<Description description={view.description} />
</Outer>
</Link>
)
}
export function Link({
view,
children,
...props
}: Props & Omit<LinkProps, 'to'>) {
const queryClient = useQueryClient()
const href = React.useMemo(() => {
return createProfileListHref({list: view})
}, [view])
React.useEffect(() => {
precacheList(queryClient, view)
}, [view, queryClient])
return (
<InternalLink to={href} {...props}>
{children}
</InternalLink>
)
}
export function TitleAndByline({
title,
creator,
purpose = CURATELIST,
}: {
title: string
creator?: AppBskyActorDefs.ProfileViewBasic
purpose?: AppBskyGraphDefs.ListView['purpose']
}) {
const t = useTheme()
return (
<View style={[a.flex_1]}>
<Text style={[a.text_md, a.font_bold, a.leading_snug]} numberOfLines={1}>
{title}
</Text>
{creator && (
<Text
style={[a.leading_snug, t.atoms.text_contrast_medium]}
numberOfLines={1}>
{purpose === MODLIST ? (
<Trans>
Moderation list by {sanitizeHandle(creator.handle, '@')}
</Trans>
) : (
<Trans>List by {sanitizeHandle(creator.handle, '@')}</Trans>
)}
</Text>
)}
</View>
)
}
export function createProfileListHref({
list,
}: {
list: AppBskyGraphDefs.ListView
}) {
const urip = new AtUri(list.uri)
const handleOrDid = list.creator.handle || list.creator.did
return `/profile/${handleOrDid}/lists/${urip.rkey}`
}
+54 -25
View File
@@ -6,10 +6,11 @@ import {useLingui} from '@lingui/react'
import {differenceInSeconds} from 'date-fns'
import {useGetTimeAgo} from '#/lib/hooks/useTimeAgo'
import {isNative} from '#/platform/detection'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {HITSLOP_10} from 'lib/constants'
import {sanitizeDisplayName} from 'lib/strings/display-names'
import {isWeb} from 'platform/detection'
import {useSession} from 'state/session'
import {atoms as a, useTheme} from '#/alf'
import {Button, ButtonText} from '#/components/Button'
import * as Dialog from '#/components/Dialog'
@@ -28,16 +29,27 @@ export function NewskieDialog({
const {_} = useLingui()
const t = useTheme()
const moderationOpts = useModerationOpts()
const {currentAccount} = useSession()
const timeAgo = useGetTimeAgo()
const control = useDialogControl()
const isMe = profile.did === currentAccount?.did
const createdAt = profile.createdAt as string | undefined
const profileName = React.useMemo(() => {
const name = profile.displayName || profile.handle
if (isMe) {
return _(msg`You`)
}
if (!moderationOpts) return name
const moderation = moderateProfile(profile, moderationOpts)
return sanitizeDisplayName(name, moderation.ui('displayName'))
}, [moderationOpts, profile])
}, [_, isMe, moderationOpts, profile])
const [now] = React.useState(() => Date.now())
const timeAgo = useGetTimeAgo()
const createdAt = profile.createdAt as string | undefined
const daysOld = React.useMemo(() => {
if (!createdAt) return Infinity
return differenceInSeconds(now, new Date(createdAt)) / 86400
@@ -70,19 +82,31 @@ export function NewskieDialog({
<Dialog.ScrollableInner
label={_(msg`New user info dialog`)}
style={[{width: 'auto', maxWidth: 400, minWidth: 200}]}>
<View style={[a.gap_sm]}>
<View style={[a.gap_md]}>
<View style={[a.align_center]}>
<Newskie
width={64}
height={64}
fill="#FFC404"
style={{marginTop: -10}}
/>
<Text style={[a.font_bold, a.text_xl, {marginTop: -10}]}>
<Trans>Say hello!</Trans>
<View
style={[
{
height: 60,
width: 64,
},
]}>
<Newskie
width={64}
height={64}
fill="#FFC404"
style={[a.absolute, a.inset_0]}
/>
</View>
<Text style={[a.font_bold, a.text_xl]}>
{isMe ? (
<Trans>Welcome, friend!</Trans>
) : (
<Trans>Say hello!</Trans>
)}
</Text>
</View>
<Text style={[a.text_md, a.text_center, a.leading_tight]}>
<Text style={[a.text_md, a.text_center, a.leading_snug]}>
{profile.joinedViaStarterPack ? (
<Trans>
{profileName} joined Bluesky using a starter pack{' '}
@@ -116,18 +140,23 @@ export function NewskieDialog({
</View>
</StarterPackCard.Link>
) : null}
<Button
label={_(msg`Close`)}
variant="solid"
color="secondary"
size="small"
style={[a.mt_sm, isWeb && [a.self_center, {marginLeft: 'auto'}]]}
onPress={() => control.close()}>
<ButtonText>
<Trans>Close</Trans>
</ButtonText>
</Button>
{isNative && (
<Button
label={_(msg`Close`)}
variant="solid"
color="secondary"
size="small"
style={[a.mt_sm]}
onPress={() => control.close()}>
<ButtonText>
<Trans>Close</Trans>
</ButtonText>
</Button>
)}
</View>
<Dialog.Close />
</Dialog.ScrollableInner>
</Dialog.Outer>
</View>
+169
View File
@@ -0,0 +1,169 @@
import React from 'react'
import {View} from 'react-native'
import {BSKY_LABELER_DID, ModerationCause} from '@atproto/api'
import {Trans} from '@lingui/macro'
import {useModerationCauseDescription} from '#/lib/moderation/useModerationCauseDescription'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import {atoms as a, useTheme, ViewStyleProp} from '#/alf'
import {Button} from '#/components/Button'
import {
ModerationDetailsDialog,
useModerationDetailsDialogControl,
} from '#/components/moderation/ModerationDetailsDialog'
import {Text} from '#/components/Typography'
export type CommonProps = {
size?: 'sm' | 'lg'
}
export function Row({
children,
style,
size = 'sm',
}: {children: React.ReactNode | React.ReactNode[]} & CommonProps &
ViewStyleProp) {
const styles = React.useMemo(() => {
switch (size) {
case 'lg':
return [{gap: 5}]
case 'sm':
default:
return [{gap: 3}]
}
}, [size])
return (
<View style={[a.flex_row, a.flex_wrap, a.gap_xs, styles, style]}>
{children}
</View>
)
}
export type LabelProps = {
cause: ModerationCause
disableDetailsDialog?: boolean
noBg?: boolean
} & CommonProps
export function Label({
cause,
size = 'sm',
disableDetailsDialog,
noBg,
}: LabelProps) {
const t = useTheme()
const control = useModerationDetailsDialogControl()
const desc = useModerationCauseDescription(cause)
const isLabeler = Boolean(desc.sourceType && desc.sourceDid)
const isBlueskyLabel =
desc.sourceType === 'labeler' && desc.sourceDid === BSKY_LABELER_DID
const {outer, avi, text} = React.useMemo(() => {
switch (size) {
case 'lg': {
return {
outer: [
t.atoms.bg_contrast_25,
{
gap: 5,
paddingHorizontal: 5,
paddingVertical: 5,
},
],
avi: 16,
text: [a.text_sm],
}
}
case 'sm':
default: {
return {
outer: [
!noBg && t.atoms.bg_contrast_25,
{
gap: 3,
paddingHorizontal: 3,
paddingVertical: 3,
},
],
avi: 12,
text: [a.text_xs],
}
}
}
}, [t, size, noBg])
return (
<>
<Button
disabled={disableDetailsDialog}
label={desc.name}
onPress={e => {
e.preventDefault()
e.stopPropagation()
control.open()
}}>
{({hovered, pressed}) => (
<View
style={[
a.flex_row,
a.align_center,
a.rounded_full,
outer,
(hovered || pressed) && t.atoms.bg_contrast_50,
]}>
{isBlueskyLabel || !isLabeler ? (
<desc.icon
width={avi}
fill={t.atoms.text_contrast_medium.color}
/>
) : (
<UserAvatar avatar={desc.sourceAvi} size={avi} />
)}
<Text
style={[
text,
a.font_semibold,
a.leading_tight,
t.atoms.text_contrast_medium,
{paddingRight: 3},
]}>
{desc.name}
</Text>
</View>
)}
</Button>
{!disableDetailsDialog && (
<ModerationDetailsDialog control={control} modcause={cause} />
)}
</>
)
}
export function FollowsYou({size = 'sm'}: CommonProps) {
const t = useTheme()
const variantStyles = React.useMemo(() => {
switch (size) {
case 'sm':
case 'lg':
default:
return [
{
paddingHorizontal: 6,
paddingVertical: 3,
borderRadius: 4,
},
]
}
}, [size])
return (
<View style={[variantStyles, a.justify_center, t.atoms.bg_contrast_25]}>
<Text style={[a.text_xs, a.leading_tight]}>
<Trans>Follows You</Trans>
</Text>
</View>
)
}
+360 -69
View File
@@ -1,20 +1,33 @@
import React from 'react'
import {View} from 'react-native'
import {AppBskyActorDefs, moderateProfile, ModerationOpts} from '@atproto/api'
import {GestureResponderEvent, View} from 'react-native'
import {
AppBskyActorDefs,
moderateProfile,
ModerationOpts,
RichText as RichTextApi,
} from '@atproto/api'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {createSanitizedDisplayName} from 'lib/moderation/create-sanitized-display-name'
import {LogEvents} from '#/lib/statsig/statsig'
import {sanitizeDisplayName} from '#/lib/strings/display-names'
import {useProfileFollowMutationQueue} from '#/state/queries/profile'
import {sanitizeHandle} from 'lib/strings/handles'
import {useProfileShadow} from 'state/cache/profile-shadow'
import {useSession} from 'state/session'
import {FollowButton} from 'view/com/profile/FollowButton'
import * as Toast from '#/view/com/util/Toast'
import {ProfileCardPills} from 'view/com/profile/ProfileCard'
import {UserAvatar} from 'view/com/util/UserAvatar'
import {atoms as a, useTheme} from '#/alf'
import {Link} from '#/components/Link'
import {Button, ButtonIcon, ButtonProps, ButtonText} from '#/components/Button'
import {Check_Stroke2_Corner0_Rounded as Check} from '#/components/icons/Check'
import {PlusLarge_Stroke2_Corner0_Rounded as Plus} from '#/components/icons/Plus'
import {Link as InternalLink, LinkProps} from '#/components/Link'
import {RichText} from '#/components/RichText'
import {Text} from '#/components/Typography'
export function Default({
profile: profileUnshadowed,
profile,
moderationOpts,
logContext = 'ProfileCard',
}: {
@@ -22,70 +35,348 @@ export function Default({
moderationOpts: ModerationOpts
logContext?: 'ProfileCard' | 'StarterPackProfilesList'
}) {
const t = useTheme()
const {currentAccount, hasSession} = useSession()
const profile = useProfileShadow(profileUnshadowed)
const name = createSanitizedDisplayName(profile)
const handle = `@${sanitizeHandle(profile.handle)}`
const moderation = moderateProfile(profile, moderationOpts)
return (
<Wrapper did={profile.did}>
<View style={[a.flex_row, a.gap_sm]}>
<UserAvatar
size={42}
avatar={profile.avatar}
type={
profile.associated?.labeler
? 'labeler'
: profile.associated?.feedgens
? 'algo'
: 'user'
}
moderation={moderation.ui('avatar')}
/>
<View style={[a.flex_1]}>
<Text
style={[a.text_md, a.font_bold, a.leading_snug]}
numberOfLines={1}>
{name}
</Text>
<Text
style={[a.leading_snug, t.atoms.text_contrast_medium]}
numberOfLines={1}>
{handle}
</Text>
</View>
{hasSession && profile.did !== currentAccount?.did && (
<View style={[a.justify_center, {marginLeft: 'auto'}]}>
<FollowButton profile={profile} logContext={logContext} />
</View>
)}
</View>
<View style={[a.mb_xs]}>
<ProfileCardPills
followedBy={Boolean(profile.viewer?.followedBy)}
moderation={moderation}
/>
</View>
{profile.description && (
<Text numberOfLines={3} style={[a.leading_snug]}>
{profile.description}
</Text>
)}
</Wrapper>
)
}
function Wrapper({did, children}: {did: string; children: React.ReactNode}) {
return (
<Link
to={{
screen: 'Profile',
params: {name: did},
}}>
<View style={[a.flex_1, a.gap_xs]}>{children}</View>
<Link did={profile.did}>
<Card
profile={profile}
moderationOpts={moderationOpts}
logContext={logContext}
/>
</Link>
)
}
export function Card({
profile,
moderationOpts,
logContext = 'ProfileCard',
}: {
profile: AppBskyActorDefs.ProfileViewDetailed
moderationOpts: ModerationOpts
logContext?: 'ProfileCard' | 'StarterPackProfilesList'
}) {
const moderation = moderateProfile(profile, moderationOpts)
return (
<Outer>
<Header>
<Avatar profile={profile} moderationOpts={moderationOpts} />
<NameAndHandle profile={profile} moderationOpts={moderationOpts} />
<FollowButton
profile={profile}
moderationOpts={moderationOpts}
logContext={logContext}
/>
</Header>
<ProfileCardPills
followedBy={Boolean(profile.viewer?.followedBy)}
moderation={moderation}
/>
<Description profile={profile} />
</Outer>
)
}
export function Outer({
children,
}: {
children: React.ReactElement | React.ReactElement[]
}) {
return <View style={[a.w_full, a.flex_1, a.gap_xs]}>{children}</View>
}
export function Header({
children,
}: {
children: React.ReactElement | React.ReactElement[]
}) {
return <View style={[a.flex_row, a.align_center, a.gap_sm]}>{children}</View>
}
export function Link({
did,
children,
style,
...rest
}: {did: string} & Omit<LinkProps, 'to'>) {
return (
<InternalLink
to={{
screen: 'Profile',
params: {name: did},
}}
style={[a.flex_col, style]}
{...rest}>
{children}
</InternalLink>
)
}
export function Avatar({
profile,
moderationOpts,
}: {
profile: AppBskyActorDefs.ProfileViewDetailed
moderationOpts: ModerationOpts
}) {
const moderation = moderateProfile(profile, moderationOpts)
return (
<UserAvatar
size={42}
avatar={profile.avatar}
type={profile.associated?.labeler ? 'labeler' : 'user'}
moderation={moderation.ui('avatar')}
/>
)
}
export function AvatarPlaceholder() {
const t = useTheme()
return (
<View
style={[
a.rounded_full,
t.atoms.bg_contrast_50,
{
width: 42,
height: 42,
},
]}
/>
)
}
export function NameAndHandle({
profile,
moderationOpts,
}: {
profile: AppBskyActorDefs.ProfileViewDetailed
moderationOpts: ModerationOpts
}) {
const t = useTheme()
const moderation = moderateProfile(profile, moderationOpts)
const name = sanitizeDisplayName(
profile.displayName || sanitizeHandle(profile.handle),
moderation.ui('displayName'),
)
const handle = sanitizeHandle(profile.handle, '@')
return (
<View style={[a.flex_1]}>
<Text style={[a.text_md, a.font_bold, a.leading_snug]} numberOfLines={1}>
{name}
</Text>
<Text
style={[a.leading_snug, t.atoms.text_contrast_medium]}
numberOfLines={1}>
{handle}
</Text>
</View>
)
}
export function NameAndHandlePlaceholder() {
const t = useTheme()
return (
<View style={[a.flex_1, a.gap_xs]}>
<View
style={[
a.rounded_xs,
t.atoms.bg_contrast_50,
{
width: '60%',
height: 14,
},
]}
/>
<View
style={[
a.rounded_xs,
t.atoms.bg_contrast_50,
{
width: '40%',
height: 10,
},
]}
/>
</View>
)
}
export function Description({
profile: profileUnshadowed,
}: {
profile: AppBskyActorDefs.ProfileViewDetailed
}) {
const profile = useProfileShadow(profileUnshadowed)
const {description} = profile
const rt = React.useMemo(() => {
if (!description) return
const rt = new RichTextApi({text: description || ''})
rt.detectFacetsWithoutResolution()
return rt
}, [description])
if (!rt) return null
if (
profile.viewer &&
(profile.viewer.blockedBy ||
profile.viewer.blocking ||
profile.viewer.blockingByList)
)
return null
return (
<View style={[a.pt_xs]}>
<RichText
value={rt}
style={[a.leading_snug]}
numberOfLines={3}
disableLinks
/>
</View>
)
}
export function DescriptionPlaceholder() {
const t = useTheme()
return (
<View style={[a.gap_xs]}>
<View
style={[a.rounded_xs, a.w_full, t.atoms.bg_contrast_50, {height: 12}]}
/>
<View
style={[a.rounded_xs, a.w_full, t.atoms.bg_contrast_50, {height: 12}]}
/>
<View
style={[
a.rounded_xs,
a.w_full,
t.atoms.bg_contrast_50,
{height: 12, width: 100},
]}
/>
</View>
)
}
export type FollowButtonProps = {
profile: AppBskyActorDefs.ProfileViewBasic
moderationOpts: ModerationOpts
logContext: LogEvents['profile:follow']['logContext'] &
LogEvents['profile:unfollow']['logContext']
} & Partial<ButtonProps>
export function FollowButton(props: FollowButtonProps) {
const {currentAccount, hasSession} = useSession()
const isMe = props.profile.did === currentAccount?.did
return hasSession && !isMe ? <FollowButtonInner {...props} /> : null
}
export function FollowButtonInner({
profile: profileUnshadowed,
moderationOpts,
logContext,
...rest
}: FollowButtonProps) {
const {_} = useLingui()
const profile = useProfileShadow(profileUnshadowed)
const moderation = moderateProfile(profile, moderationOpts)
const [queueFollow, queueUnfollow] = useProfileFollowMutationQueue(
profile,
logContext,
)
const isRound = Boolean(rest.shape && rest.shape === 'round')
const onPressFollow = async (e: GestureResponderEvent) => {
e.preventDefault()
e.stopPropagation()
try {
await queueFollow()
Toast.show(
_(
msg`Following ${sanitizeDisplayName(
profile.displayName || profile.handle,
moderation.ui('displayName'),
)}`,
),
)
} catch (e: any) {
if (e?.name !== 'AbortError') {
Toast.show(_(msg`An issue occurred, please try again.`))
}
}
}
const onPressUnfollow = async (e: GestureResponderEvent) => {
e.preventDefault()
e.stopPropagation()
try {
await queueUnfollow()
Toast.show(
_(
msg`No longer following ${sanitizeDisplayName(
profile.displayName || profile.handle,
moderation.ui('displayName'),
)}`,
),
)
} catch (e: any) {
if (e?.name !== 'AbortError') {
Toast.show(_(msg`An issue occurred, please try again.`))
}
}
}
const unfollowLabel = _(
msg({
message: 'Following',
comment: 'User is following this account, click to unfollow',
}),
)
const followLabel = _(
msg({
message: 'Follow',
comment: 'User is not following this account, click to follow',
}),
)
if (!profile.viewer) return null
if (
profile.viewer.blockedBy ||
profile.viewer.blocking ||
profile.viewer.blockingByList
)
return null
return (
<View>
{profile.viewer.following ? (
<Button
label={unfollowLabel}
size="small"
variant="solid"
color="secondary"
{...rest}
onPress={onPressUnfollow}>
<ButtonIcon icon={Check} position={isRound ? undefined : 'left'} />
{isRound ? null : <ButtonText>{unfollowLabel}</ButtonText>}
</Button>
) : (
<Button
label={followLabel}
size="small"
variant="solid"
color="primary"
{...rest}
onPress={onPressFollow}>
<ButtonIcon icon={Plus} position={isRound ? undefined : 'left'} />
{isRound ? null : <ButtonText>{followLabel}</ButtonText>}
</Button>
)}
</View>
)
}
@@ -29,10 +29,10 @@ import {
} from '#/components/KnownFollowers'
import {InlineLinkText, Link} from '#/components/Link'
import {Loader} from '#/components/Loader'
import * as Pills from '#/components/Pills'
import {Portal} from '#/components/Portal'
import {RichText} from '#/components/RichText'
import {Text} from '#/components/Typography'
import {ProfileLabel} from '../moderation/ProfileHeaderAlerts'
import {ProfileHoverCardProps} from './types'
const floatingMiddlewares = [
@@ -476,8 +476,9 @@ function Inner({
{isBlockedUser && (
<View style={[a.flex_row, a.flex_wrap, a.gap_xs]}>
{moderation.ui('profileView').alerts.map(cause => (
<ProfileLabel
<Pills.Label
key={getModerationCauseKey(cause)}
size="lg"
cause={cause}
disableDetailsDialog
/>
+61
View File
@@ -0,0 +1,61 @@
import React from 'react'
import {StyleProp, View, ViewStyle} from 'react-native'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {
useProgressGuide,
useProgressGuideControls,
} from '#/state/shell/progress-guide'
import {atoms as a, useTheme} from '#/alf'
import {Button, ButtonIcon} from '#/components/Button'
import {TimesLarge_Stroke2_Corner0_Rounded as Times} from '#/components/icons/Times'
import {Text} from '#/components/Typography'
import {ProgressGuideTask} from './Task'
export function ProgressGuideList({style}: {style?: StyleProp<ViewStyle>}) {
const t = useTheme()
const {_} = useLingui()
const guide = useProgressGuide('like-10-and-follow-7')
const {endProgressGuide} = useProgressGuideControls()
if (guide) {
return (
<View style={[a.flex_col, a.gap_md, style]}>
<View style={[a.flex_row, a.align_center, a.justify_between]}>
<Text
style={[
t.atoms.text_contrast_medium,
a.font_semibold,
a.text_sm,
{textTransform: 'uppercase'},
]}>
<Trans>Getting started</Trans>
</Text>
<Button
variant="ghost"
size="tiny"
color="secondary"
shape="round"
label={_(msg`Dismiss getting started guide`)}
onPress={endProgressGuide}>
<ButtonIcon icon={Times} size="sm" />
</Button>
</View>
<ProgressGuideTask
current={guide.numLikes + 1}
total={10 + 1}
title={_(msg`Like 10 posts`)}
subtitle={_(msg`Teach our algorithm what you like`)}
/>
<ProgressGuideTask
current={guide.numFollows + 1}
total={7 + 1}
title={_(msg`Follow 7 accounts`)}
subtitle={_(msg`Bluesky is better with friends!`)}
/>
</View>
)
}
return null
}
+50
View File
@@ -0,0 +1,50 @@
import React from 'react'
import {View} from 'react-native'
import * as Progress from 'react-native-progress'
import {atoms as a, useTheme} from '#/alf'
import {AnimatedCheck} from '../anim/AnimatedCheck'
import {Text} from '../Typography'
export function ProgressGuideTask({
current,
total,
title,
subtitle,
}: {
current: number
total: number
title: string
subtitle?: string
}) {
const t = useTheme()
return (
<View style={[a.flex_row, a.gap_sm, !subtitle && a.align_center]}>
{current === total ? (
<AnimatedCheck playOnMount fill={t.palette.primary_500} width={20} />
) : (
<Progress.Circle
progress={current / total}
color={t.palette.primary_400}
size={20}
thickness={3}
borderWidth={0}
unfilledColor={t.palette.contrast_50}
/>
)}
<View style={[a.flex_col, a.gap_2xs, {marginTop: -2}]}>
<Text style={[a.text_sm, a.font_semibold, a.leading_tight]}>
{title}
</Text>
{subtitle && (
<Text
style={[a.text_sm, t.atoms.text_contrast_medium, a.leading_tight]}>
{subtitle}
</Text>
)}
</View>
</View>
)
}
+169
View File
@@ -0,0 +1,169 @@
import React, {useImperativeHandle} from 'react'
import {Pressable, useWindowDimensions, View} from 'react-native'
import Animated, {
Easing,
runOnJS,
useAnimatedStyle,
useSharedValue,
withTiming,
} from 'react-native-reanimated'
import {useSafeAreaInsets} from 'react-native-safe-area-context'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {isWeb} from '#/platform/detection'
import {atoms as a, useTheme} from '#/alf'
import {Portal} from '#/components/Portal'
import {AnimatedCheck, AnimatedCheckRef} from '../anim/AnimatedCheck'
import {Text} from '../Typography'
export interface ProgressGuideToastRef {
open(): void
close(): void
}
export interface ProgressGuideToastProps {
title: string
subtitle?: string
visibleDuration?: number // default 5s
}
export const ProgressGuideToast = React.forwardRef<
ProgressGuideToastRef,
ProgressGuideToastProps
>(function ProgressGuideToast({title, subtitle, visibleDuration}, ref) {
const t = useTheme()
const {_} = useLingui()
const insets = useSafeAreaInsets()
const [isOpen, setIsOpen] = React.useState(false)
const translateY = useSharedValue(0)
const opacity = useSharedValue(0)
const animatedCheckRef = React.useRef<AnimatedCheckRef | null>(null)
const timeoutRef = React.useRef<NodeJS.Timeout | undefined>()
const winDim = useWindowDimensions()
/**
* Methods
*/
const close = React.useCallback(() => {
// clear the timeout, in case this was called imperatively
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
timeoutRef.current = undefined
}
// animate the opacity then set isOpen to false when done
const setIsntOpen = () => setIsOpen(false)
opacity.value = withTiming(
0,
{
duration: 400,
easing: Easing.out(Easing.cubic),
},
() => runOnJS(setIsntOpen)(),
)
}, [setIsOpen, opacity])
const open = React.useCallback(() => {
// set isOpen=true to render
setIsOpen(true)
// animate the vertical translation, the opacity, and the checkmark
const playCheckmark = () => animatedCheckRef.current?.play()
opacity.value = 0
opacity.value = withTiming(
1,
{
duration: 100,
easing: Easing.out(Easing.cubic),
},
() => runOnJS(playCheckmark)(),
)
translateY.value = 0
translateY.value = withTiming(insets.top + 10, {
duration: 500,
easing: Easing.out(Easing.cubic),
})
// start the countdown timer to autoclose
timeoutRef.current = setTimeout(close, visibleDuration || 5e3)
}, [setIsOpen, translateY, opacity, insets, close, visibleDuration])
useImperativeHandle(
ref,
() => ({
open,
close,
}),
[open, close],
)
const containerStyle = React.useMemo(() => {
let left = 10
let right = 10
if (isWeb && winDim.width > 400) {
left = right = (winDim.width - 380) / 2
}
return {
position: isWeb ? 'fixed' : 'absolute',
top: 0,
left,
right,
}
}, [winDim.width])
const animatedStyle = useAnimatedStyle(() => ({
transform: [{translateY: translateY.value}],
opacity: opacity.value,
}))
return (
isOpen && (
<Portal>
<Animated.View
style={[
// @ts-ignore position: fixed is web only
containerStyle,
animatedStyle,
]}>
<Pressable
style={[
t.atoms.bg,
a.flex_row,
a.align_center,
a.gap_md,
a.border,
t.atoms.border_contrast_high,
a.rounded_md,
a.px_lg,
a.py_md,
a.shadow_sm,
{
shadowRadius: 8,
shadowOpacity: 0.1,
shadowOffset: {width: 0, height: 2},
elevation: 8,
},
]}
onPress={close}
accessibilityLabel={_(msg`Tap to dismiss`)}
accessibilityHint="">
<AnimatedCheck
fill={t.palette.primary_500}
ref={animatedCheckRef}
/>
<View>
<Text style={[a.text_md, a.font_semibold]}>{title}</Text>
{subtitle && (
<Text style={[a.text_sm, t.atoms.text_contrast_medium]}>
{subtitle}
</Text>
)}
</View>
</Pressable>
</Animated.View>
</Portal>
)
)
})
+14 -12
View File
@@ -17,6 +17,19 @@ import {Text, TextProps} from '#/components/Typography'
const WORD_WRAP = {wordWrap: 1}
export type RichTextProps = TextStyleProp &
Pick<TextProps, 'selectable'> & {
value: RichTextAPI | string
testID?: string
numberOfLines?: number
disableLinks?: boolean
enableTags?: boolean
authorHandle?: string
onLinkPress?: LinkProps['onPress']
interactiveStyle?: TextStyle
emojiMultiplier?: number
}
export function RichText({
testID,
value,
@@ -29,18 +42,7 @@ export function RichText({
onLinkPress,
interactiveStyle,
emojiMultiplier = 1.85,
}: TextStyleProp &
Pick<TextProps, 'selectable'> & {
value: RichTextAPI | string
testID?: string
numberOfLines?: number
disableLinks?: boolean
enableTags?: boolean
authorHandle?: string
onLinkPress?: LinkProps['onPress']
interactiveStyle?: TextStyle
emojiMultiplier?: number
}) {
}: RichTextProps) {
const richText = React.useMemo(
() =>
value instanceof RichTextAPI ? value : new RichTextAPI({text: value}),
@@ -45,7 +45,7 @@ export const FeedsList = React.forwardRef<SectionRef, ProfilesListProps>(
(isWeb || index !== 0) && a.border_t,
t.atoms.border_contrast_low,
]}>
<FeedCard.Default type="feed" view={item} />
<FeedCard.Default view={item} />
</View>
)
}
@@ -0,0 +1,51 @@
import React, {useCallback} from 'react'
import {View} from 'react-native'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {FeedDescriptor} from '#/state/queries/post-feed'
import {isNative} from 'platform/detection'
import {Feed} from 'view/com/posts/Feed'
import {EmptyState} from 'view/com/util/EmptyState'
import {ListRef} from 'view/com/util/List'
import {SectionRef} from '#/screens/Profile/Sections/types'
interface ProfilesListProps {
listUri: string
headerHeight: number
scrollElRef: ListRef
}
export const PostsList = React.forwardRef<SectionRef, ProfilesListProps>(
function PostsListImpl({listUri, headerHeight, scrollElRef}, ref) {
const feed: FeedDescriptor = `list|${listUri}|as_following`
const {_} = useLingui()
const onScrollToTop = useCallback(() => {
scrollElRef.current?.scrollToOffset({
animated: isNative,
offset: -headerHeight,
})
}, [scrollElRef, headerHeight])
React.useImperativeHandle(ref, () => ({
scrollToTop: onScrollToTop,
}))
const renderPostsEmpty = useCallback(() => {
return <EmptyState icon="hashtag" message={_(msg`This feed is empty.`)} />
}, [_])
return (
<View>
<Feed
feed={feed}
pollInterval={60e3}
scrollElRef={scrollElRef}
renderEmptyState={renderPostsEmpty}
headerOffset={headerHeight}
/>
</View>
)
},
)
@@ -9,11 +9,14 @@ import {
import {InfiniteData, UseInfiniteQueryResult} from '@tanstack/react-query'
import {useBottomBarOffset} from 'lib/hooks/useBottomBarOffset'
import {isBlockedOrBlocking} from 'lib/moderation/blocked-and-muted'
import {isNative, isWeb} from 'platform/detection'
import {useListMembersQuery} from 'state/queries/list-members'
import {useSession} from 'state/session'
import {List, ListRef} from 'view/com/util/List'
import {SectionRef} from '#/screens/Profile/Sections/types'
import {atoms as a, useTheme} from '#/alf'
import {ListMaybePlaceholder} from '#/components/Lists'
import {Default as ProfileCard} from '#/components/ProfileCard'
function keyExtractor(item: AppBskyActorDefs.ProfileViewBasic, index: number) {
@@ -32,21 +35,21 @@ interface ProfilesListProps {
export const ProfilesList = React.forwardRef<SectionRef, ProfilesListProps>(
function ProfilesListImpl(
{listUri, listMembersQuery, moderationOpts, headerHeight, scrollElRef},
{listUri, moderationOpts, headerHeight, scrollElRef},
ref,
) {
const t = useTheme()
const [initialHeaderHeight] = React.useState(headerHeight)
const bottomBarOffset = useBottomBarOffset(20)
const {currentAccount} = useSession()
const {data, refetch, isError} = useListMembersQuery(listUri, 50)
const [isPTRing, setIsPTRing] = React.useState(false)
const {data, refetch} = listMembersQuery
// The server returns these sorted by descending creation date, so we want to invert
const profiles = data?.pages
.flatMap(p => p.items.map(i => i.subject))
.filter(p => !isBlockedOrBlocking(p) && !p.associated?.labeler)
.reverse()
const isOwn = new AtUri(listUri).host === currentAccount?.did
@@ -94,7 +97,19 @@ export const ProfilesList = React.forwardRef<SectionRef, ProfilesListProps>(
)
}
if (listMembersQuery)
if (!data) {
return (
<View style={{marginTop: headerHeight, marginBottom: bottomBarOffset}}>
<ListMaybePlaceholder
isLoading={true}
isError={isError}
onRetry={refetch}
/>
</View>
)
}
if (data)
return (
<List
data={getSortedProfiles()}
@@ -232,11 +232,13 @@ function Empty() {
t.atoms.text_contrast_medium,
{color: 'white'},
]}>
You haven't created a starter pack yet!
<Trans>You haven't created a starter pack yet!</Trans>
</Text>
<Text style={[a.text_md, {color: 'white'}]}>
Starter packs let you easily share your favorite feeds and people with
your friends.
<Trans>
Starter packs let you easily share your favorite feeds and people
with your friends.
</Trans>
</Text>
</View>
<View style={[a.flex_row, a.gap_md, {marginLeft: 'auto'}]}>
+2 -8
View File
@@ -1,16 +1,14 @@
import React from 'react'
import {View} from 'react-native'
import ViewShot from 'react-native-view-shot'
import * as FS from 'expo-file-system'
import {requestMediaLibraryPermissionsAsync} from 'expo-image-picker'
import {createAssetAsync} from 'expo-media-library'
import * as Sharing from 'expo-sharing'
import {AppBskyGraphDefs, AppBskyGraphStarterpack} from '@atproto/api'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {nanoid} from 'nanoid/non-secure'
import {logger} from '#/logger'
import {saveImageToMediaLibrary} from 'lib/media/manip'
import {logEvent} from 'lib/statsig/statsig'
import {isNative, isWeb} from 'platform/detection'
import * as Toast from '#/view/com/util/Toast'
@@ -65,13 +63,9 @@ export function QrCodeDialog({
return
}
const filename = `${FS.documentDirectory}/${nanoid(12)}.png`
// Incase of a FS failure, don't crash the app
try {
await FS.copyAsync({from: uri, to: filename})
await saveImageToMediaLibrary({uri: filename})
await FS.deleteAsync(filename)
await createAssetAsync(`file://${uri}`)
} catch (e: unknown) {
Toast.show(_(msg`An error occurred while saving the QR code!`))
logger.error('Failed to save QR code', {error: e})
+5 -18
View File
@@ -1,12 +1,10 @@
import React from 'react'
import {View} from 'react-native'
import * as FS from 'expo-file-system'
import {Image} from 'expo-image'
import {requestMediaLibraryPermissionsAsync} from 'expo-image-picker'
import {AppBskyGraphDefs} from '@atproto/api'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {nanoid} from 'nanoid/non-secure'
import {logger} from '#/logger'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
@@ -72,19 +70,8 @@ function ShareDialogInner({
return
}
const cachePath = await Image.getCachePathAsync(imageUrl)
const filename = `${FS.documentDirectory}/${nanoid(12)}.png`
if (!cachePath) {
Toast.show(_(msg`An error occurred while saving the image.`))
return
}
try {
await FS.copyAsync({from: cachePath, to: filename})
await saveImageToMediaLibrary({uri: filename})
await FS.deleteAsync(filename)
await saveImageToMediaLibrary({uri: imageUrl})
Toast.show(_(msg`Image saved to your camera roll!`))
control.close()
} catch (e: unknown) {
@@ -133,18 +120,18 @@ function ShareDialogInner({
isWeb && [a.gap_sm, a.flex_row_reverse, {marginLeft: 'auto'}],
]}>
<Button
label="Share link"
label={isWeb ? _(msg`Copy link`) : _(msg`Share link`)}
variant="solid"
color="secondary"
size="small"
style={[isWeb && a.self_center]}
onPress={onShareLink}>
<ButtonText>
{isWeb ? <Trans>Copy Link</Trans> : <Trans>Share Link</Trans>}
{isWeb ? <Trans>Copy Link</Trans> : <Trans>Share link</Trans>}
</ButtonText>
</Button>
<Button
label="Create QR code"
label={_(msg`Share QR code`)}
variant="solid"
color="secondary"
size="small"
@@ -155,7 +142,7 @@ function ShareDialogInner({
})
}}>
<ButtonText>
<Trans>Create QR code</Trans>
<Trans>Share QR code</Trans>
</ButtonText>
</Button>
{isNative && (
+50 -10
View File
@@ -1,15 +1,20 @@
import React from 'react'
import {View} from 'react-native'
import {Image} from 'expo-image'
import {AppBskyGraphStarterpack, AtUri} from '@atproto/api'
import {StarterPackViewBasic} from '@atproto/api/dist/client/types/app/bsky/graph/defs'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useQueryClient} from '@tanstack/react-query'
import {sanitizeHandle} from 'lib/strings/handles'
import {getStarterPackOgCard} from 'lib/strings/starter-pack'
import {precacheResolvedUri} from 'state/queries/resolve-uri'
import {precacheStarterPack} from 'state/queries/starter-packs'
import {useSession} from 'state/session'
import {atoms as a, useTheme} from '#/alf'
import {StarterPack} from '#/components/icons/StarterPack'
import {Link as InternalLink, LinkProps} from '#/components/Link'
import {BaseLink} from '#/components/Link'
import {Text} from '#/components/Typography'
export function Default({starterPack}: {starterPack?: StarterPackViewBasic}) {
@@ -88,10 +93,13 @@ export function Card({
export function Link({
starterPack,
children,
...rest
}: {
starterPack: StarterPackViewBasic
} & Omit<LinkProps, 'to'>) {
onPress?: () => void
children: React.ReactNode
}) {
const {_} = useLingui()
const queryClient = useQueryClient()
const {record} = starterPack
const {rkey, handleOrDid} = React.useMemo(() => {
const rkey = new AtUri(starterPack.uri).rkey
@@ -104,14 +112,46 @@ export function Link({
}
return (
<InternalLink
label={record.name}
{...rest}
to={{
screen: 'StarterPack',
params: {name: handleOrDid, rkey},
<BaseLink
action="push"
to={`/starter-pack/${handleOrDid}/${rkey}`}
label={_(msg`Navigate to ${record.name}`)}
onPress={() => {
precacheResolvedUri(
queryClient,
starterPack.creator.handle,
starterPack.creator.did,
)
precacheStarterPack(queryClient, starterPack)
}}>
{children}
</InternalLink>
</BaseLink>
)
}
export function Embed({starterPack}: {starterPack: StarterPackViewBasic}) {
const t = useTheme()
const imageUri = getStarterPackOgCard(starterPack)
return (
<View
style={[
a.mt_xs,
a.border,
a.rounded_sm,
a.overflow_hidden,
t.atoms.border_contrast_low,
]}>
<Link starterPack={starterPack}>
<Image
source={imageUri}
style={[a.w_full, {aspectRatio: 1.91}]}
accessibilityIgnoresInvertColors={true}
/>
<View style={[a.px_sm, a.py_md]}>
<Card starterPack={starterPack} />
</View>
</Link>
</View>
)
}
@@ -58,6 +58,7 @@ export function WizardEditListDialog({
state.currentStep === 'Profiles' ? (
<WizardProfileCard
profile={item}
btnType="remove"
state={state}
dispatch={dispatch}
moderationOpts={moderationOpts}
@@ -65,6 +66,7 @@ export function WizardEditListDialog({
) : (
<WizardFeedCard
generator={item}
btnType="remove"
state={state}
dispatch={dispatch}
moderationOpts={moderationOpts}
@@ -9,7 +9,7 @@ import {
ModerationUI,
} from '@atproto/api'
import {GeneratorView} from '@atproto/api/dist/client/types/app/bsky/feed/defs'
import {msg} from '@lingui/macro'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {DISCOVER_FEED_URI} from 'lib/constants'
@@ -19,12 +19,14 @@ import {useSession} from 'state/session'
import {UserAvatar} from 'view/com/util/UserAvatar'
import {WizardAction, WizardState} from '#/screens/StarterPack/Wizard/State'
import {atoms as a, useTheme} from '#/alf'
import {Button, ButtonText} from '#/components/Button'
import * as Toggle from '#/components/forms/Toggle'
import {Checkbox} from '#/components/forms/Toggle'
import {Text} from '#/components/Typography'
function WizardListCard({
type,
btnType,
displayName,
subtitle,
onPress,
@@ -34,6 +36,7 @@ function WizardListCard({
moderationUi,
}: {
type: 'user' | 'algo'
btnType: 'checkbox' | 'remove'
profile?: AppBskyActorDefs.ProfileViewBasic
feed?: AppBskyFeedDefs.GeneratorView
displayName: string
@@ -56,7 +59,7 @@ function WizardListCard({
: _(msg`Add ${displayName} to starter pack`)
}
value={included}
disabled={disabled}
disabled={btnType === 'remove' || disabled}
onChange={onPress}
style={[
a.flex_row,
@@ -85,17 +88,33 @@ function WizardListCard({
{subtitle}
</Text>
</View>
<Checkbox />
{btnType === 'checkbox' ? (
<Checkbox />
) : !disabled ? (
<Button
label={_(msg`Remove`)}
variant="solid"
color="secondary"
size="xsmall"
style={[a.self_center, {marginLeft: 'auto'}]}
onPress={onPress}>
<ButtonText>
<Trans>Remove</Trans>
</ButtonText>
</Button>
) : null}
</Toggle.Item>
)
}
export function WizardProfileCard({
btnType,
state,
dispatch,
profile,
moderationOpts,
}: {
btnType: 'checkbox' | 'remove'
state: WizardState
dispatch: (action: WizardAction) => void
profile: AppBskyActorDefs.ProfileViewBasic
@@ -127,6 +146,7 @@ export function WizardProfileCard({
return (
<WizardListCard
type="user"
btnType={btnType}
displayName={displayName}
subtitle={`@${sanitizeHandle(profile.handle)}`}
onPress={onPress}
@@ -139,11 +159,13 @@ export function WizardProfileCard({
}
export function WizardFeedCard({
btnType,
generator,
state,
dispatch,
moderationOpts,
}: {
btnType: 'checkbox' | 'remove'
generator: GeneratorView
state: WizardState
dispatch: (action: WizardAction) => void
@@ -170,6 +192,7 @@ export function WizardFeedCard({
return (
<WizardListCard
type="algo"
btnType={btnType}
displayName={sanitizeDisplayName(generator.displayName)}
subtitle={`Feed by @${sanitizeHandle(generator.creator.handle)}`}
onPress={onPress}
@@ -17,7 +17,6 @@ import {HITSLOP_10} from '#/lib/constants'
import {makeListLink, makeProfileLink} from '#/lib/routes/links'
import {logger} from '#/logger'
import {isNative} from '#/platform/detection'
import {useModalControls} from '#/state/modals'
import {RQKEY_ROOT as POST_THREAD_RQKEY_ROOT} from '#/state/queries/post-thread'
import {
ThreadgateSetting,
@@ -33,7 +32,9 @@ import {CircleBanSign_Stroke2_Corner0_Rounded as CircleBanSign} from '#/componen
import {Earth_Stroke2_Corner0_Rounded as Earth} from '#/components/icons/Globe'
import {Group3_Stroke2_Corner0_Rounded as Group} from '#/components/icons/Group'
import {Text} from '#/components/Typography'
import {TextLink} from '../util/Link'
import {TextLink} from '../view/com/util/Link'
import {ThreadgateEditorDialog} from './dialogs/ThreadgateEditor'
import {PencilLine_Stroke2_Corner0_Rounded as PencilLine} from './icons/Pencil'
interface WhoCanReplyProps {
post: AppBskyFeedDefs.PostView
@@ -41,15 +42,19 @@ interface WhoCanReplyProps {
style?: StyleProp<ViewStyle>
}
export function WhoCanReplyInline({
post,
isThreadAuthor,
style,
}: WhoCanReplyProps) {
export function WhoCanReply({post, isThreadAuthor, style}: WhoCanReplyProps) {
const {_} = useLingui()
const t = useTheme()
const infoDialogControl = useDialogControl()
const {settings, isRootPost, onPressEdit} = useWhoCanReply(post)
const editDialogControl = useDialogControl()
const agent = useAgent()
const queryClient = useQueryClient()
const settings = React.useMemo(
() => threadgateViewToSettings(post.threadgate),
[post],
)
const isRootPost = !('reply' in post.record)
if (!isRootPost) {
return null
@@ -66,6 +71,55 @@ export function WhoCanReplyInline({
? _(msg`Replies disabled`)
: _(msg`Some people can reply`)
const onPressEdit = () => {
if (isNative && Keyboard.isVisible()) {
Keyboard.dismiss()
}
if (isThreadAuthor) {
editDialogControl.open()
} else {
infoDialogControl.open()
}
}
const onEditConfirm = async (newSettings: ThreadgateSetting[]) => {
if (JSON.stringify(settings) === JSON.stringify(newSettings)) {
return
}
try {
if (newSettings.length) {
await createThreadgate(agent, post.uri, newSettings)
} else {
await agent.api.com.atproto.repo.deleteRecord({
repo: agent.session!.did,
collection: 'app.bsky.feed.threadgate',
rkey: new AtUri(post.uri).rkey,
})
}
await whenAppViewReady(agent, post.uri, res => {
const thread = res.data.thread
if (AppBskyFeedDefs.isThreadViewPost(thread)) {
const fetchedSettings = threadgateViewToSettings(
thread.post.threadgate,
)
return JSON.stringify(fetchedSettings) === JSON.stringify(newSettings)
}
return false
})
Toast.show(_(msg`Thread settings updated`))
queryClient.invalidateQueries({
queryKey: [POST_THREAD_RQKEY_ROOT],
})
} catch (err) {
Toast.show(
_(
msg`There was an issue. Please check your internet connection and try again.`,
),
)
logger.error('Failed to edit threadgate', {message: err})
}
}
return (
<>
<Button
@@ -90,73 +144,24 @@ export function WhoCanReplyInline({
]}>
{description}
</Text>
{isThreadAuthor && (
<PencilLine width={12} fill={t.palette.primary_500} />
)}
</View>
)}
</Button>
<InfoDialog control={infoDialogControl} post={post} settings={settings} />
</>
)
}
export function WhoCanReplyBlock({
post,
isThreadAuthor,
style,
}: WhoCanReplyProps) {
const {_} = useLingui()
const t = useTheme()
const infoDialogControl = useDialogControl()
const {settings, isRootPost, onPressEdit} = useWhoCanReply(post)
if (!isRootPost) {
return null
}
if (!settings.length && !isThreadAuthor) {
return null
}
const isEverybody = settings.length === 0
const isNobody = !!settings.find(gate => gate.type === 'nobody')
const description = isEverybody
? _(msg`Everybody can reply`)
: isNobody
? _(msg`Replies on this thread are disabled`)
: _(msg`Some people can reply`)
return (
<>
<Button
label={
isThreadAuthor ? _(msg`Edit who can reply`) : _(msg`Who can reply`)
}
onPress={isThreadAuthor ? onPressEdit : infoDialogControl.open}
hitSlop={HITSLOP_10}>
{({hovered}) => (
<View
style={[
a.flex_1,
a.flex_row,
a.align_center,
a.py_sm,
a.pr_lg,
style,
]}>
<View style={[{paddingLeft: 25, paddingRight: 18}]}>
<Icon color={t.palette.contrast_300} settings={settings} />
</View>
<Text
style={[
a.text_sm,
a.leading_tight,
t.atoms.text_contrast_medium,
hovered && a.underline,
]}>
{description}
</Text>
</View>
)}
</Button>
<InfoDialog control={infoDialogControl} post={post} settings={settings} />
<WhoCanReplyDialog
control={infoDialogControl}
post={post}
settings={settings}
/>
{isThreadAuthor && (
<ThreadgateEditorDialog
control={editDialogControl}
threadgate={settings}
onConfirm={onEditConfirm}
/>
)}
</>
)
}
@@ -176,7 +181,7 @@ function Icon({
return <IconComponent fill={color} width={width} />
}
function InfoDialog({
function WhoCanReplyDialog({
control,
post,
settings,
@@ -188,12 +193,12 @@ function InfoDialog({
return (
<Dialog.Outer control={control}>
<Dialog.Handle />
<InfoDialogInner post={post} settings={settings} />
<WhoCanReplyDialogInner post={post} settings={settings} />
</Dialog.Outer>
)
}
function InfoDialogInner({
function WhoCanReplyDialogInner({
post,
settings,
}: {
@@ -315,64 +320,6 @@ function Separator({i, length}: {i: number; length: number}) {
return <>, </>
}
function useWhoCanReply(post: AppBskyFeedDefs.PostView) {
const agent = useAgent()
const queryClient = useQueryClient()
const {openModal} = useModalControls()
const settings = React.useMemo(
() => threadgateViewToSettings(post.threadgate),
[post],
)
const isRootPost = !('reply' in post.record)
const onPressEdit = () => {
if (isNative && Keyboard.isVisible()) {
Keyboard.dismiss()
}
openModal({
name: 'threadgate',
settings,
async onConfirm(newSettings: ThreadgateSetting[]) {
try {
if (newSettings.length) {
await createThreadgate(agent, post.uri, newSettings)
} else {
await agent.api.com.atproto.repo.deleteRecord({
repo: agent.session!.did,
collection: 'app.bsky.feed.threadgate',
rkey: new AtUri(post.uri).rkey,
})
}
await whenAppViewReady(agent, post.uri, res => {
const thread = res.data.thread
if (AppBskyFeedDefs.isThreadViewPost(thread)) {
const fetchedSettings = threadgateViewToSettings(
thread.post.threadgate,
)
return (
JSON.stringify(fetchedSettings) === JSON.stringify(newSettings)
)
}
return false
})
Toast.show('Thread settings updated')
queryClient.invalidateQueries({
queryKey: [POST_THREAD_RQKEY_ROOT],
})
} catch (err) {
Toast.show(
'There was an issue. Please check your internet connection and try again.',
)
logger.error('Failed to edit threadgate', {message: err})
}
},
})
}
return {settings, isRootPost, onPressEdit}
}
async function whenAppViewReady(
agent: BskyAgent,
uri: string,
+92
View File
@@ -0,0 +1,92 @@
import React from 'react'
import Animated, {
Easing,
useAnimatedProps,
useSharedValue,
withDelay,
withTiming,
} from 'react-native-reanimated'
import Svg, {Circle, Path} from 'react-native-svg'
import {Props, useCommonSVGProps} from '#/components/icons/common'
const AnimatedPath = Animated.createAnimatedComponent(Path)
const AnimatedCircle = Animated.createAnimatedComponent(Circle)
const PATH = 'M14.1 27.2l7.1 7.2 16.7-16.8'
export interface AnimatedCheckRef {
play(cb?: () => void): void
}
export interface AnimatedCheckProps extends Props {
playOnMount?: boolean
}
export const AnimatedCheck = React.forwardRef<
AnimatedCheckRef,
AnimatedCheckProps
>(function AnimatedCheck({playOnMount, ...props}, ref) {
const {fill, size, style, ...rest} = useCommonSVGProps(props)
const circleAnim = useSharedValue(0)
const checkAnim = useSharedValue(0)
const circleAnimatedProps = useAnimatedProps(() => ({
strokeDashoffset: 166 - circleAnim.value * 166,
}))
const checkAnimatedProps = useAnimatedProps(() => ({
strokeDashoffset: 48 - 48 * checkAnim.value,
}))
const play = React.useCallback(
(cb?: () => void) => {
circleAnim.value = 0
checkAnim.value = 0
circleAnim.value = withTiming(1, {duration: 500, easing: Easing.linear})
checkAnim.value = withDelay(
500,
withTiming(1, {duration: 300, easing: Easing.linear}, cb),
)
},
[circleAnim, checkAnim],
)
React.useImperativeHandle(ref, () => ({
play,
}))
React.useEffect(() => {
if (playOnMount) {
play()
}
}, [play, playOnMount])
return (
<Svg
fill="none"
{...rest}
viewBox="0 0 52 52"
width={size}
height={size}
style={style}>
<AnimatedCircle
animatedProps={circleAnimatedProps}
cx="26"
cy="26"
r="24"
fill="none"
stroke={fill}
strokeWidth={4}
strokeDasharray={166}
/>
<AnimatedPath
animatedProps={checkAnimatedProps}
stroke={fill}
d={PATH}
strokeWidth={4}
strokeDasharray={48}
/>
</Svg>
)
})
+1
View File
@@ -113,6 +113,7 @@ export function EmbedConsentDialog({
</ButtonText>
</Button>
</View>
<Dialog.Close />
</Dialog.ScrollableInner>
</Dialog.Outer>
)
+218
View File
@@ -0,0 +1,218 @@
import React from 'react'
import {StyleProp, View, ViewStyle} from 'react-native'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import isEqual from 'lodash.isequal'
import {useMyListsQuery} from '#/state/queries/my-lists'
import {ThreadgateSetting} from '#/state/queries/threadgate'
import {atoms as a, useTheme} from '#/alf'
import {Button, ButtonText} from '#/components/Button'
import * as Dialog from '#/components/Dialog'
import {Check_Stroke2_Corner0_Rounded as Check} from '#/components/icons/Check'
import {Text} from '#/components/Typography'
interface ThreadgateEditorDialogProps {
control: Dialog.DialogControlProps
threadgate: ThreadgateSetting[]
onChange?: (v: ThreadgateSetting[]) => void
onConfirm?: (v: ThreadgateSetting[]) => void
}
export function ThreadgateEditorDialog({
control,
threadgate,
onChange,
onConfirm,
}: ThreadgateEditorDialogProps) {
return (
<Dialog.Outer control={control}>
<Dialog.Handle />
<DialogContent
seedThreadgate={threadgate}
onChange={onChange}
onConfirm={onConfirm}
/>
</Dialog.Outer>
)
}
function DialogContent({
seedThreadgate,
onChange,
onConfirm,
}: {
seedThreadgate: ThreadgateSetting[]
onChange?: (v: ThreadgateSetting[]) => void
onConfirm?: (v: ThreadgateSetting[]) => void
}) {
const {_} = useLingui()
const control = Dialog.useDialogContext()
const {data: lists} = useMyListsQuery('curate')
const [draft, setDraft] = React.useState(seedThreadgate)
const [prevSeedThreadgate, setPrevSeedThreadgate] =
React.useState(seedThreadgate)
if (seedThreadgate !== prevSeedThreadgate) {
// New data flowed from above (e.g. due to update coming through).
setPrevSeedThreadgate(seedThreadgate)
setDraft(seedThreadgate) // Reset draft.
}
function updateThreadgate(nextThreadgate: ThreadgateSetting[]) {
setDraft(nextThreadgate)
onChange?.(nextThreadgate)
}
const onPressEverybody = () => {
updateThreadgate([])
}
const onPressNobody = () => {
updateThreadgate([{type: 'nobody'}])
}
const onPressAudience = (setting: ThreadgateSetting) => {
// remove nobody
let newSelected = draft.filter(v => v.type !== 'nobody')
// toggle
const i = newSelected.findIndex(v => isEqual(v, setting))
if (i === -1) {
newSelected.push(setting)
} else {
newSelected.splice(i, 1)
}
updateThreadgate(newSelected)
}
const doneLabel = onConfirm ? _(msg`Save`) : _(msg`Done`)
return (
<Dialog.ScrollableInner
label={_(msg`Choose who can reply`)}
style={[{maxWidth: 500}, a.w_full]}>
<View style={[a.flex_1, a.gap_md]}>
<Text style={[a.text_2xl, a.font_bold]}>
<Trans>Choose who can reply</Trans>
</Text>
<Text style={a.mt_xs}>
<Trans>Either choose "Everybody" or "Nobody"</Trans>
</Text>
<View style={[a.flex_row, a.gap_sm]}>
<Selectable
label={_(msg`Everybody`)}
isSelected={draft.length === 0}
onPress={onPressEverybody}
style={{flex: 1}}
/>
<Selectable
label={_(msg`Nobody`)}
isSelected={!!draft.find(v => v.type === 'nobody')}
onPress={onPressNobody}
style={{flex: 1}}
/>
</View>
<Text style={a.mt_md}>
<Trans>Or combine these options:</Trans>
</Text>
<View style={[a.gap_sm]}>
<Selectable
label={_(msg`Mentioned users`)}
isSelected={!!draft.find(v => v.type === 'mention')}
onPress={() => onPressAudience({type: 'mention'})}
/>
<Selectable
label={_(msg`Followed users`)}
isSelected={!!draft.find(v => v.type === 'following')}
onPress={() => onPressAudience({type: 'following'})}
/>
{lists && lists.length > 0
? lists.map(list => (
<Selectable
key={list.uri}
label={_(msg`Users in "${list.name}"`)}
isSelected={
!!draft.find(v => v.type === 'list' && v.list === list.uri)
}
onPress={() =>
onPressAudience({type: 'list', list: list.uri})
}
/>
))
: // No loading states to avoid jumps for the common case (no lists)
null}
</View>
</View>
<Button
label={doneLabel}
onPress={() => {
control.close()
onConfirm?.(draft)
}}
onAccessibilityEscape={control.close}
color="primary"
size="medium"
variant="solid"
style={a.mt_xl}>
<ButtonText>{doneLabel}</ButtonText>
</Button>
<Dialog.Close />
</Dialog.ScrollableInner>
)
}
function Selectable({
label,
isSelected,
onPress,
style,
}: {
label: string
isSelected: boolean
onPress: () => void
style?: StyleProp<ViewStyle>
}) {
const t = useTheme()
return (
<Button
onPress={onPress}
label={label}
accessibilityHint="Select this option"
accessibilityRole="checkbox"
aria-checked={isSelected}
accessibilityState={{
checked: isSelected,
}}
style={a.flex_1}>
{({hovered, focused}) => (
<View
style={[
a.flex_1,
a.flex_row,
a.align_center,
a.justify_between,
a.rounded_sm,
a.p_md,
{height: 40}, // for consistency with checkmark icon visible or not
t.atoms.bg_contrast_50,
(hovered || focused) && t.atoms.bg_contrast_100,
isSelected && {
backgroundColor:
t.name === 'light'
? t.palette.primary_50
: t.palette.primary_975,
},
style,
]}>
<Text style={[a.text_sm, isSelected && a.font_semibold]}>
{label}
</Text>
{isSelected ? (
<Check size="sm" fill={t.palette.primary_500} />
) : (
<View />
)}
</View>
)}
</Button>
)
}
+1 -1
View File
@@ -214,7 +214,7 @@ function HeaderReady({
]}>
<PostAlerts
modui={moderation.ui('contentList')}
size="large"
size="lg"
style={[a.pt_xs]}
/>
</View>
+4
View File
@@ -8,6 +8,10 @@ export const ArrowLeft_Stroke2_Corner0_Rounded = createSinglePathSVG({
path: 'M3 12a1 1 0 0 1 .293-.707l6-6a1 1 0 0 1 1.414 1.414L6.414 11H20a1 1 0 1 1 0 2H6.414l4.293 4.293a1 1 0 0 1-1.414 1.414l-6-6A1 1 0 0 1 3 12Z',
})
export const ArrowRight_Stroke2_Corner0_Rounded = createSinglePathSVG({
path: 'M21 12a1 1 0 0 1-.293.707l-6 6a1 1 0 0 1-1.414-1.414L17.586 13H4a1 1 0 1 1 0-2h13.586l-4.293-4.293a1 1 0 0 1 1.414-1.414l6 6A1 1 0 0 1 21 12Z',
})
export const ArrowBottom_Stroke2_Corner0_Rounded = createSinglePathSVG({
path: 'M12 21a1 1 0 0 1-.707-.293l-6-6a1 1 0 1 1 1.414-1.414L11 17.586V4a1 1 0 1 1 2 0v13.586l4.293-4.293a1 1 0 0 1 1.414 1.414l-6 6A1 1 0 0 1 12 21Z',
})
+5
View File
@@ -0,0 +1,5 @@
import {createSinglePathSVG} from './TEMPLATE'
export const VideoClip_Stroke2_Corner0_Rounded = createSinglePathSVG({
path: 'M3 4a1 1 0 0 1 1-1h16a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4Zm2 1v2h2V5H5Zm4 0v6h6V5H9Zm8 0v2h2V5h-2Zm2 4h-2v2h2V9Zm0 4h-2v2.444h2V13Zm0 4.444h-2V19h2v-1.556ZM15 19v-6H9v6h6Zm-8 0v-2H5v2h2Zm-2-4h2v-2H5v2Zm0-4h2V9H5v2Z',
})
+1 -3
View File
@@ -165,9 +165,7 @@ export function ContentHider({
}
const styles = StyleSheet.create({
outer: {
overflow: 'hidden',
},
outer: {},
cover: {
flexDirection: 'row',
alignItems: 'center',
+23 -98
View File
@@ -1,25 +1,17 @@
import React from 'react'
import {StyleProp, View, ViewStyle} from 'react-native'
import {BSKY_LABELER_DID, ModerationCause, ModerationUI} from '@atproto/api'
import {StyleProp, ViewStyle} from 'react-native'
import {ModerationUI} from '@atproto/api'
import {getModerationCauseKey} from '#/lib/moderation'
import {useModerationCauseDescription} from '#/lib/moderation/useModerationCauseDescription'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import {atoms as a, useTheme} from '#/alf'
import {Button} from '#/components/Button'
import {
ModerationDetailsDialog,
useModerationDetailsDialogControl,
} from '#/components/moderation/ModerationDetailsDialog'
import {Text} from '#/components/Typography'
import * as Pills from '#/components/Pills'
export function PostAlerts({
modui,
size,
size = 'sm',
style,
}: {
modui: ModerationUI
size?: 'medium' | 'large'
size?: Pills.CommonProps['size']
includeMute?: boolean
style?: StyleProp<ViewStyle>
}) {
@@ -28,90 +20,23 @@ export function PostAlerts({
}
return (
<View style={[a.flex_col, a.gap_xs, style]}>
<View style={[a.flex_row, a.flex_wrap, a.gap_xs]}>
{modui.alerts.map(cause => (
<PostLabel
key={getModerationCauseKey(cause)}
cause={cause}
size={size}
/>
))}
{modui.informs.map(cause => (
<PostLabel
key={getModerationCauseKey(cause)}
cause={cause}
size={size}
/>
))}
</View>
</View>
)
}
function PostLabel({
cause,
size,
}: {
cause: ModerationCause
size?: 'medium' | 'large'
}) {
const control = useModerationDetailsDialogControl()
const desc = useModerationCauseDescription(cause)
const t = useTheme()
return (
<>
<Button
label={desc.name}
onPress={e => {
e.preventDefault()
e.stopPropagation()
control.open()
}}>
{({hovered, pressed}) => (
<View
style={[
a.flex_row,
a.align_center,
a.gap_xs,
a.rounded_sm,
hovered || pressed
? size === 'large'
? t.atoms.bg_contrast_50
: t.atoms.bg_contrast_25
: size === 'large'
? t.atoms.bg_contrast_25
: undefined,
size === 'large'
? {paddingLeft: 4, paddingRight: 6, paddingVertical: 2}
: {paddingRight: 4, paddingVertical: 1},
]}>
{desc.sourceType === 'labeler' &&
desc.sourceDid !== BSKY_LABELER_DID ? (
<UserAvatar
avatar={desc.sourceAvi}
size={size === 'large' ? 16 : 12}
type="labeler"
shape="circle"
/>
) : (
<desc.icon size="sm" fill={t.atoms.text_contrast_medium.color} />
)}
<Text
style={[
a.text_left,
a.leading_snug,
size === 'large' ? {fontSize: 13} : a.text_xs,
size === 'large' ? t.atoms.text : t.atoms.text_contrast_high,
]}>
{desc.name}
</Text>
</View>
)}
</Button>
<ModerationDetailsDialog control={control} modcause={cause} />
</>
<Pills.Row size={size} style={[size === 'sm' && {marginLeft: -3}, style]}>
{modui.alerts.map(cause => (
<Pills.Label
key={getModerationCauseKey(cause)}
cause={cause}
size={size}
noBg={size === 'sm'}
/>
))}
{modui.informs.map(cause => (
<Pills.Label
key={getModerationCauseKey(cause)}
cause={cause}
size={size}
noBg={size === 'sm'}
/>
))}
</Pills.Row>
)
}
@@ -1,25 +1,12 @@
import React from 'react'
import {StyleProp, View, ViewStyle} from 'react-native'
import {
BSKY_LABELER_DID,
ModerationCause,
ModerationDecision,
} from '@atproto/api'
import {StyleProp, ViewStyle} from 'react-native'
import {ModerationDecision} from '@atproto/api'
import {useModerationCauseDescription} from '#/lib/moderation/useModerationCauseDescription'
import {getModerationCauseKey} from 'lib/moderation'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import {atoms as a, useTheme} from '#/alf'
import {Button} from '#/components/Button'
import {
ModerationDetailsDialog,
useModerationDetailsDialogControl,
} from '#/components/moderation/ModerationDetailsDialog'
import {Text} from '#/components/Typography'
import * as Pills from '#/components/Pills'
export function ProfileHeaderAlerts({
moderation,
style,
}: {
moderation: ModerationDecision
style?: StyleProp<ViewStyle>
@@ -30,73 +17,21 @@ export function ProfileHeaderAlerts({
}
return (
<View style={[a.flex_col, a.gap_xs, style]}>
<View style={[a.flex_row, a.flex_wrap, a.gap_xs]}>
{modui.alerts.map(cause => (
<ProfileLabel key={getModerationCauseKey(cause)} cause={cause} />
))}
{modui.informs.map(cause => (
<ProfileLabel key={getModerationCauseKey(cause)} cause={cause} />
))}
</View>
</View>
)
}
export function ProfileLabel({
cause,
disableDetailsDialog,
}: {
cause: ModerationCause
disableDetailsDialog?: boolean
}) {
const t = useTheme()
const control = useModerationDetailsDialogControl()
const desc = useModerationCauseDescription(cause)
return (
<>
<Button
disabled={disableDetailsDialog}
label={desc.name}
onPress={() => {
control.open()
}}>
{({hovered, pressed}) => (
<View
style={[
a.flex_row,
a.align_center,
{paddingLeft: 6, paddingRight: 8, paddingVertical: 4},
a.gap_xs,
a.rounded_md,
hovered || pressed
? t.atoms.bg_contrast_50
: t.atoms.bg_contrast_25,
]}>
{desc.sourceType === 'labeler' &&
desc.sourceDid !== BSKY_LABELER_DID ? (
<UserAvatar avatar={desc.sourceAvi} size={16} />
) : (
<desc.icon size="sm" fill={t.atoms.text_contrast_medium.color} />
)}
<Text
style={[
a.text_left,
a.leading_snug,
a.text_sm,
t.atoms.text_contrast_medium,
a.font_semibold,
]}>
{desc.name}
</Text>
</View>
)}
</Button>
{!disableDetailsDialog && (
<ModerationDetailsDialog control={control} modcause={cause} />
)}
</>
<Pills.Row size="lg">
{modui.alerts.map(cause => (
<Pills.Label
size="lg"
key={getModerationCauseKey(cause)}
cause={cause}
/>
))}
{modui.informs.map(cause => (
<Pills.Label
size="lg"
key={getModerationCauseKey(cause)}
cause={cause}
/>
))}
</Pills.Row>
)
}
+9
View File
@@ -13,6 +13,15 @@ export const EMBED_SERVICE = 'https://embed.bsky.app'
export const EMBED_SCRIPT = `${EMBED_SERVICE}/static/embed.js`
export const BSKY_DOWNLOAD_URL = 'https://bsky.app/download'
// HACK
// Yes, this is exactly what it looks like. It's a hard-coded constant
// reflecting the number of new users in the last week. We don't have
// time to add a route to the servers for this so we're just going to hard
// code and update this number with each release until we can get the
// server route done.
// -prf
export const JOINED_THIS_WEEK = 21797 // as of Jul5 2024
const BASE_FEEDBACK_FORM_URL = `${HELP_DESK_URL}/requests/new`
export function FEEDBACK_FORM_URL({
email,
+32 -1
View File
@@ -20,7 +20,9 @@ const openPermissionAlert = (perm: string) => {
}
export function usePhotoLibraryPermission() {
const [res, requestPermission] = MediaLibrary.usePermissions()
const [res, requestPermission] = MediaLibrary.usePermissions({
granularPermissions: ['photo'],
})
const requestPhotoAccessIfNeeded = async () => {
// On the, we use <input type="file"> to produce a filepicker
// This does not need any permission granting.
@@ -46,6 +48,35 @@ export function usePhotoLibraryPermission() {
return {requestPhotoAccessIfNeeded}
}
export function useVideoLibraryPermission() {
const [res, requestPermission] = MediaLibrary.usePermissions({
granularPermissions: ['video'],
})
const requestVideoAccessIfNeeded = async () => {
// On the, we use <input type="file"> to produce a filepicker
// This does not need any permission granting.
if (isWeb) {
return true
}
if (res?.granted) {
return true
} else if (!res || res.status === 'undetermined' || res?.canAskAgain) {
const {canAskAgain, granted, status} = await requestPermission()
if (!canAskAgain && status === 'undetermined') {
openPermissionAlert('video library')
}
return granted
} else {
openPermissionAlert('video library')
return false
}
}
return {requestVideoAccessIfNeeded}
}
export function useCameraPermission() {
const [res, requestPermission] = Camera.useCameraPermissions()
+8
View File
@@ -14,3 +14,11 @@ export function useCameraPermission() {
return {requestCameraAccessIfNeeded}
}
export function useVideoLibraryPermission() {
const requestVideoAccessIfNeeded = async () => {
return true
}
return {requestVideoAccessIfNeeded}
}
+46 -5
View File
@@ -1,11 +1,16 @@
import {AppBskyFeedPost, BskyAgent} from '@atproto/api'
import {AppBskyFeedPost, AppBskyGraphStarterpack, BskyAgent} from '@atproto/api'
import {useFetchDid} from '#/state/queries/handle'
import {useGetPost} from '#/state/queries/post'
import * as apilib from 'lib/api/index'
import {LikelyType, LinkMeta} from './link-meta'
import {
createStarterPackUri,
parseStarterPackUri,
} from 'lib/strings/starter-pack'
import {ComposerOptsQuote} from 'state/shell/composer'
// import {match as matchRoute} from 'view/routes'
import {convertBskyAppUrlIfNeeded, makeRecordUri} from '../strings/url-helpers'
import {ComposerOptsQuote} from 'state/shell/composer'
import {useGetPost} from '#/state/queries/post'
import {useFetchDid} from '#/state/queries/handle'
import {LikelyType, LinkMeta} from './link-meta'
// TODO
// import {Home} from 'view/screens/Home'
@@ -174,3 +179,39 @@ export async function getListAsEmbed(
},
}
}
export async function getStarterPackAsEmbed(
agent: BskyAgent,
fetchDid: ReturnType<typeof useFetchDid>,
url: string,
): Promise<apilib.ExternalEmbedDraft> {
const parsed = parseStarterPackUri(url)
if (!parsed) {
throw new Error(
'Unexepectedly called getStarterPackAsEmbed with a non-starterpack url',
)
}
const did = await fetchDid(parsed.name)
const starterPack = createStarterPackUri({did, rkey: parsed.rkey})
const res = await agent.app.bsky.graph.getStarterPack({starterPack})
const record = res.data.starterPack.record
return {
isLoading: false,
uri: starterPack,
meta: {
url: starterPack,
likelyType: LikelyType.AtpData,
// Validation here should never fail
title: AppBskyGraphStarterpack.isRecord(record)
? record.name
: 'Starter Pack',
},
embed: {
$type: 'app.bsky.embed.record',
record: {
uri: res.data.starterPack.uri,
cid: res.data.starterPack.cid,
},
},
}
}
+5 -3
View File
@@ -1,8 +1,10 @@
import {BskyAgent} from '@atproto/api'
import {isBskyAppUrl} from '../strings/url-helpers'
import {extractBskyMeta} from './bsky'
import {LINK_META_PROXY} from 'lib/constants'
import {getGiphyMetaUri} from 'lib/strings/embed-player'
import {parseStarterPackUri} from 'lib/strings/starter-pack'
import {isBskyAppUrl} from '../strings/url-helpers'
import {extractBskyMeta} from './bsky'
export enum LikelyType {
HTML,
@@ -28,7 +30,7 @@ export async function getLinkMeta(
url: string,
timeout = 15e3,
): Promise<LinkMeta> {
if (isBskyAppUrl(url)) {
if (isBskyAppUrl(url) && !parseStarterPackUri(url)) {
return extractBskyMeta(agent, url)
}
+27
View File
@@ -0,0 +1,27 @@
import {logger} from '#/logger'
export async function resolveShortLink(shortLink: string) {
const controller = new AbortController()
const to = setTimeout(() => controller.abort(), 2e3)
try {
const res = await fetch(shortLink, {
method: 'GET',
headers: {
Accept: 'application/json',
},
signal: controller.signal,
})
if (res.status !== 200) {
logger.error('Failed to resolve short link', {status: res.status})
return shortLink
}
const json = (await res.json()) as {url: string}
return json.url
} catch (e: unknown) {
logger.error('Failed to resolve short link', {safeMessage: e})
return shortLink
} finally {
clearTimeout(to)
}
}
+30
View File
@@ -0,0 +1,30 @@
import {getVideoMetaData, Video} from 'react-native-compressor'
export type CompressedVideo = {
uri: string
size: number
}
export async function compressVideo(
file: string,
opts?: {
getCancellationId?: (id: string) => void
onProgress?: (progress: number) => void
},
): Promise<CompressedVideo> {
const {onProgress, getCancellationId} = opts || {}
const compressed = await Video.compress(
file,
{
getCancellationId,
compressionMethod: 'manual',
bitrate: 3_000_000, // 3mbps
maxSize: 1920,
},
onProgress,
)
const info = await getVideoMetaData(compressed)
return {uri: compressed, size: info.size}
}
+28
View File
@@ -0,0 +1,28 @@
import {VideoTooLargeError} from 'lib/media/video/errors'
const MAX_VIDEO_SIZE = 1024 * 1024 * 100 // 100MB
export type CompressedVideo = {
uri: string
size: number
}
// doesn't actually compress, but throws if >100MB
export async function compressVideo(
file: string,
_callbacks?: {
onProgress: (progress: number) => void
},
): Promise<CompressedVideo> {
const blob = await fetch(file).then(res => res.blob())
const video = URL.createObjectURL(blob)
if (blob.size > MAX_VIDEO_SIZE) {
throw new VideoTooLargeError()
}
return {
size: blob.size,
uri: video,
}
}
+6
View File
@@ -0,0 +1,6 @@
export class VideoTooLargeError extends Error {
constructor() {
super('Videos cannot be larger than 100MB')
this.name = 'VideoTooLargeError'
}
}
+17
View File
@@ -0,0 +1,17 @@
import {AppBskyActorDefs} from '@atproto/api'
export function isBlockedOrBlocking(
profile:
| AppBskyActorDefs.ProfileViewBasic
| AppBskyActorDefs.ProfileViewDetailed,
) {
return profile.viewer?.blockedBy || profile.viewer?.blocking
}
export function isMuted(
profile:
| AppBskyActorDefs.ProfileViewBasic
| AppBskyActorDefs.ProfileViewDetailed,
) {
return profile.viewer?.muted || profile.viewer?.mutedByList
}
@@ -12,10 +12,6 @@ export function createSanitizedDisplayName(
if (profile.displayName != null && profile.displayName !== '') {
return sanitizeDisplayName(profile.displayName)
} else {
let sanitizedHandle = sanitizeHandle(profile.handle)
if (!noAt) {
sanitizedHandle = `@${sanitizedHandle}`
}
return sanitizedHandle
return sanitizeHandle(profile.handle, noAt ? '' : '@')
}
}
+2
View File
@@ -44,6 +44,7 @@ export type CommonNavigatorParams = {
Feeds: undefined
Start: {name: string; rkey: string}
StarterPack: {name: string; rkey: string; new?: boolean}
StarterPackShort: {code: string}
StarterPackWizard: undefined
StarterPackEdit: {
rkey?: string
@@ -101,6 +102,7 @@ export type AllNavigatorParams = CommonNavigatorParams & {
Messages: {animation?: 'push' | 'pop'}
Start: {name: string; rkey: string}
StarterPack: {name: string; rkey: string; new?: boolean}
StarterPackShort: {code: string}
StarterPackWizard: undefined
StarterPackEdit: {
rkey?: string
+17
View File
@@ -31,7 +31,13 @@ export type LogEvents = {
'splash:createAccountPressed': {}
'signup:nextPressed': {
activeStep: number
phoneVerificationRequired?: boolean
}
'signup:backPressed': {
activeStep: number
}
'signup:captchaSuccess': {}
'signup:captchaFailure': {}
'onboarding:interests:nextPressed': {
selectedInterests: string[]
selectedInterestsLength: number
@@ -147,6 +153,7 @@ export type LogEvents = {
| 'ProfileHoverCard'
| 'AvatarButton'
| 'StarterPackProfilesList'
| 'FeedInterstitial'
}
'profile:unfollow': {
logContext:
@@ -160,6 +167,7 @@ export type LogEvents = {
| 'Chat'
| 'AvatarButton'
| 'StarterPackProfilesList'
| 'FeedInterstitial'
}
'chat:create': {
logContext: 'ProfileHeader' | 'NewChatDialog' | 'SendViaChatDialog'
@@ -188,6 +196,15 @@ export type LogEvents = {
profilesCount: number
feedsCount: number
}
'starterPack:ctaPress': {
starterPack: string
}
'starterPack:opened': {
starterPack: string
}
'feed:interstitial:profileCard:press': {}
'feed:interstitial:feedCard:press': {}
'test:all:always': {}
'test:all:sometimes': {}
+7 -1
View File
@@ -2,7 +2,13 @@ export type Gate =
// Keep this alphabetic please.
| 'debug_show_feedcontext'
| 'native_pwi_disabled'
| 'new_user_guided_tour'
| 'new_user_progress_guide'
| 'onboarding_minimum_interests'
| 'request_notifications_permission_after_onboarding_v2'
| 'show_avi_follow_button'
| 'show_follow_back_label_v2'
| 'starter_packs_enabled'
| 'suggested_feeds_interstitial'
| 'suggested_follows_interstitial'
| 'ungroup_follow_backs'
| 'videos'
+10
View File
@@ -0,0 +1,10 @@
const LEFT_TO_RIGHT_EMBEDDING = '\u202A'
const POP_DIRECTIONAL_FORMATTING = '\u202C'
/*
* Force LTR directionality in a string.
* https://www.unicode.org/reports/tr9/#Directional_Formatting_Characters
*/
export function forceLTR(str: string) {
return LEFT_TO_RIGHT_EMBEDDING + str + POP_DIRECTIONAL_FORMATTING
}
+5 -1
View File
@@ -1,5 +1,7 @@
// Regex from the go implementation
// https://github.com/bluesky-social/indigo/blob/main/atproto/syntax/handle.go#L10
import {forceLTR} from 'lib/strings/bidi'
const VALIDATE_REGEX =
/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/
@@ -22,7 +24,9 @@ export function isInvalidHandle(handle: string): boolean {
}
export function sanitizeHandle(handle: string, prefix = ''): string {
return isInvalidHandle(handle) ? '⚠Invalid Handle' : `${prefix}${handle}`
return isInvalidHandle(handle)
? '⚠Invalid Handle'
: forceLTR(`${prefix}${handle}`)
}
export interface IsValidHandle {
+5 -1
View File
@@ -96,6 +96,10 @@ export function createStarterPackUri({
}: {
did: string
rkey: string
}): string | null {
}): string {
return new AtUri(`at://${did}/app.bsky.graph.starterpack/${rkey}`).toString()
}
export function startUriToStarterPackUri(uri: string) {
return uri.replace('/start/', '/starter-pack/')
}
+54
View File
@@ -2,8 +2,10 @@ import {AtUri} from '@atproto/api'
import psl from 'psl'
import TLDs from 'tlds'
import {logger} from '#/logger'
import {BSKY_SERVICE} from 'lib/constants'
import {isInvalidHandle} from 'lib/strings/handles'
import {startUriToStarterPackUri} from 'lib/strings/starter-pack'
export const BSKY_APP_HOST = 'https://bsky.app'
const BSKY_TRUSTED_HOSTS = [
@@ -151,6 +153,30 @@ export function isBskyListUrl(url: string): boolean {
return false
}
export function isBskyStartUrl(url: string): boolean {
if (isBskyAppUrl(url)) {
try {
const urlp = new URL(url)
return /start\/(?<name>[^/]+)\/(?<rkey>[^/]+)/i.test(urlp.pathname)
} catch {
console.error('Unexpected error in isBskyStartUrl()', url)
}
}
return false
}
export function isBskyStarterPackUrl(url: string): boolean {
if (isBskyAppUrl(url)) {
try {
const urlp = new URL(url)
return /starter-pack\/(?<name>[^/]+)\/(?<rkey>[^/]+)/i.test(urlp.pathname)
} catch {
console.error('Unexpected error in isBskyStartUrl()', url)
}
}
return false
}
export function isBskyDownloadUrl(url: string): boolean {
if (isExternalUrl(url)) {
return false
@@ -162,10 +188,18 @@ export function convertBskyAppUrlIfNeeded(url: string): string {
if (isBskyAppUrl(url)) {
try {
const urlp = new URL(url)
if (isBskyStartUrl(url)) {
return startUriToStarterPackUri(urlp.pathname)
}
return urlp.pathname
} catch (e) {
console.error('Unexpected error in convertBskyAppUrlIfNeeded()', e)
}
} else if (isShortLink(url)) {
// We only want to do this on native, web handles the 301 for us
return shortLinkToHref(url)
}
return url
}
@@ -285,3 +319,23 @@ export function createBskyAppAbsoluteUrl(path: string): string {
const sanitizedPath = path.replace(BSKY_APP_HOST, '').replace(/^\/+/, '')
return `${BSKY_APP_HOST.replace(/\/$/, '')}/${sanitizedPath}`
}
export function isShortLink(url: string): boolean {
return url.startsWith('https://go.bsky.app/')
}
export function shortLinkToHref(url: string): string {
try {
const urlp = new URL(url)
// For now we only support starter packs, but in the future we should add additional paths to this check
const parts = urlp.pathname.split('/').filter(Boolean)
if (parts.length === 1) {
return `/starter-pack-short/${parts[0]}`
}
return url
} catch (e) {
logger.error('Failed to parse possible short link', {safeMessage: e})
return url
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1
View File
@@ -44,5 +44,6 @@ export const router = new Router({
Start: '/start/:name/:rkey',
StarterPackEdit: '/starter-pack/edit/:rkey',
StarterPack: '/starter-pack/:name/:rkey',
StarterPackShort: '/starter-pack-short/:code',
StarterPackWizard: '/starter-pack/create',
})
+40 -20
View File
@@ -60,12 +60,13 @@ export const LoginForm = ({
const {track} = useAnalytics()
const t = useTheme()
const [isProcessing, setIsProcessing] = useState<boolean>(false)
const [isReady, setIsReady] = useState<boolean>(false)
const [isAuthFactorTokenNeeded, setIsAuthFactorTokenNeeded] =
useState<boolean>(false)
const [identifier, setIdentifier] = useState<string>(initialHandle)
const [password, setPassword] = useState<string>('')
const [authFactorToken, setAuthFactorToken] = useState<string>('')
const passwordInputRef = useRef<TextInput>(null)
const identifierValueRef = useRef<string>(initialHandle || '')
const passwordValueRef = useRef<string>('')
const authFactorTokenValueRef = useRef<string>('')
const passwordRef = useRef<TextInput>(null)
const {_} = useLingui()
const {login} = useSessionApi()
const requestNotificationsPermission = useRequestNotificationsPermission()
@@ -84,6 +85,10 @@ export const LoginForm = ({
setError('')
setIsProcessing(true)
const identifier = identifierValueRef.current.toLowerCase().trim()
const password = passwordValueRef.current
const authFactorToken = authFactorTokenValueRef.current
try {
// try to guess the handle if the user just gave their own username
let fullIdent = identifier
@@ -152,7 +157,22 @@ export const LoginForm = ({
}
}
const isReady = !!serviceDescription && !!identifier && !!password
const checkIsReady = () => {
if (
!!serviceDescription &&
!!identifierValueRef.current &&
!!passwordValueRef.current
) {
if (!isReady) {
setIsReady(true)
}
} else {
if (isReady) {
setIsReady(false)
}
}
}
return (
<FormContainer testID="loginForm" titleText={<Trans>Sign in</Trans>}>
<View>
@@ -181,14 +201,15 @@ export const LoginForm = ({
autoComplete="username"
returnKeyType="next"
textContentType="username"
defaultValue={initialHandle || ''}
onChangeText={v => {
identifierValueRef.current = v
checkIsReady()
}}
onSubmitEditing={() => {
passwordInputRef.current?.focus()
passwordRef.current?.focus()
}}
blurOnSubmit={false} // prevents flickering due to onSubmitEditing going to next field
value={identifier}
onChangeText={str =>
setIdentifier((str || '').toLowerCase().trim())
}
editable={!isProcessing}
accessibilityHint={_(
msg`Input the username or email address you used at signup`,
@@ -200,7 +221,7 @@ export const LoginForm = ({
<TextField.Icon icon={Lock} />
<TextField.Input
testID="loginPasswordInput"
inputRef={passwordInputRef}
inputRef={passwordRef}
label={_(msg`Password`)}
autoCapitalize="none"
autoCorrect={false}
@@ -210,16 +231,14 @@ export const LoginForm = ({
secureTextEntry={true}
textContentType="password"
clearButtonMode="while-editing"
value={password}
onChangeText={setPassword}
onChangeText={v => {
passwordValueRef.current = v
checkIsReady()
}}
onSubmitEditing={onPressNext}
blurOnSubmit={false} // HACK: https://github.com/facebook/react-native/issues/21911#issuecomment-558343069 Keyboard blur behavior is now handled in onSubmitEditing
editable={!isProcessing}
accessibilityHint={
identifier === ''
? _(msg`Input your password`)
: _(msg`Input the password tied to ${identifier}`)
}
accessibilityHint={_(msg`Input your password`)}
/>
<Button
testID="forgotPasswordButton"
@@ -258,8 +277,9 @@ export const LoginForm = ({
returnKeyType="done"
textContentType="username"
blurOnSubmit={false} // prevents flickering due to onSubmitEditing going to next field
value={authFactorToken}
onChangeText={setAuthFactorToken}
onChangeText={v => {
authFactorTokenValueRef.current = v
}}
onSubmitEditing={onPressNext}
editable={!isProcessing}
accessibilityHint={_(
+1 -1
View File
@@ -315,7 +315,7 @@ function ChatListItemReady({
<PostAlerts
modui={moderation.ui('contentList')}
size="large"
size="lg"
style={[a.pt_xs]}
/>
</View>
+25 -1
View File
@@ -1,5 +1,5 @@
import React from 'react'
import {View} from 'react-native'
import {Linking, View} from 'react-native'
import {useSafeAreaFrame} from 'react-native-safe-area-context'
import {ComAtprotoLabelDefs} from '@atproto/api'
import {LABELS} from '@atproto/api'
@@ -10,6 +10,7 @@ import {useFocusEffect} from '@react-navigation/native'
import {getLabelingServiceTitle} from '#/lib/moderation'
import {CommonNavigatorParams, NativeStackScreenProps} from '#/lib/routes/types'
import {logger} from '#/logger'
import {isIOS} from '#/platform/detection'
import {
useMyLabelersQuery,
usePreferencesQuery,
@@ -202,6 +203,8 @@ export function ModerationScreenInner({
[setAdultContentPref],
)
const disabledOnIOS = isIOS && !adultContentEnabled
return (
<ScrollView
contentContainerStyle={[
@@ -324,12 +327,14 @@ export function ModerationScreenInner({
a.flex_row,
a.align_center,
a.justify_between,
disabledOnIOS && {opacity: 0.5},
]}>
<Text style={[a.font_semibold, t.atoms.text_contrast_high]}>
<Trans>Enable adult content</Trans>
</Text>
<Toggle.Item
label={_(msg`Toggle to enable or disable adult content`)}
disabled={disabledOnIOS}
name="adultContent"
value={adultContentEnabled}
onChange={onToggleAdultContentEnabled}>
@@ -345,6 +350,25 @@ export function ModerationScreenInner({
</View>
</Toggle.Item>
</View>
{disabledOnIOS && (
<View style={[a.pb_lg, a.px_lg]}>
<Text>
<Trans>
Adult content can only be enabled via the Web at{' '}
<InlineLinkText
to=""
onPress={evt => {
evt.preventDefault()
Linking.openURL('https://bsky.app/')
return false
}}>
bsky.app
</InlineLinkText>
.
</Trans>
</Text>
</View>
)}
<Divider />
</>
)}
+10 -2
View File
@@ -19,6 +19,7 @@ import {preferencesQueryKey} from '#/state/queries/preferences'
import {RQKEY as profileRQKey} from '#/state/queries/profile'
import {useAgent} from '#/state/session'
import {useOnboardingDispatch} from '#/state/shell'
import {useProgressGuideControls} from '#/state/shell/progress-guide'
import {uploadBlob} from 'lib/api'
import {useRequestNotificationsPermission} from 'lib/notifications/notifications'
import {useSetHasCheckedForStarterPack} from 'state/preferences/used-starter-packs'
@@ -42,6 +43,7 @@ import {News2_Stroke2_Corner0_Rounded as News} from '#/components/icons/News2'
import {Trending2_Stroke2_Corner2_Rounded as Trending} from '#/components/icons/Trending2'
import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography'
import {TOURS, useSetQueuedTour} from '#/tours'
export function StepFinished() {
const {_} = useLingui()
@@ -56,6 +58,8 @@ export function StepFinished() {
const activeStarterPack = useActiveStarterPack()
const setActiveStarterPack = useSetActiveStarterPack()
const setHasCheckedForStarterPack = useSetHasCheckedForStarterPack()
const setQueuedTour = useSetQueuedTour()
const {startProgressGuide} = useProgressGuideControls()
const finishOnboarding = React.useCallback(async () => {
setSaving(true)
@@ -110,8 +114,8 @@ export function StepFinished() {
// Any starter pack feeds will be pinned _after_ the defaults
if (starterPack && starterPack.feeds?.length) {
feedsToSave.concat(
starterPack.feeds.map(f => ({
feedsToSave.push(
...starterPack.feeds.map(f => ({
type: 'feed',
value: f.uri,
pinned: true,
@@ -182,6 +186,8 @@ export function StepFinished() {
setSaving(false)
setActiveStarterPack(undefined)
setHasCheckedForStarterPack(true)
setQueuedTour(TOURS.HOME)
startProgressGuide('like-10-and-follow-7')
dispatch({type: 'finish'})
onboardDispatch({type: 'finish'})
track('OnboardingV2:StepFinished:End')
@@ -214,6 +220,8 @@ export function StepFinished() {
requestNotificationsPermission,
setActiveStarterPack,
setHasCheckedForStarterPack,
setQueuedTour,
startProgressGuide,
])
React.useEffect(() => {
@@ -1,16 +1,15 @@
import React from 'react'
import {View, ViewStyle, TextStyle} from 'react-native'
import {TextStyle, View, ViewStyle} from 'react-native'
import {useTheme, atoms as a, native} from '#/alf'
import {capitalize} from '#/lib/strings/capitalize'
import {useInterestsDisplayNames} from '#/screens/Onboarding/state'
import {atoms as a, native, useTheme} from '#/alf'
import * as Toggle from '#/components/forms/Toggle'
import {Text} from '#/components/Typography'
import {capitalize} from '#/lib/strings/capitalize'
import {Context} from '#/screens/Onboarding/state'
export function InterestButton({interest}: {interest: string}) {
const t = useTheme()
const {interestsDisplayNames} = React.useContext(Context)
const interestsDisplayNames = useInterestsDisplayNames()
const ctx = Toggle.useItemContext()
const styles = React.useMemo(() => {
+75 -4
View File
@@ -6,8 +6,10 @@ import {useQuery} from '@tanstack/react-query'
import {useAnalytics} from '#/lib/analytics/analytics'
import {logEvent} from '#/lib/statsig/statsig'
import {useGate} from '#/lib/statsig/statsig'
import {capitalize} from '#/lib/strings/capitalize'
import {logger} from '#/logger'
import {isWeb} from '#/platform/detection'
import {useAgent} from '#/state/session'
import {useOnboardingDispatch} from '#/state/shell'
import {
@@ -15,7 +17,11 @@ import {
OnboardingControls,
TitleText,
} from '#/screens/Onboarding/Layout'
import {ApiResponseMap, Context} from '#/screens/Onboarding/state'
import {
ApiResponseMap,
Context,
useInterestsDisplayNames,
} from '#/screens/Onboarding/state'
import {InterestButton} from '#/screens/Onboarding/StepInterests/InterestButton'
import {atoms as a, useBreakpoints, useTheme} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
@@ -23,18 +29,26 @@ import * as Toggle from '#/components/forms/Toggle'
import {IconCircle} from '#/components/IconCircle'
import {ArrowRotateCounterClockwise_Stroke2_Corner0_Rounded as ArrowRotateCounterClockwise} from '#/components/icons/ArrowRotateCounterClockwise'
import {ChevronRight_Stroke2_Corner0_Rounded as ChevronRight} from '#/components/icons/Chevron'
import {CircleInfo_Stroke2_Corner0_Rounded as CircleInfo} from '#/components/icons/CircleInfo'
import {EmojiSad_Stroke2_Corner0_Rounded as EmojiSad} from '#/components/icons/Emoji'
import {Hashtag_Stroke2_Corner0_Rounded as Hashtag} from '#/components/icons/Hashtag'
import {Loader} from '#/components/Loader'
import {Text} from '#/components/Typography'
const PROMPT_HEIGHT = isWeb ? 42 : 36
// matches the padding of the OnboardingControls.Portal
const PROMPT_OFFSET = isWeb ? a.pb_2xl.paddingBottom : a.pb_lg.paddingBottom
const MIN_INTERESTS = 3
export function StepInterests() {
const {_} = useLingui()
const t = useTheme()
const {gtMobile} = useBreakpoints()
const {track} = useAnalytics()
const gate = useGate()
const interestsDisplayNames = useInterestsDisplayNames()
const {state, dispatch, interestsDisplayNames} = React.useContext(Context)
const {state, dispatch} = React.useContext(Context)
const [saving, setSaving] = React.useState(false)
const [interests, setInterests] = React.useState<string[]>(
state.interestsStepResults.selectedInterests.map(i => i),
@@ -129,6 +143,11 @@ export function StepInterests() {
track('OnboardingV2:StepInterests:Start')
}, [track])
const isMinimumInterestsEnabled = gate('onboarding_minimum_interests')
const meetsMinimumRequirement = isMinimumInterestsEnabled
? interests.length >= MIN_INTERESTS
: true
const title = isError ? (
<Trans>Oh no! Something went wrong.</Trans>
) : (
@@ -166,8 +185,13 @@ export function StepInterests() {
<TitleText>{title}</TitleText>
<DescriptionText>{description}</DescriptionText>
{isMinimumInterestsEnabled && (
<DescriptionText style={[a.pt_sm]}>
<Trans>Choose 3 or more:</Trans>
</DescriptionText>
)}
<View style={[a.w_full, a.pt_2xl]}>
<View style={[a.w_full, isMinimumInterestsEnabled ? a.pt_md : a.pt_2xl]}>
{isLoading ? (
<Loader size="xl" />
) : isError || !data ? (
@@ -243,7 +267,7 @@ export function StepInterests() {
</View>
) : (
<Button
disabled={saving || !data}
disabled={saving || !data || !meetsMinimumRequirement}
variant="gradient"
color="gradient_sky"
size="large"
@@ -258,6 +282,53 @@ export function StepInterests() {
/>
</Button>
)}
{!meetsMinimumRequirement && (
<View
style={[
a.align_center,
a.absolute,
{
top: 0,
left: 0,
right: 0,
margin: 'auto',
transform: [
{
translateY:
-1 *
(PROMPT_OFFSET + PROMPT_HEIGHT + a.pb_lg.paddingBottom),
},
],
},
]}>
<View
style={[
a.flex_row,
a.align_center,
a.gap_sm,
a.rounded_full,
a.border,
t.atoms.bg_contrast_25,
t.atoms.border_contrast_medium,
{
height: PROMPT_HEIGHT,
...t.atoms.shadow_sm,
shadowOpacity: 0.1,
},
isWeb
? [a.py_md, a.px_lg, a.pr_xl]
: [a.py_sm, a.px_md, a.pr_lg],
]}>
<CircleInfo />
<Text>
<Trans>
Choose at least {MIN_INTERESTS - interests.length} more
</Trans>
</Text>
</View>
</View>
)}
</OnboardingControls.Portal>
</View>
)
+33 -27
View File
@@ -1,4 +1,6 @@
import React from 'react'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {logger} from '#/logger'
import {AvatarColor, Emoji} from '#/screens/Onboarding/StepProfile/types'
@@ -68,31 +70,37 @@ export type ApiResponseMap = {
}
}
export const INTEREST_TO_DISPLAY_NAME_DEFAULTS: {
[key: string]: string
} = {
news: 'News',
journalism: 'Journalism',
nature: 'Nature',
art: 'Art',
comics: 'Comics',
writers: 'Writers',
culture: 'Culture',
sports: 'Sports',
pets: 'Pets',
animals: 'Animals',
books: 'Books',
education: 'Education',
climate: 'Climate',
science: 'Science',
politics: 'Politics',
fitness: 'Fitness',
tech: 'Tech',
dev: 'Software Dev',
comedy: 'Comedy',
gaming: 'Video Games',
food: 'Food',
cooking: 'Cooking',
export function useInterestsDisplayNames() {
const {_} = useLingui()
return React.useMemo<Record<string, string>>(() => {
return {
// Keep this alphabetized
animals: _(msg`Animals`),
art: _(msg`Art`),
books: _(msg`Books`),
comedy: _(msg`Comedy`),
comics: _(msg`Comics`),
culture: _(msg`Culture`),
dev: _(msg`Software Dev`),
education: _(msg`Education`),
food: _(msg`Food`),
gaming: _(msg`Video Games`),
journalism: _(msg`Journalism`),
movies: _(msg`Movies`),
music: _(msg`Music`),
nature: _(msg`Nature`),
news: _(msg`News`),
pets: _(msg`Pets`),
photography: _(msg`Photography`),
politics: _(msg`Politics`),
science: _(msg`Science`),
sports: _(msg`Sports`),
tech: _(msg`Tech`),
tv: _(msg`TV`),
writers: _(msg`Writers`),
}
}, [_])
}
export const initialState: OnboardingState = {
@@ -120,11 +128,9 @@ export const initialState: OnboardingState = {
export const Context = React.createContext<{
state: OnboardingState
dispatch: React.Dispatch<OnboardingAction>
interestsDisplayNames: {[key: string]: string}
}>({
state: {...initialState},
dispatch: () => {},
interestsDisplayNames: INTEREST_TO_DISPLAY_NAME_DEFAULTS,
})
export function reducer(
+12
View File
@@ -3,6 +3,7 @@ import {
AppBskyGraphGetFollows,
BskyAgent,
} from '@atproto/api'
import {TID} from '@atproto/common-web'
import {until} from '#/lib/async/until'
@@ -20,9 +21,11 @@ export async function bulkWriteFollows(agent: BskyAgent, dids: string[]) {
createdAt: new Date().toISOString(),
}
})
const followWrites = followRecords.map(r => ({
$type: 'com.atproto.repo.applyWrites#create',
collection: 'app.bsky.graph.follow',
rkey: TID.nextStr(),
value: r,
}))
@@ -31,6 +34,15 @@ export async function bulkWriteFollows(agent: BskyAgent, dids: string[]) {
writes: followWrites,
})
await whenFollowsIndexed(agent, session.did, res => !!res.data.follows.length)
const followUris = new Map()
for (const r of followWrites) {
followUris.set(
r.value.subject,
`at://${session.did}/app.bsky.graph.follow/${r.rkey}`,
)
}
return followUris
}
async function whenFollowsIndexed(
+2 -2
View File
@@ -5,7 +5,7 @@ import {Trans} from '@lingui/macro'
import {Shadow} from '#/state/cache/types'
import {isInvalidHandle} from 'lib/strings/handles'
import {isAndroid} from 'platform/detection'
import {isIOS} from 'platform/detection'
import {atoms as a, useTheme, web} from '#/alf'
import {NewskieDialog} from '#/components/NewskieDialog'
import {Text} from '#/components/Typography'
@@ -23,7 +23,7 @@ export function ProfileHeaderHandle({
return (
<View
style={[a.flex_row, a.gap_xs, a.align_center]}
pointerEvents={disableTaps ? 'none' : isAndroid ? 'box-only' : 'auto'}>
pointerEvents={disableTaps ? 'none' : isIOS ? 'auto' : 'box-none'}>
<NewskieDialog profile={profile} disabled={disableTaps} />
{profile.viewer?.followedBy && !blockHide ? (
<View style={[t.atoms.bg_contrast_25, a.rounded_xs, a.px_sm, a.py_xs]}>
+73
View File
@@ -0,0 +1,73 @@
import React from 'react'
import {View} from 'react-native'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {atoms as a} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import {Loader} from '#/components/Loader'
export interface BackNextButtonsProps {
hideNext?: boolean
showRetry?: boolean
isLoading: boolean
isNextDisabled?: boolean
onBackPress: () => void
onNextPress?: () => void
onRetryPress?: () => void
}
export function BackNextButtons({
hideNext,
showRetry,
isLoading,
isNextDisabled,
onBackPress,
onNextPress,
onRetryPress,
}: BackNextButtonsProps) {
const {_} = useLingui()
return (
<View style={[a.flex_row, a.justify_between, a.pb_lg, a.pt_3xl]}>
<Button
label={_(msg`Go back to previous step`)}
variant="solid"
color="secondary"
size="medium"
onPress={onBackPress}>
<ButtonText>
<Trans>Back</Trans>
</ButtonText>
</Button>
{!hideNext &&
(showRetry ? (
<Button
label={_(msg`Press to retry`)}
variant="solid"
color="primary"
size="medium"
onPress={onRetryPress}>
<ButtonText>
<Trans>Retry</Trans>
</ButtonText>
{isLoading && <ButtonIcon icon={Loader} />}
</Button>
) : (
<Button
testID="nextBtn"
label={_(msg`Continue to next step`)}
variant="solid"
color="primary"
size="medium"
disabled={isLoading || isNextDisabled}
onPress={onNextPress}>
<ButtonText>
<Trans>Next</Trans>
</ButtonText>
{isLoading && <ButtonIcon icon={Loader} />}
</Button>
))}
</View>
)
}
+19
View File
@@ -6,11 +6,13 @@ import {nanoid} from 'nanoid/non-secure'
import {createFullHandle} from '#/lib/strings/handles'
import {logger} from '#/logger'
import {logEvent} from 'lib/statsig/statsig'
import {ScreenTransition} from '#/screens/Login/ScreenTransition'
import {useSignupContext, useSubmitSignup} from '#/screens/Signup/state'
import {CaptchaWebView} from '#/screens/Signup/StepCaptcha/CaptchaWebView'
import {atoms as a, useTheme} from '#/alf'
import {FormError} from '#/components/forms/FormError'
import {BackNextButtons} from '../BackNextButtons'
const CAPTCHA_PATH = '/gate/signup'
@@ -39,6 +41,7 @@ export function StepCaptcha() {
const onSuccess = React.useCallback(
(code: string) => {
setCompleted(true)
logEvent('signup:captchaSuccess', {})
submit(code)
},
[submit],
@@ -50,6 +53,7 @@ export function StepCaptcha() {
type: 'setError',
value: _(msg`Error receiving captcha response.`),
})
logEvent('signup:captchaFailure', {})
logger.error('Signup Flow Error', {
registrationHandle: state.handle,
error,
@@ -58,6 +62,16 @@ export function StepCaptcha() {
[_, dispatch, state.handle],
)
const onBackPress = React.useCallback(() => {
logger.error('Signup Flow Error', {
errorMessage:
'User went back from captcha step. Possibly encountered an error.',
registrationHandle: state.handle,
})
dispatch({type: 'prev'})
}, [dispatch, state.handle])
return (
<ScreenTransition>
<View style={[a.gap_lg]}>
@@ -83,6 +97,11 @@ export function StepCaptcha() {
</View>
<FormError error={state.error} />
</View>
<BackNextButtons
hideNext
isLoading={state.isLoading}
onBackPress={onBackPress}
/>
</ScreenTransition>
)
}
+138 -80
View File
@@ -1,56 +1,96 @@
import React from 'react'
import React, {useRef} from 'react'
import {View} from 'react-native'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useFocusEffect} from '@react-navigation/native'
import {
createFullHandle,
IsValidHandle,
validateHandle,
} from '#/lib/strings/handles'
import {logEvent} from '#/lib/statsig/statsig'
import {createFullHandle, validateHandle} from '#/lib/strings/handles'
import {useAgent} from '#/state/session'
import {ScreenTransition} from '#/screens/Login/ScreenTransition'
import {useSignupContext} from '#/screens/Signup/state'
import {useSignupContext, useSubmitSignup} from '#/screens/Signup/state'
import {atoms as a, useTheme} from '#/alf'
import * as TextField from '#/components/forms/TextField'
import {At_Stroke2_Corner0_Rounded as At} from '#/components/icons/At'
import {Check_Stroke2_Corner0_Rounded as Check} from '#/components/icons/Check'
import {TimesLarge_Stroke2_Corner0_Rounded as Times} from '#/components/icons/Times'
import {Text} from '#/components/Typography'
import {BackNextButtons} from './BackNextButtons'
export function StepHandle() {
const {_} = useLingui()
const t = useTheme()
const {state, dispatch} = useSignupContext()
const submit = useSubmitSignup({state, dispatch})
const agent = useAgent()
const handleValueRef = useRef<string>(state.handle)
const [draftValue, setDraftValue] = React.useState(state.handle)
const [validCheck, setValidCheck] = React.useState<IsValidHandle>({
handleChars: false,
hyphenStartOrEnd: false,
frontLength: false,
totalLength: true,
overall: false,
})
const onNextPress = React.useCallback(async () => {
const handle = handleValueRef.current.trim()
dispatch({
type: 'setHandle',
value: handle,
})
useFocusEffect(
React.useCallback(() => {
setValidCheck(validateHandle(state.handle, state.userDomain))
}, [state.handle, state.userDomain]),
)
const newValidCheck = validateHandle(handle, state.userDomain)
if (!newValidCheck.overall) {
return
}
const onHandleChange = React.useCallback(
(value: string) => {
if (state.error) {
dispatch({type: 'setError', value: ''})
}
try {
dispatch({type: 'setIsLoading', value: true})
dispatch({
type: 'setHandle',
value,
const res = await agent.resolveHandle({
handle: createFullHandle(handle, state.userDomain),
})
},
[dispatch, state.error],
)
if (res.data.did) {
dispatch({
type: 'setError',
value: _(msg`That handle is already taken.`),
})
return
}
} catch (e) {
// Don't have to handle
} finally {
dispatch({type: 'setIsLoading', value: false})
}
logEvent('signup:nextPressed', {
activeStep: state.activeStep,
phoneVerificationRequired:
state.serviceDescription?.phoneVerificationRequired,
})
// phoneVerificationRequired is actually whether a captcha is required
if (!state.serviceDescription?.phoneVerificationRequired) {
submit()
return
}
dispatch({type: 'next'})
}, [
_,
dispatch,
state.activeStep,
state.serviceDescription?.phoneVerificationRequired,
state.userDomain,
submit,
agent,
])
const onBackPress = React.useCallback(() => {
const handle = handleValueRef.current.trim()
dispatch({
type: 'setHandle',
value: handle,
})
dispatch({type: 'prev'})
logEvent('signup:backPressed', {
activeStep: state.activeStep,
})
}, [dispatch, state.activeStep])
const validCheck = validateHandle(draftValue, state.userDomain)
return (
<ScreenTransition>
<View style={[a.gap_lg]}>
@@ -59,9 +99,17 @@ export function StepHandle() {
<TextField.Icon icon={At} />
<TextField.Input
testID="handleInput"
onChangeText={onHandleChange}
onChangeText={val => {
if (state.error) {
dispatch({type: 'setError', value: ''})
}
// These need to always be in sync.
handleValueRef.current = val
setDraftValue(val)
}}
label={_(msg`Input your user handle`)}
defaultValue={state.handle}
defaultValue={draftValue}
autoCapitalize="none"
autoCorrect={false}
autoFocus
@@ -69,59 +117,69 @@ export function StepHandle() {
/>
</TextField.Root>
</View>
<Text style={[a.text_md]}>
<Trans>Your full handle will be</Trans>{' '}
<Text style={[a.text_md, a.font_bold]}>
@{createFullHandle(state.handle, state.userDomain)}
{draftValue !== '' && (
<Text style={[a.text_md]}>
<Trans>Your full handle will be</Trans>{' '}
<Text style={[a.text_md, a.font_bold]}>
@{createFullHandle(draftValue, state.userDomain)}
</Text>
</Text>
</Text>
)}
<View
style={[
a.w_full,
a.rounded_sm,
a.border,
a.p_md,
a.gap_sm,
t.atoms.border_contrast_low,
]}>
{state.error ? (
<View style={[a.w_full, a.flex_row, a.align_center, a.gap_sm]}>
<IsValidIcon valid={false} />
<Text style={[a.text_md, a.flex_1]}>{state.error}</Text>
</View>
) : undefined}
{validCheck.hyphenStartOrEnd ? (
<View style={[a.w_full, a.flex_row, a.align_center, a.gap_sm]}>
<IsValidIcon valid={validCheck.handleChars} />
<Text style={[a.text_md, a.flex_1]}>
<Trans>Only contains letters, numbers, and hyphens</Trans>
</Text>
</View>
) : (
<View style={[a.w_full, a.flex_row, a.align_center, a.gap_sm]}>
<IsValidIcon valid={validCheck.hyphenStartOrEnd} />
<Text style={[a.text_md, a.flex_1]}>
<Trans>Doesn't begin or end with a hyphen</Trans>
</Text>
</View>
)}
<View style={[a.w_full, a.flex_row, a.align_center, a.gap_sm]}>
<IsValidIcon
valid={validCheck.frontLength && validCheck.totalLength}
/>
{!validCheck.totalLength ? (
<Text style={[a.text_md, a.flex_1]}>
<Trans>No longer than 253 characters</Trans>
</Text>
{draftValue !== '' && (
<View
style={[
a.w_full,
a.rounded_sm,
a.border,
a.p_md,
a.gap_sm,
t.atoms.border_contrast_low,
]}>
{state.error ? (
<View style={[a.w_full, a.flex_row, a.align_center, a.gap_sm]}>
<IsValidIcon valid={false} />
<Text style={[a.text_md, a.flex_1]}>{state.error}</Text>
</View>
) : undefined}
{validCheck.hyphenStartOrEnd ? (
<View style={[a.w_full, a.flex_row, a.align_center, a.gap_sm]}>
<IsValidIcon valid={validCheck.handleChars} />
<Text style={[a.text_md, a.flex_1]}>
<Trans>Only contains letters, numbers, and hyphens</Trans>
</Text>
</View>
) : (
<Text style={[a.text_md, a.flex_1]}>
<Trans>At least 3 characters</Trans>
</Text>
<View style={[a.w_full, a.flex_row, a.align_center, a.gap_sm]}>
<IsValidIcon valid={validCheck.hyphenStartOrEnd} />
<Text style={[a.text_md, a.flex_1]}>
<Trans>Doesn't begin or end with a hyphen</Trans>
</Text>
</View>
)}
<View style={[a.w_full, a.flex_row, a.align_center, a.gap_sm]}>
<IsValidIcon
valid={validCheck.frontLength && validCheck.totalLength}
/>
{!validCheck.totalLength ? (
<Text style={[a.text_md, a.flex_1]}>
<Trans>No longer than 253 characters</Trans>
</Text>
) : (
<Text style={[a.text_md, a.flex_1]}>
<Trans>At least 3 characters</Trans>
</Text>
)}
</View>
</View>
</View>
)}
</View>
<BackNextButtons
isLoading={state.isLoading}
isNextDisabled={!validCheck.overall}
onBackPress={onBackPress}
onNextPress={onNextPress}
/>
</ScreenTransition>
)
}
+80 -15
View File
@@ -1,8 +1,10 @@
import React from 'react'
import React, {useRef} from 'react'
import {View} from 'react-native'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import * as EmailValidator from 'email-validator'
import {logEvent} from '#/lib/statsig/statsig'
import {logger} from '#/logger'
import {ScreenTransition} from '#/screens/Login/ScreenTransition'
import {is13, is18, useSignupContext} from '#/screens/Signup/state'
@@ -16,6 +18,7 @@ import {Envelope_Stroke2_Corner0_Rounded as Envelope} from '#/components/icons/E
import {Lock_Stroke2_Corner0_Rounded as Lock} from '#/components/icons/Lock'
import {Ticket_Stroke2_Corner0_Rounded as Ticket} from '#/components/icons/Ticket'
import {Loader} from '#/components/Loader'
import {BackNextButtons} from '../BackNextButtons'
function sanitizeDate(date: Date): Date {
if (!date || date.toString() === 'Invalid Date') {
@@ -27,10 +30,73 @@ function sanitizeDate(date: Date): Date {
return date
}
export function StepInfo() {
export function StepInfo({
onPressBack,
isServerError,
refetchServer,
isLoadingStarterPack,
}: {
onPressBack: () => void
isServerError: boolean
refetchServer: () => void
isLoadingStarterPack: boolean
}) {
const {_} = useLingui()
const {state, dispatch} = useSignupContext()
const inviteCodeValueRef = useRef<string>(state.inviteCode)
const emailValueRef = useRef<string>(state.email)
const passwordValueRef = useRef<string>(state.password)
const onNextPress = React.useCallback(async () => {
const inviteCode = inviteCodeValueRef.current
const email = emailValueRef.current
const password = passwordValueRef.current
if (!is13(state.dateOfBirth)) {
return
}
if (state.serviceDescription?.inviteCodeRequired && !inviteCode) {
return dispatch({
type: 'setError',
value: _(msg`Please enter your invite code.`),
})
}
if (!email) {
return dispatch({
type: 'setError',
value: _(msg`Please enter your email.`),
})
}
if (!EmailValidator.validate(email)) {
return dispatch({
type: 'setError',
value: _(msg`Your email appears to be invalid.`),
})
}
if (!password) {
return dispatch({
type: 'setError',
value: _(msg`Please choose your password.`),
})
}
dispatch({type: 'setInviteCode', value: inviteCode})
dispatch({type: 'setEmail', value: email})
dispatch({type: 'setPassword', value: password})
dispatch({type: 'next'})
logEvent('signup:nextPressed', {
activeStep: state.activeStep,
})
}, [
_,
dispatch,
state.activeStep,
state.dateOfBirth,
state.serviceDescription?.inviteCodeRequired,
])
return (
<ScreenTransition>
<View style={[a.gap_md]}>
@@ -46,7 +112,7 @@ export function StepInfo() {
}
/>
</View>
{state.isLoading ? (
{state.isLoading || isLoadingStarterPack ? (
<View style={[a.align_center]}>
<Loader size="xl" />
</View>
@@ -61,10 +127,7 @@ export function StepInfo() {
<TextField.Icon icon={Ticket} />
<TextField.Input
onChangeText={value => {
dispatch({
type: 'setInviteCode',
value: value.trim(),
})
inviteCodeValueRef.current = value.trim()
}}
label={_(msg`Required for this provider`)}
defaultValue={state.inviteCode}
@@ -84,10 +147,7 @@ export function StepInfo() {
<TextField.Input
testID="emailInput"
onChangeText={value => {
dispatch({
type: 'setEmail',
value: value.trim(),
})
emailValueRef.current = value.trim()
}}
label={_(msg`Enter your email address`)}
defaultValue={state.email}
@@ -106,10 +166,7 @@ export function StepInfo() {
<TextField.Input
testID="passwordInput"
onChangeText={value => {
dispatch({
type: 'setPassword',
value,
})
passwordValueRef.current = value
}}
label={_(msg`Choose your password`)}
defaultValue={state.password}
@@ -143,6 +200,14 @@ export function StepInfo() {
</>
) : undefined}
</View>
<BackNextButtons
hideNext={!is13(state.dateOfBirth)}
showRetry={isServerError}
isLoading={state.isLoading}
onBackPress={onPressBack}
onNextPress={onNextPress}
onRetryPress={refetchServer}
/>
</ScreenTransition>
)
}
+27 -132
View File
@@ -1,21 +1,13 @@
import React from 'react'
import {View} from 'react-native'
import Animated, {
FadeIn,
FadeOut,
LayoutAnimationConfig,
} from 'react-native-reanimated'
import Animated, {FadeIn, LayoutAnimationConfig} from 'react-native-reanimated'
import {AppBskyGraphStarterpack} from '@atproto/api'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useAnalytics} from '#/lib/analytics/analytics'
import {FEEDBACK_FORM_URL} from '#/lib/constants'
import {logEvent} from '#/lib/statsig/statsig'
import {createFullHandle} from '#/lib/strings/handles'
import {logger} from '#/logger'
import {useServiceQuery} from '#/state/queries/service'
import {useAgent} from '#/state/session'
import {useStarterPackQuery} from 'state/queries/starter-packs'
import {useActiveStarterPack} from 'state/shell/starter-pack'
import {LoggedOutLayout} from '#/view/com/util/layouts/LoggedOutLayout'
@@ -24,14 +16,12 @@ import {
reducer,
SignupContext,
SignupStep,
useSubmitSignup,
} from '#/screens/Signup/state'
import {StepCaptcha} from '#/screens/Signup/StepCaptcha'
import {StepHandle} from '#/screens/Signup/StepHandle'
import {StepInfo} from '#/screens/Signup/StepInfo'
import {atoms as a, useBreakpoints, useTheme} from '#/alf'
import {AppLanguageDropdown} from '#/components/AppLanguageDropdown'
import {Button, ButtonText} from '#/components/Button'
import {Divider} from '#/components/Divider'
import {LinearGradientBackground} from '#/components/LinearGradientBackground'
import {InlineLinkText} from '#/components/Link'
@@ -42,15 +32,21 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
const t = useTheme()
const {screen} = useAnalytics()
const [state, dispatch] = React.useReducer(reducer, initialState)
const submit = useSubmitSignup({state, dispatch})
const {gtMobile} = useBreakpoints()
const agent = useAgent()
const activeStarterPack = useActiveStarterPack()
const {data: starterPack} = useStarterPackQuery({
const {
data: starterPack,
isFetching: isFetchingStarterPack,
isError: isErrorStarterPack,
} = useStarterPackQuery({
uri: activeStarterPack?.uri,
})
const [isFetchedAtMount] = React.useState(starterPack != null)
const showStarterPackCard =
activeStarterPack?.uri && !isFetchingStarterPack && starterPack
const {
data: serviceInfo,
isFetching,
@@ -85,68 +81,6 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
}
}, [_, serviceInfo, isError])
const onNextPress = React.useCallback(async () => {
if (state.activeStep === SignupStep.HANDLE) {
try {
dispatch({type: 'setIsLoading', value: true})
const res = await agent.resolveHandle({
handle: createFullHandle(state.handle, state.userDomain),
})
if (res.data.did) {
dispatch({
type: 'setError',
value: _(msg`That handle is already taken.`),
})
return
}
} catch (e) {
// Don't have to handle
} finally {
dispatch({type: 'setIsLoading', value: false})
}
}
// phoneVerificationRequired is actually whether a captcha is required
if (
state.activeStep === SignupStep.HANDLE &&
!state.serviceDescription?.phoneVerificationRequired
) {
submit()
return
}
dispatch({type: 'next'})
logEvent('signup:nextPressed', {
activeStep: state.activeStep,
})
}, [
_,
state.activeStep,
state.handle,
state.serviceDescription?.phoneVerificationRequired,
state.userDomain,
submit,
agent,
])
const onBackPress = React.useCallback(() => {
if (state.activeStep !== SignupStep.INFO) {
if (state.activeStep === SignupStep.CAPTCHA) {
logger.error('Signup Flow Error', {
errorMessage:
'User went back from captcha step. Possibly encountered an error.',
registrationHandle: state.handle,
})
}
dispatch({type: 'prev'})
} else {
onPressBack()
}
}, [onPressBack, state.activeStep, state.handle])
return (
<SignupContext.Provider value={{state, dispatch}}>
<LoggedOutLayout
@@ -155,10 +89,9 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
description={_(msg`We're so excited to have you join us!`)}
scrollable>
<View testID="createAccount" style={a.flex_1}>
{state.activeStep === SignupStep.INFO &&
starterPack &&
{showStarterPackCard &&
AppBskyGraphStarterpack.isRecord(starterPack.record) ? (
<Animated.View entering={FadeIn} exiting={FadeOut}>
<Animated.View entering={!isFetchedAtMount ? FadeIn : undefined}>
<LinearGradientBackground
style={[a.mx_lg, a.p_lg, a.gap_sm, a.rounded_sm]}>
<Text style={[a.font_bold, a.text_xl, {color: 'white'}]}>
@@ -208,60 +141,22 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
</Text>
</View>
<View style={[a.pb_3xl]}>
<LayoutAnimationConfig skipEntering skipExiting>
{state.activeStep === SignupStep.INFO ? (
<StepInfo />
) : state.activeStep === SignupStep.HANDLE ? (
<StepHandle />
) : (
<StepCaptcha />
)}
</LayoutAnimationConfig>
</View>
<View style={[a.flex_row, a.justify_between, a.pb_lg]}>
<Button
label={_(msg`Go back to previous step`)}
variant="solid"
color="secondary"
size="medium"
onPress={onBackPress}>
<ButtonText>
<Trans>Back</Trans>
</ButtonText>
</Button>
{state.activeStep !== SignupStep.CAPTCHA && (
<>
{isError ? (
<Button
label={_(msg`Press to retry`)}
variant="solid"
color="primary"
size="medium"
disabled={state.isLoading}
onPress={() => refetch()}>
<ButtonText>
<Trans>Retry</Trans>
</ButtonText>
</Button>
) : (
<Button
testID="nextBtn"
label={_(msg`Continue to next step`)}
variant="solid"
color="primary"
size="medium"
disabled={!state.canNext || state.isLoading}
onPress={onNextPress}>
<ButtonText>
<Trans>Next</Trans>
</ButtonText>
</Button>
)}
</>
<LayoutAnimationConfig skipEntering skipExiting>
{state.activeStep === SignupStep.INFO ? (
<StepInfo
onPressBack={onPressBack}
isLoadingStarterPack={
isFetchingStarterPack && !isErrorStarterPack
}
isServerError={isError}
refetchServer={refetch}
/>
) : state.activeStep === SignupStep.HANDLE ? (
<StepHandle />
) : (
<StepCaptcha />
)}
</View>
</LayoutAnimationConfig>
<Divider />
+1 -25
View File
@@ -10,7 +10,7 @@ import * as EmailValidator from 'email-validator'
import {DEFAULT_SERVICE} from '#/lib/constants'
import {cleanError} from '#/lib/strings/errors'
import {createFullHandle, validateHandle} from '#/lib/strings/handles'
import {createFullHandle} from '#/lib/strings/handles'
import {getAge} from '#/lib/strings/time'
import {logger} from '#/logger'
import {useSessionApi} from '#/state/session'
@@ -28,7 +28,6 @@ export enum SignupStep {
export type SignupState = {
hasPrev: boolean
canNext: boolean
activeStep: SignupStep
serviceUrl: string
@@ -58,12 +57,10 @@ export type SignupAction =
| {type: 'setHandle'; value: string}
| {type: 'setVerificationCode'; value: string}
| {type: 'setError'; value: string}
| {type: 'setCanNext'; value: boolean}
| {type: 'setIsLoading'; value: boolean}
export const initialState: SignupState = {
hasPrev: false,
canNext: false,
activeStep: SignupStep.INFO,
serviceUrl: DEFAULT_SERVICE,
@@ -144,10 +141,6 @@ export function reducer(s: SignupState, a: SignupAction): SignupState {
next.handle = a.value
break
}
case 'setCanNext': {
next.canNext = a.value
break
}
case 'setIsLoading': {
next.isLoading = a.value
break
@@ -160,23 +153,6 @@ export function reducer(s: SignupState, a: SignupAction): SignupState {
next.hasPrev = next.activeStep !== SignupStep.INFO
switch (next.activeStep) {
case SignupStep.INFO: {
const isValidEmail = EmailValidator.validate(next.email)
next.canNext =
!!(next.email && next.password && next.dateOfBirth) &&
(!next.serviceDescription?.inviteCodeRequired || !!next.inviteCode) &&
is13(next.dateOfBirth) &&
isValidEmail
break
}
case SignupStep.HANDLE: {
next.canNext =
!!next.handle && validateHandle(next.handle, next.userDomain).overall
break
}
}
logger.debug('signup', next)
if (s.activeStep !== next.activeStep) {
@@ -11,8 +11,10 @@ import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {JOINED_THIS_WEEK} from '#/lib/constants'
import {isAndroidWeb} from 'lib/browser'
import {useWebMediaQueries} from 'lib/hooks/useWebMediaQueries'
import {logEvent} from 'lib/statsig/statsig'
import {createStarterPackGooglePlayUri} from 'lib/strings/starter-pack'
import {isWeb} from 'platform/detection'
import {useModerationOpts} from 'state/preferences/moderation-opts'
@@ -21,6 +23,7 @@ import {
useActiveStarterPack,
useSetActiveStarterPack,
} from 'state/shell/starter-pack'
import {formatCount} from '#/view/com/util/numeric/format'
import {LoggedOutScreenState} from 'view/com/auth/LoggedOut'
import {CenteredView} from 'view/com/util/Views'
import {Logo} from 'view/icons/Logo'
@@ -55,7 +58,11 @@ export function LandingScreen({
const moderationOpts = useModerationOpts()
const activeStarterPack = useActiveStarterPack()
const {data: starterPack, isError: isErrorStarterPack} = useStarterPackQuery({
const {
data: starterPack,
isError: isErrorStarterPack,
isFetching,
} = useStarterPackQuery({
uri: activeStarterPack?.uri,
})
@@ -71,7 +78,7 @@ export function LandingScreen({
}
}, [isErrorStarterPack, setScreenState, isValid, starterPack])
if (!starterPack || !isValid || !moderationOpts) {
if (isFetching || !starterPack || !isValid || !moderationOpts) {
return <ListMaybePlaceholder isLoading={true} />
}
@@ -95,7 +102,7 @@ function LandingScreenLoaded({
setScreenState: (state: LoggedOutScreenState) => void
moderationOpts: ModerationOpts
}) {
const {record, creator, listItemsSample, feeds, joinedWeekCount} = starterPack
const {record, creator, listItemsSample, feeds} = starterPack
const {_} = useLingui()
const t = useTheme()
const activeStarterPack = useActiveStarterPack()
@@ -109,9 +116,6 @@ function LandingScreenLoaded({
const listItemsCount = starterPack.list?.listItemCount ?? 0
const onContinue = () => {
setActiveStarterPack({
uri: starterPack.uri,
})
setScreenState(LoggedOutScreenState.S_CreateAccount)
}
@@ -126,6 +130,9 @@ function LandingScreenLoaded({
} else {
onContinue()
}
logEvent('starterPack:ctaPress', {
starterPack: starterPack.uri,
})
}
const onJoinWithoutPress = () => {
@@ -200,24 +207,22 @@ function LandingScreenLoaded({
<Trans>Join Bluesky</Trans>
</ButtonText>
</Button>
{joinedWeekCount && joinedWeekCount >= 25 ? (
<View style={[a.flex_row, a.align_center, a.gap_sm]}>
<FontAwesomeIcon
icon="arrow-trend-up"
size={12}
color={t.atoms.text_contrast_medium.color}
/>
<Text
style={[
a.font_semibold,
a.text_sm,
t.atoms.text_contrast_medium,
]}
numberOfLines={1}>
123,659 joined this week
</Text>
</View>
) : null}
<View style={[a.flex_row, a.align_center, a.gap_sm]}>
<FontAwesomeIcon
icon="arrow-trend-up"
size={12}
color={t.atoms.text_contrast_medium.color}
/>
<Text
style={[
a.font_semibold,
a.text_sm,
t.atoms.text_contrast_medium,
]}
numberOfLines={1}>
<Trans>{formatCount(JOINED_THIS_WEEK)} joined this week</Trans>
</Text>
</View>
</View>
<View style={[a.gap_3xl]}>
{Boolean(listItemsSample?.length) && (
@@ -231,22 +236,33 @@ function LandingScreenLoaded({
</Trans>
)}
</Text>
<View>
{starterPack.listItemsSample?.slice(0, 8).map(item => (
<View
key={item.subject.did}
style={[
a.py_lg,
a.px_md,
a.border_t,
t.atoms.border_contrast_low,
]}>
<ProfileCard
profile={item.subject}
moderationOpts={moderationOpts}
/>
</View>
))}
<View
style={
isTabletOrDesktop && [
a.border,
a.rounded_md,
t.atoms.border_contrast_low,
]
}>
{starterPack.listItemsSample
?.filter(p => !p.subject.associated?.labeler)
.slice(0, 8)
.map((item, i) => (
<View
key={item.subject.did}
style={[
a.py_lg,
a.px_md,
(!isTabletOrDesktop || i !== 0) && a.border_t,
t.atoms.border_contrast_low,
{pointerEvents: 'none'},
]}>
<ProfileCard
profile={item.subject}
moderationOpts={moderationOpts}
/>
</View>
))}
</View>
</View>
)}
@@ -256,17 +272,25 @@ function LandingScreenLoaded({
<Trans>You'll stay updated with these feeds</Trans>
</Text>
<View style={[{pointerEvents: 'none'}]}>
{feeds?.map(feed => (
<View
style={[
{pointerEvents: 'none'},
isTabletOrDesktop && [
a.border,
a.rounded_md,
t.atoms.border_contrast_low,
],
]}>
{feeds?.map((feed, i) => (
<View
style={[
a.py_lg,
a.px_md,
a.border_t,
(!isTabletOrDesktop || i !== 0) && a.border_t,
t.atoms.border_contrast_low,
]}
key={feed.uri}>
<FeedCard.Default type="feed" view={feed} />
<FeedCard.Default view={feed} />
</View>
))}
</View>
+187 -74
View File
@@ -3,37 +3,42 @@ import {View} from 'react-native'
import {Image} from 'expo-image'
import {
AppBskyGraphDefs,
AppBskyGraphGetList,
AppBskyGraphStarterpack,
AtUri,
ModerationOpts,
RichText as RichTextAPI,
} from '@atproto/api'
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useNavigation} from '@react-navigation/native'
import {NativeStackScreenProps} from '@react-navigation/native-stack'
import {
InfiniteData,
UseInfiniteQueryResult,
useQueryClient,
} from '@tanstack/react-query'
import {useQueryClient} from '@tanstack/react-query'
import {cleanError} from '#/lib/strings/errors'
import {logger} from '#/logger'
import {useDeleteStarterPackMutation} from '#/state/queries/starter-packs'
import {
ProgressGuideAction,
useProgressGuideControls,
} from '#/state/shell/progress-guide'
import {batchedUpdates} from 'lib/batchedUpdates'
import {HITSLOP_20} from 'lib/constants'
import {isBlockedOrBlocking, isMuted} from 'lib/moderation/blocked-and-muted'
import {makeProfileLink, makeStarterPackLink} from 'lib/routes/links'
import {CommonNavigatorParams, NavigationProp} from 'lib/routes/types'
import {logEvent} from 'lib/statsig/statsig'
import {getStarterPackOgCard} from 'lib/strings/starter-pack'
import {isWeb} from 'platform/detection'
import {updateProfileShadow} from 'state/cache/profile-shadow'
import {useModerationOpts} from 'state/preferences/moderation-opts'
import {RQKEY, useListMembersQuery} from 'state/queries/list-members'
import {useResolvedStarterPackShortLink} from 'state/queries/resolve-short-link'
import {useResolveDidQuery} from 'state/queries/resolve-uri'
import {useShortenLink} from 'state/queries/shorten-link'
import {useStarterPackQuery} from 'state/queries/starter-packs'
import {useAgent, useSession} from 'state/session'
import {useLoggedOutViewControls} from 'state/shell/logged-out'
import {useSetActiveStarterPack} from 'state/shell/starter-pack'
import * as Toast from '#/view/com/util/Toast'
import {PagerWithHeader} from 'view/com/pager/PagerWithHeader'
import {ProfileSubpageHeader} from 'view/com/profile/ProfileSubpageHeader'
@@ -52,7 +57,9 @@ import {Loader} from '#/components/Loader'
import * as Menu from '#/components/Menu'
import * as Prompt from '#/components/Prompt'
import {ReportDialog, useReportDialogControl} from '#/components/ReportDialog'
import {RichText} from '#/components/RichText'
import {FeedsList} from '#/components/StarterPack/Main/FeedsList'
import {PostsList} from '#/components/StarterPack/Main/PostsList'
import {ProfilesList} from '#/components/StarterPack/Main/ProfilesList'
import {QrCodeDialog} from '#/components/StarterPack/QrCodeDialog'
import {ShareDialog} from '#/components/StarterPack/ShareDialog'
@@ -62,12 +69,47 @@ type StarterPackScreeProps = NativeStackScreenProps<
CommonNavigatorParams,
'StarterPack'
>
type StarterPackScreenShortProps = NativeStackScreenProps<
CommonNavigatorParams,
'StarterPackShort'
>
export function StarterPackScreen({route}: StarterPackScreeProps) {
return <StarterPackScreenInner routeParams={route.params} />
}
export function StarterPackScreenShort({route}: StarterPackScreenShortProps) {
const {_} = useLingui()
const {
data: resolvedStarterPack,
isLoading,
isError,
} = useResolvedStarterPackShortLink({
code: route.params.code,
})
if (isLoading || isError || !resolvedStarterPack) {
return (
<ListMaybePlaceholder
isLoading={isLoading}
isError={isError}
errorMessage={_(msg`That starter pack could not be found.`)}
emptyMessage={_(msg`That starter pack could not be found.`)}
/>
)
}
return <StarterPackScreenInner routeParams={resolvedStarterPack} />
}
export function StarterPackScreenInner({
routeParams,
}: {
routeParams: StarterPackScreeProps['route']['params']
}) {
const {name, rkey} = routeParams
const {_} = useLingui()
const {currentAccount} = useSession()
const {name, rkey} = route.params
const moderationOpts = useModerationOpts()
const {
data: did,
@@ -79,7 +121,6 @@ export function StarterPackScreen({route}: StarterPackScreeProps) {
isLoading: isLoadingStarterPack,
isError: isErrorStarterPack,
} = useStarterPackQuery({did, rkey})
const listMembersQuery = useListMembersQuery(starterPack?.list?.uri, 50)
const isValid =
starterPack &&
@@ -90,12 +131,7 @@ export function StarterPackScreen({route}: StarterPackScreeProps) {
if (!did || !starterPack || !isValid || !moderationOpts) {
return (
<ListMaybePlaceholder
isLoading={
isLoadingDid ||
isLoadingStarterPack ||
listMembersQuery.isLoading ||
!moderationOpts
}
isLoading={isLoadingDid || isLoadingStarterPack || !moderationOpts}
isError={isErrorDid || isErrorStarterPack || !isValid}
errorMessage={_(msg`That starter pack could not be found.`)}
emptyMessage={_(msg`That starter pack could not be found.`)}
@@ -108,31 +144,32 @@ export function StarterPackScreen({route}: StarterPackScreeProps) {
}
return (
<StarterPackScreenInner
<StarterPackScreenLoaded
starterPack={starterPack}
routeParams={route.params}
listMembersQuery={listMembersQuery}
routeParams={routeParams}
moderationOpts={moderationOpts}
/>
)
}
function StarterPackScreenInner({
function StarterPackScreenLoaded({
starterPack,
routeParams,
listMembersQuery,
moderationOpts,
}: {
starterPack: AppBskyGraphDefs.StarterPackView
routeParams: StarterPackScreeProps['route']['params']
listMembersQuery: UseInfiniteQueryResult<
InfiniteData<AppBskyGraphGetList.OutputSchema>
>
moderationOpts: ModerationOpts
}) {
const showPeopleTab = Boolean(starterPack.list)
const showFeedsTab = Boolean(starterPack.feeds?.length)
const showPostsTab = Boolean(starterPack.list)
const {_} = useLingui()
const tabs = [
...(starterPack.list ? ['People'] : []),
...(starterPack.feeds?.length ? ['Feeds'] : []),
...(showPeopleTab ? [_(msg`People`)] : []),
...(showFeedsTab ? [_(msg`Feeds`)] : []),
...(showPostsTab ? [_(msg`Posts`)] : []),
]
const qrCodeDialogControl = useDialogControl()
@@ -142,6 +179,12 @@ function StarterPackScreenInner({
const [link, setLink] = React.useState<string>()
const [imageLoaded, setImageLoaded] = React.useState(false)
React.useEffect(() => {
logEvent('starterPack:opened', {
starterPack: starterPack.uri,
})
}, [starterPack.uri])
const onOpenShareDialog = React.useCallback(() => {
const rkey = new AtUri(starterPack.uri).rkey
shortenLink(makeStarterPackLink(starterPack.creator.did, rkey)).then(
@@ -178,24 +221,21 @@ function StarterPackScreenInner({
onOpenShareDialog={onOpenShareDialog}
/>
)}>
{starterPack.list != null
{showPeopleTab
? ({headerHeight, scrollElRef}) => (
<ProfilesList
key={0}
// Validated above
listUri={starterPack!.list!.uri}
headerHeight={headerHeight}
// @ts-expect-error
scrollElRef={scrollElRef}
listMembersQuery={listMembersQuery}
moderationOpts={moderationOpts}
/>
)
: null}
{starterPack.feeds != null
{showFeedsTab
? ({headerHeight, scrollElRef}) => (
<FeedsList
key={1}
// @ts-expect-error ?
feeds={starterPack?.feeds}
headerHeight={headerHeight}
@@ -204,6 +244,18 @@ function StarterPackScreenInner({
/>
)
: null}
{showPostsTab
? ({headerHeight, scrollElRef}) => (
<PostsList
// Validated above
listUri={starterPack!.list!.uri}
headerHeight={headerHeight}
// @ts-expect-error
scrollElRef={scrollElRef}
moderationOpts={moderationOpts}
/>
)
: null}
</PagerWithHeader>
</View>
@@ -234,9 +286,12 @@ function Header({
}) {
const {_} = useLingui()
const t = useTheme()
const {currentAccount} = useSession()
const {currentAccount, hasSession} = useSession()
const agent = useAgent()
const queryClient = useQueryClient()
const setActiveStarterPack = useSetActiveStarterPack()
const {requestSwitchToAccount} = useLoggedOutViewControls()
const {captureAction} = useProgressGuideControls()
const [isProcessing, setIsProcessing] = React.useState(false)
@@ -244,6 +299,29 @@ function Header({
const isOwn = creator?.did === currentAccount?.did
const joinedAllTimeCount = starterPack.joinedAllTimeCount ?? 0
const navigation = useNavigation<NavigationProp>()
React.useEffect(() => {
const onFocus = () => {
if (hasSession) return
setActiveStarterPack({
uri: starterPack.uri,
})
}
const onBeforeRemove = () => {
if (hasSession) return
setActiveStarterPack(undefined)
}
navigation.addListener('focus', onFocus)
navigation.addListener('beforeRemove', onBeforeRemove)
return () => {
navigation.removeListener('focus', onFocus)
navigation.removeListener('beforeRemove', onBeforeRemove)
}
}, [hasSession, navigation, setActiveStarterPack, starterPack.uri])
const onFollowAll = async () => {
if (!starterPack.list) return
@@ -254,13 +332,23 @@ function Header({
list: starterPack.list.uri,
})
const dids = list.data.items
.filter(li => !li.subject.viewer?.following)
.filter(
li =>
li.subject.did !== currentAccount?.did &&
!isBlockedOrBlocking(li.subject) &&
!isMuted(li.subject) &&
!li.subject.viewer?.following,
)
.map(li => li.subject.did)
await bulkWriteFollows(agent, dids)
const followUris = await bulkWriteFollows(agent, dids)
await queryClient.refetchQueries({
queryKey: RQKEY(starterPack.list.uri),
batchedUpdates(() => {
for (let did of dids) {
updateProfileShadow(queryClient, did, {
followingUri: followUris.get(did),
})
}
})
logEvent('starterPack:followAll', {
@@ -268,6 +356,7 @@ function Header({
starterPack: starterPack.uri,
count: dids.length,
})
captureAction(ProgressGuideAction.Follow, dids.length)
Toast.show(_(msg`All accounts have been followed!`))
} catch (e) {
Toast.show(_(msg`An error occurred while trying to follow all`))
@@ -280,6 +369,13 @@ function Header({
return null
}
const richText = record.description
? new RichTextAPI({
text: record.description,
facets: record.descriptionFacets,
})
: undefined
return (
<>
<ProfileSubpageHeader
@@ -290,46 +386,63 @@ function Header({
avatar={undefined}
creator={creator}
avatarType="starter-pack">
<View style={[a.flex_row, a.gap_sm, a.align_center]}>
{isOwn ? (
<Button
label={_(msg`Share this starter pack`)}
hitSlop={HITSLOP_20}
variant="solid"
color="primary"
size="small"
onPress={onOpenShareDialog}>
<ButtonText>
<Trans>Share</Trans>
</ButtonText>
</Button>
) : (
<Button
label={_(msg`Follow all`)}
variant="solid"
color="primary"
size="small"
disabled={isProcessing}
onPress={onFollowAll}>
<ButtonText>
<Trans>Follow all</Trans>
{isProcessing && <Loader size="xs" />}
</ButtonText>
</Button>
)}
<OverflowMenu
routeParams={routeParams}
starterPack={starterPack}
onOpenShareDialog={onOpenShareDialog}
/>
</View>
{hasSession ? (
<View style={[a.flex_row, a.gap_sm, a.align_center]}>
{isOwn ? (
<Button
label={_(msg`Share this starter pack`)}
hitSlop={HITSLOP_20}
variant="solid"
color="primary"
size="small"
onPress={onOpenShareDialog}>
<ButtonText>
<Trans>Share</Trans>
</ButtonText>
</Button>
) : (
<Button
label={_(msg`Follow all`)}
variant="solid"
color="primary"
size="small"
disabled={isProcessing}
onPress={onFollowAll}>
<ButtonText>
<Trans>Follow all</Trans>
{isProcessing && <Loader size="xs" />}
</ButtonText>
</Button>
)}
<OverflowMenu
routeParams={routeParams}
starterPack={starterPack}
onOpenShareDialog={onOpenShareDialog}
/>
</View>
) : null}
</ProfileSubpageHeader>
{record.description || joinedAllTimeCount >= 25 ? (
{!hasSession || richText || joinedAllTimeCount >= 25 ? (
<View style={[a.px_lg, a.pt_md, a.pb_sm, a.gap_md]}>
{record.description ? (
<Text style={[a.text_md, a.leading_snug]}>
{record.description}
</Text>
{richText ? (
<RichText value={richText} style={[a.text_md, a.leading_snug]} />
) : null}
{!hasSession ? (
<Button
label={_(msg`Join Bluesky`)}
onPress={() => {
setActiveStarterPack({
uri: starterPack.uri,
})
requestSwitchToAccount({requestedAccount: 'new'})
}}
variant="solid"
color="primary"
size="medium">
<ButtonText style={[a.text_lg]}>
<Trans>Join Bluesky</Trans>
</ButtonText>
</Button>
) : null}
{joinedAllTimeCount >= 25 ? (
<View style={[a.flex_row, a.align_center, a.gap_sm]}>
@@ -494,7 +607,7 @@ function OverflowMenu({
<Trans>Delete starter pack?</Trans>
</Prompt.TitleText>
<Prompt.DescriptionText>
<Trans>Are you sure you want delete this starter pack?</Trans>
<Trans>Are you sure you want to delete this starter pack?</Trans>
</Prompt.DescriptionText>
{deleteError && (
<View
+24 -9
View File
@@ -32,30 +32,45 @@ export function StepFeeds({moderationOpts}: {moderationOpts: ModerationOpts}) {
const throttledQuery = useThrottledValue(query, 500)
const {screenReaderEnabled} = useA11y()
const {data: savedFeedsAndLists} = useSavedFeeds()
const {data: savedFeedsAndLists, isFetchedAfterMount: isFetchedSavedFeeds} =
useSavedFeeds()
const savedFeeds = savedFeedsAndLists?.feeds
.filter(f => f.type === 'feed' && f.view.uri !== DISCOVER_FEED_URI)
.map(f => f.view) as AppBskyFeedDefs.GeneratorView[]
const {data: popularFeedsPages, fetchNextPage} = useGetPopularFeedsQuery({
const {
data: popularFeedsPages,
fetchNextPage,
isLoading: isLoadingPopularFeeds,
} = useGetPopularFeedsQuery({
limit: 30,
})
const popularFeeds =
popularFeedsPages?.pages
.flatMap(page => page.feeds)
.filter(f => !savedFeeds?.some(sf => sf?.uri === f.uri)) ?? []
const popularFeeds = popularFeedsPages?.pages.flatMap(p => p.feeds) ?? []
const suggestedFeeds = savedFeeds?.concat(popularFeeds)
// If we have saved feeds already loaded, display them immediately
// Then, when popular feeds have loaded we can concat them to the saved feeds
const suggestedFeeds =
savedFeeds || isFetchedSavedFeeds
? popularFeeds
? savedFeeds.concat(
popularFeeds.filter(f => !savedFeeds.some(sf => sf.uri === f.uri)),
)
: savedFeeds
: undefined
const {data: searchedFeeds, isLoading: isLoadingSearch} =
const {data: searchedFeeds, isFetching: isFetchingSearchedFeeds} =
useSearchPopularFeedsQuery({q: throttledQuery})
const isLoading =
!isFetchedSavedFeeds || isLoadingPopularFeeds || isFetchingSearchedFeeds
const renderItem = ({
item,
}: ListRenderItemInfo<AppBskyFeedDefs.GeneratorView>) => {
return (
<WizardFeedCard
generator={item}
btnType="checkbox"
state={state}
dispatch={dispatch}
moderationOpts={moderationOpts}
@@ -91,7 +106,7 @@ export function StepFeeds({moderationOpts}: {moderationOpts: ModerationOpts}) {
style={{flex: 1}}
ListEmptyComponent={
<View style={[a.flex_1, a.align_center, a.mt_lg, a.px_lg]}>
{isLoadingSearch ? (
{isLoading ? (
<Loader size="lg" />
) : (
<Text
@@ -31,13 +31,22 @@ export function StepProfiles({
const [query, setQuery] = useState('')
const {screenReaderEnabled} = useA11y()
const {data: topPages, fetchNextPage} = useActorSearchPaginated({
const {
data: topPages,
fetchNextPage,
isLoading: isLoadingTopPages,
} = useActorSearchPaginated({
query: encodeURIComponent('*'),
})
const topFollowers = topPages?.pages.flatMap(p => p.actors)
const topFollowers = topPages?.pages
.flatMap(p => p.actors)
.filter(p => !p.associated?.labeler)
const {data: results, isLoading: isLoadingResults} =
const {data: resultsUnfiltered, isFetching: isFetchingResults} =
useActorAutocompleteQuery(query, true, 12)
const results = resultsUnfiltered?.filter(p => !p.associated?.labeler)
const isLoading = isLoadingTopPages || isFetchingResults
const renderItem = ({
item,
@@ -45,6 +54,7 @@ export function StepProfiles({
return (
<WizardProfileCard
profile={item}
btnType="checkbox"
state={state}
dispatch={dispatch}
moderationOpts={moderationOpts}
@@ -79,7 +89,7 @@ export function StepProfiles({
onEndReachedThreshold={isNative ? 2 : 0.25}
ListEmptyComponent={
<View style={[a.flex_1, a.align_center, a.mt_lg, a.px_lg]}>
{isLoadingResults ? (
{isLoading ? (
<Loader size="lg" />
) : (
<Text
+98 -69
View File
@@ -21,6 +21,7 @@ import {NativeStackScreenProps} from '@react-navigation/native-stack'
import {logger} from '#/logger'
import {HITSLOP_10} from 'lib/constants'
import {createSanitizedDisplayName} from 'lib/moderation/create-sanitized-display-name'
import {CommonNavigatorParams, NavigationProp} from 'lib/routes/types'
import {logEvent} from 'lib/statsig/statsig'
import {sanitizeDisplayName} from 'lib/strings/display-names'
@@ -170,15 +171,7 @@ function WizardInner({
)
const getDefaultName = () => {
let displayName
if (
currentProfile?.displayName != null &&
currentProfile?.displayName !== ''
) {
displayName = sanitizeDisplayName(currentProfile.displayName)
} else {
displayName = sanitizeHandle(currentProfile!.handle)
}
const displayName = createSanitizedDisplayName(currentProfile!, true)
return _(msg`${displayName}'s Starter Pack`).slice(0, 50)
}
@@ -191,16 +184,12 @@ function WizardInner({
nextBtn: _(msg`Next`),
},
Profiles: {
header: _(msg`People`),
header: _(msg`Choose People`),
nextBtn: _(msg`Next`),
subtitle: _(
msg`Add people to your starter pack that you think others will enjoy following`,
),
},
Feeds: {
header: _(msg`Feeds`),
header: _(msg`Choose Feeds`),
nextBtn: state.feeds.length === 0 ? _(msg`Skip`) : _(msg`Finish`),
subtitle: _(msg`Some subtitle`),
},
}
const currUiStrings = wizardUiStrings[state.currentStep]
@@ -254,9 +243,8 @@ function WizardInner({
dispatch({type: 'SetProcessing', processing: true})
if (currentStarterPack && currentListItems) {
editStarterPack({
name: state.name ?? getDefaultName(),
description: state.description,
descriptionFacets: [],
name: state.name?.trim() || getDefaultName(),
description: state.description?.trim(),
profiles: state.profiles,
feeds: state.feeds,
currentStarterPack: currentStarterPack,
@@ -264,9 +252,8 @@ function WizardInner({
})
} else {
createStarterPack({
name: state.name ?? getDefaultName(),
description: state.description,
descriptionFacets: [],
name: state.name?.trim() || getDefaultName(),
description: state.description?.trim(),
profiles: state.profiles,
feeds: state.feeds,
})
@@ -406,7 +393,6 @@ function Footer({
state.currentStep === 'Profiles'
? [profile, ...state.profiles]
: state.feeds
const initialNamesIndex = state.currentStep === 'Profiles' ? 1 : 0
const isEditEnabled =
(state.currentStep === 'Profiles' && items.length > 1) ||
@@ -458,56 +444,99 @@ function Footer({
))}
</View>
{items.length === 0 ? (
<View style={[a.gap_sm]}>
<Text style={[a.font_bold, a.text_center, textStyles]}>
<Trans>Add some feeds to your starter pack!</Trans>
</Text>
{
state.currentStep === 'Profiles' ? (
<Text style={[a.text_center, textStyles]}>
<Trans>Search for feeds that you want to suggest to others.</Trans>
{
items.length < 2 ? (
<Trans>
It's just you right now! Add more people to your starter pack
by searching above.
</Trans>
) : items.length === 2 ? (
<Trans>
<Text style={[a.font_bold, textStyles]}>You</Text> and
<Text> </Text>
<Text style={[a.font_bold, textStyles]}>
{getName(items[1] /* [0] is self, skip it */)}{' '}
</Text>
are included in your starter pack
</Trans>
) : items.length > 2 ? (
<Trans context="profiles">
<Text style={[a.font_bold, textStyles]}>
{getName(items[1] /* [0] is self, skip it */)},{' '}
</Text>
<Text style={[a.font_bold, textStyles]}>
{getName(items[2])},{' '}
</Text>
and{' '}
<Plural
value={items.length - 2}
one="# other"
other="# others"
/>{' '}
are included in your starter pack
</Trans>
) : null /* Should not happen. */
}
</Text>
</View>
) : (
<Text style={[a.text_center, textStyles]}>
{state.currentStep === 'Profiles' && items.length === 1 ? (
<Trans>
It's just you right now! Add more people to your starter pack by
searching above.
</Trans>
) : items.length === 1 ? (
<Trans>
<Text style={[a.font_bold, textStyles]}>
{getName(items[initialNamesIndex])}
</Text>{' '}
is included in your starter pack
</Trans>
) : items.length === 2 ? (
<Trans>
<Text style={[a.font_bold, textStyles]}>
{getName(items[initialNamesIndex])}{' '}
) : state.currentStep === 'Feeds' ? (
items.length === 0 ? (
<View style={[a.gap_sm]}>
<Text style={[a.font_bold, a.text_center, textStyles]}>
<Trans>Add some feeds to your starter pack!</Trans>
</Text>
and
<Text> </Text>
<Text style={[a.font_bold, textStyles]}>
{getName(items[state.currentStep === 'Profiles' ? 0 : 1])}{' '}
<Text style={[a.text_center, textStyles]}>
<Trans>
Search for feeds that you want to suggest to others.
</Trans>
</Text>
are included in your starter pack
</Trans>
</View>
) : (
<Trans>
<Text style={[a.font_bold, textStyles]}>
{getName(items[initialNamesIndex])},{' '}
</Text>
<Text style={[a.font_bold, textStyles]}>
{getName(items[initialNamesIndex + 1])},{' '}
</Text>
and {items.length - 2}{' '}
<Plural value={items.length - 2} one="other" other="others" /> are
included in your starter pack
</Trans>
)}
</Text>
)}
<Text style={[a.text_center, textStyles]}>
{
items.length === 1 ? (
<Trans>
<Text style={[a.font_bold, textStyles]}>
{getName(items[0])}
</Text>{' '}
is included in your starter pack
</Trans>
) : items.length === 2 ? (
<Trans>
<Text style={[a.font_bold, textStyles]}>
{getName(items[0])}
</Text>{' '}
and
<Text> </Text>
<Text style={[a.font_bold, textStyles]}>
{getName(items[1])}{' '}
</Text>
are included in your starter pack
</Trans>
) : items.length > 2 ? (
<Trans context="feeds">
<Text style={[a.font_bold, textStyles]}>
{getName(items[0])},{' '}
</Text>
<Text style={[a.font_bold, textStyles]}>
{getName(items[1])},{' '}
</Text>
and{' '}
<Plural
value={items.length - 2}
one="# other"
other="# others"
/>{' '}
are included in your starter pack
</Trans>
) : null /* Should not happen. */
}
</Text>
)
) : null /* Should not happen. */
}
<View
style={[
@@ -567,9 +596,9 @@ function Footer({
function getName(item: AppBskyActorDefs.ProfileViewBasic | GeneratorView) {
if (typeof item.displayName === 'string') {
return enforceLen(sanitizeDisplayName(item.displayName), 16, true)
return enforceLen(sanitizeDisplayName(item.displayName), 28, true)
} else if (typeof item.handle === 'string') {
return enforceLen(sanitizeHandle(item.handle), 16, true)
return enforceLen(sanitizeHandle(item.handle), 28, true)
}
return ''
}
+5 -7
View File
@@ -6,11 +6,8 @@ import throttle from 'lodash.throttle'
import {PROD_DEFAULT_FEED} from '#/lib/constants'
import {logEvent} from '#/lib/statsig/statsig'
import {logger} from '#/logger'
import {
FeedDescriptor,
FeedPostSliceItem,
isFeedPostSlice,
} from '#/state/queries/post-feed'
import {FeedDescriptor, FeedPostSliceItem} from '#/state/queries/post-feed'
import {getFeedPostSlice} from '#/view/com/posts/Feed'
import {useAgent} from './session'
type StateContext = {
@@ -93,11 +90,12 @@ export function useFeedFeedback(feed: FeedDescriptor, hasSession: boolean) {
}, [enabled, sendToFeed])
const onItemSeen = React.useCallback(
(slice: any) => {
(feedItem: any) => {
if (!enabled) {
return
}
if (!isFeedPostSlice(slice)) {
const slice = getFeedPostSlice(feedItem)
if (slice === null) {
return
}
for (const postItem of slice.items) {
-9
View File
@@ -5,7 +5,6 @@ import {AppBskyActorDefs, AppBskyGraphDefs} from '@atproto/api'
import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback'
import {GalleryModel} from '#/state/models/media/gallery'
import {ImageModel} from '#/state/models/media/image'
import {ThreadgateSetting} from '../queries/threadgate'
export interface EditProfileModal {
name: 'edit-profile'
@@ -67,13 +66,6 @@ export interface SelfLabelModal {
onChange: (labels: string[]) => void
}
export interface ThreadgateModal {
name: 'threadgate'
settings: ThreadgateSetting[]
onChange?: (settings: ThreadgateSetting[]) => void
onConfirm?: (settings: ThreadgateSetting[]) => void
}
export interface ChangeHandleModal {
name: 'change-handle'
onChanged: () => void
@@ -149,7 +141,6 @@ export type Modal =
| CropImageModal
| EditImageModal
| SelfLabelModal
| ThreadgateModal
// Bluesky access
| WaitlistModal
+34 -3
View File
@@ -12,6 +12,12 @@ export function useFeedTuners(feedDesc: FeedDescriptor) {
const {currentAccount} = useSession()
return useMemo(() => {
if (feedDesc.startsWith('author')) {
if (feedDesc.endsWith('|posts_with_replies')) {
// TODO: Do this on the server instead.
return [FeedTuner.removeReposts]
}
}
if (feedDesc.startsWith('feedgen')) {
return [
FeedTuner.dedupReposts,
@@ -19,7 +25,34 @@ export function useFeedTuners(feedDesc: FeedDescriptor) {
]
}
if (feedDesc.startsWith('list')) {
return [FeedTuner.dedupReposts]
const feedTuners = []
if (feedDesc.endsWith('|as_following')) {
// Same as Following tuners below, copypaste for now.
if (preferences?.feedViewPrefs.hideReposts) {
feedTuners.push(FeedTuner.removeReposts)
} else {
feedTuners.push(FeedTuner.dedupReposts)
}
if (preferences?.feedViewPrefs.hideReplies) {
feedTuners.push(FeedTuner.removeReplies)
} else {
feedTuners.push(
FeedTuner.thresholdRepliesOnly({
userDid: currentAccount?.did || '',
minLikes: preferences?.feedViewPrefs.hideRepliesByLikeCount || 0,
followedOnly:
!!preferences?.feedViewPrefs.hideRepliesByUnfollowed,
}),
)
}
if (preferences?.feedViewPrefs.hideQuotePosts) {
feedTuners.push(FeedTuner.removeQuotePosts)
}
} else {
feedTuners.push(FeedTuner.dedupReposts)
}
return feedTuners
}
if (feedDesc === 'following') {
const feedTuners = []
@@ -29,7 +62,6 @@ export function useFeedTuners(feedDesc: FeedDescriptor) {
} else {
feedTuners.push(FeedTuner.dedupReposts)
}
if (preferences?.feedViewPrefs.hideReplies) {
feedTuners.push(FeedTuner.removeReplies)
} else {
@@ -41,7 +73,6 @@ export function useFeedTuners(feedDesc: FeedDescriptor) {
}),
)
}
if (preferences?.feedViewPrefs.hideQuotePosts) {
feedTuners.push(FeedTuner.removeQuotePosts)
}
+28 -16
View File
@@ -509,6 +509,7 @@ export function useSavedFeeds() {
placeholderData: previousData => {
return (
previousData || {
// The likely count before we try to resolve them.
count: savedItems.length,
feeds: [],
}
@@ -556,28 +557,39 @@ export function useSavedFeeds() {
precacheList(queryClient, list)
})
const res: SavedFeedItem[] = savedItems.map(s => {
if (s.type === 'timeline') {
return {
const result: SavedFeedItem[] = []
for (let savedItem of savedItems) {
if (savedItem.type === 'timeline') {
result.push({
type: 'timeline',
config: s,
config: savedItem,
view: undefined,
})
} else if (savedItem.type === 'feed') {
const resolvedFeed = resolvedFeeds.get(savedItem.value)
if (resolvedFeed) {
result.push({
type: 'feed',
config: savedItem,
view: resolvedFeed,
})
}
} else if (savedItem.type === 'list') {
const resolvedList = resolvedLists.get(savedItem.value)
if (resolvedList) {
result.push({
type: 'list',
config: savedItem,
view: resolvedList,
})
}
}
return {
type: s.type,
config: s,
view:
s.type === 'feed'
? resolvedFeeds.get(s.value)
: resolvedLists.get(s.value),
}
}) as SavedFeedItem[]
}
return {
count: savedItems.length,
feeds: res,
// By this point we know the real count.
count: result.length,
feeds: result,
}
},
})
+3
View File
@@ -26,6 +26,7 @@ import {
useQueryClient,
} from '@tanstack/react-query'
import {useGate} from '#/lib/statsig/statsig'
import {useAgent} from '#/state/session'
import {useModerationOpts} from '../../preferences/moderation-opts'
import {STALE} from '..'
@@ -56,6 +57,7 @@ export function useNotificationFeedQuery(opts?: {enabled?: boolean}) {
const unreads = useUnreadNotificationsApi()
const enabled = opts?.enabled !== false
const lastPageCountRef = useRef(0)
const gate = useGate()
const query = useInfiniteQuery<
FeedPage,
@@ -81,6 +83,7 @@ export function useNotificationFeedQuery(opts?: {enabled?: boolean}) {
queryClient,
moderationOpts,
fetchAdditionalData: true,
shouldUngroupFollowBacks: () => gate('ungroup_follow_backs'),
})
).page
}
+4 -1
View File
@@ -8,6 +8,7 @@ import {useQueryClient} from '@tanstack/react-query'
import EventEmitter from 'eventemitter3'
import BroadcastChannel from '#/lib/broadcast'
import {useGate} from '#/lib/statsig/statsig'
import {logger} from '#/logger'
import {useAgent, useSession} from '#/state/session'
import {resetBadgeCount} from 'lib/notifications/notifications'
@@ -47,6 +48,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
const agent = useAgent()
const queryClient = useQueryClient()
const moderationOpts = useModerationOpts()
const gate = useGate()
const [numUnread, setNumUnread] = React.useState('')
@@ -149,6 +151,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
// only fetch subjects when the page is going to be used
// in the notifications query, otherwise skip it
fetchAdditionalData: !!invalidate,
shouldUngroupFollowBacks: () => gate('ungroup_follow_backs'),
})
const unreadCount = countUnread(page)
const unreadCountStr =
@@ -189,7 +192,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
}
},
}
}, [setNumUnread, queryClient, moderationOpts, agent])
}, [setNumUnread, queryClient, moderationOpts, agent, gate])
checkUnreadRef.current = api.checkUnread
return (
+18 -5
View File
@@ -30,6 +30,7 @@ export async function fetchPage({
queryClient,
moderationOpts,
fetchAdditionalData,
shouldUngroupFollowBacks,
}: {
agent: BskyAgent
cursor: string | undefined
@@ -37,6 +38,7 @@ export async function fetchPage({
queryClient: QueryClient
moderationOpts: ModerationOpts | undefined
fetchAdditionalData: boolean
shouldUngroupFollowBacks?: () => boolean
}): Promise<{page: FeedPage; indexedAt: string | undefined}> {
const res = await agent.listNotifications({
limit,
@@ -51,7 +53,7 @@ export async function fetchPage({
)
// group notifications which are essentially similar (follows, likes on a post)
let notifsGrouped = groupNotifications(notifs)
let notifsGrouped = groupNotifications(notifs, {shouldUngroupFollowBacks})
// we fetch subjects of notifications (usually posts) now instead of lazily
// in the UI to avoid relayouts
@@ -109,6 +111,7 @@ export function shouldFilterNotif(
export function groupNotifications(
notifs: AppBskyNotificationListNotifications.Notification[],
options?: {shouldUngroupFollowBacks?: () => boolean},
): FeedNotification[] {
const groupedNotifs: FeedNotification[] = []
for (const notif of notifs) {
@@ -123,10 +126,20 @@ export function groupNotifications(
notif.reasonSubject === groupedNotif.notification.reasonSubject &&
notif.author.did !== groupedNotif.notification.author.did
) {
groupedNotif.additional = groupedNotif.additional || []
groupedNotif.additional.push(notif)
grouped = true
break
const nextIsFollowBack =
notif.reason === 'follow' && notif.author.viewer?.following
const prevIsFollowBack =
groupedNotif.notification.reason === 'follow' &&
groupedNotif.notification.author.viewer?.following
const shouldUngroup =
(nextIsFollowBack || prevIsFollowBack) &&
options?.shouldUngroupFollowBacks?.()
if (!shouldUngroup) {
groupedNotif.additional = groupedNotif.additional || []
groupedNotif.additional.push(notif)
grouped = true
break
}
}
}
}
+35 -3
View File
@@ -17,11 +17,13 @@ import {
import {HomeFeedAPI} from '#/lib/api/feed/home'
import {aggregateUserInterests} from '#/lib/api/feed/utils'
import {DISCOVER_FEED_URI} from '#/lib/constants'
import {moderatePost_wrapped as moderatePost} from '#/lib/moderatePost_wrapped'
import {logger} from '#/logger'
import {STALE} from '#/state/queries'
import {DEFAULT_LOGGED_OUT_PREFERENCES} from '#/state/queries/preferences/const'
import {useAgent} from '#/state/session'
import * as userActionHistory from '#/state/userActionHistory'
import {AuthorFeedAPI} from 'lib/api/feed/author'
import {CustomFeedAPI} from 'lib/api/feed/custom'
import {FollowingFeedAPI} from 'lib/api/feed/following'
@@ -49,6 +51,7 @@ type AuthorFilter =
| 'posts_with_media'
type FeedUri = string
type ListUri = string
type ListFilter = 'as_following' // Applies current Following settings. Currently client-side.
export type FeedDescriptor =
| 'following'
@@ -56,6 +59,7 @@ export type FeedDescriptor =
| `feedgen|${FeedUri}`
| `likes|${ActorDid}`
| `list|${ListUri}`
| `list|${ListUri}|${ListFilter}`
export interface FeedParams {
disableTuner?: boolean
mergeFeedEnabled?: boolean
@@ -129,6 +133,7 @@ export function usePostFeedQuery(
result: InfiniteData<FeedPage>
} | null>(null)
const lastPageCountRef = useRef(0)
const isDiscover = feedDesc.includes(DISCOVER_FEED_URI)
// Make sure this doesn't invalidate unless really needed.
const selectArgs = React.useMemo(
@@ -137,8 +142,15 @@ export function usePostFeedQuery(
disableTuner: params?.disableTuner,
moderationOpts,
ignoreFilterFor: opts?.ignoreFilterFor,
isDiscover,
}),
[feedTuners, params?.disableTuner, moderationOpts, opts?.ignoreFilterFor],
[
feedTuners,
params?.disableTuner,
moderationOpts,
opts?.ignoreFilterFor,
isDiscover,
],
)
const query = useInfiniteQuery<
@@ -217,8 +229,13 @@ export function usePostFeedQuery(
(data: InfiniteData<FeedPageUnselected, RQPageParam>) => {
// If the selection depends on some data, that data should
// be included in the selectArgs object and read here.
const {feedTuners, disableTuner, moderationOpts, ignoreFilterFor} =
selectArgs
const {
feedTuners,
disableTuner,
moderationOpts,
ignoreFilterFor,
isDiscover,
} = selectArgs
const tuner = disableTuner
? new NoopFeedTuner()
@@ -291,6 +308,21 @@ export function usePostFeedQuery(
}
}
if (isDiscover) {
userActionHistory.seen(
slice.items.map(item => ({
feedContext: item.feedContext,
likeCount: item.post.likeCount ?? 0,
repostCount: item.post.repostCount ?? 0,
replyCount: item.post.replyCount ?? 0,
isFollowedBy: Boolean(
item.post.author.viewer?.followedBy,
),
uri: item.post.uri,
})),
)
}
return {
_reactKey: slice._reactKey,
_isFeedPostSlice: true,

Some files were not shown because too many files have changed in this diff Show More