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

This commit is contained in:
Minseo Lee
2024-09-03 17:54:27 +09:00
84 changed files with 2441 additions and 1034 deletions
+1 -1
View File
@@ -22,7 +22,7 @@
"eslint-plugin-simple-import-sort": "^12.0.0",
"postcss": "^8.4.38",
"tailwindcss": "^3.4.3",
"typescript": "^4.0.5",
"typescript": "^5.5.4",
"vite": "^5.2.8",
"vite-tsconfig-paths": "^4.3.2"
}
+4 -4
View File
@@ -11,7 +11,7 @@ import likeIcon from '../../assets/heart2_filled_stroke2_corner0_rounded.svg'
import logo from '../../assets/logo.svg'
import repostIcon from '../../assets/repost_stroke2_corner2_rounded.svg'
import {CONTENT_LABELS} from '../labels'
import {getRkey, niceDate} from '../utils'
import {getRkey, niceDate, prettyNumber} from '../utils'
import {Container} from './container'
import {Embed} from './embed'
import {Link} from './link'
@@ -78,7 +78,7 @@ export function Post({thread}: Props) {
<div className="flex items-center gap-2 cursor-pointer">
<img src={likeIcon} className="w-5 h-5" />
<p className="font-bold text-neutral-500 mb-px">
{post.likeCount}
{prettyNumber(post.likeCount)}
</p>
</div>
)}
@@ -86,7 +86,7 @@ export function Post({thread}: Props) {
<div className="flex items-center gap-2 cursor-pointer">
<img src={repostIcon} className="w-5 h-5" />
<p className="font-bold text-neutral-500 mb-px">
{post.repostCount}
{prettyNumber(post.repostCount)}
</p>
</div>
)}
@@ -97,7 +97,7 @@ export function Post({thread}: Props) {
<div className="flex-1" />
<p className="cursor-pointer text-brand font-bold hover:underline hidden min-[450px]:inline">
{post.replyCount
? `Read ${post.replyCount} ${
? `Read ${prettyNumber(post.replyCount)} ${
post.replyCount > 1 ? 'replies' : 'reply'
} on Bluesky`
: `View on Bluesky`}
+10
View File
@@ -16,3 +16,13 @@ export function getRkey({uri}: {uri: string}): string {
const at = new AtUri(uri)
return at.rkey
}
const formatter = new Intl.NumberFormat('en-US', {
notation: 'compact',
maximumFractionDigits: 1,
roundingMode: 'trunc',
})
export function prettyNumber(number: number) {
return formatter.format(number)
}
+1 -1
View File
@@ -20,5 +20,5 @@
"jsxFragmentFactory": "Fragment",
"downlevelIteration": true
},
"include": ["src"]
"include": ["src", "vite.config.ts"]
}
+1 -1
View File
@@ -6,5 +6,5 @@
"strict": true,
"outDir": "dist"
},
"include": ["snippet"],
"include": ["snippet"]
}
+4 -4
View File
@@ -4024,10 +4024,10 @@ typed-array-length@^1.0.6:
is-typed-array "^1.1.13"
possible-typed-array-names "^1.0.0"
typescript@^4.0.5:
version "4.9.5"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.9.5.tgz#095979f9bcc0d09da324d58d03ce8f8374cbe65a"
integrity sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==
typescript@^5.5.4:
version "5.5.4"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.5.4.tgz#d9852d6c82bad2d2eda4fd74a5762a8f5909e9ba"
integrity sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==
uint8arrays@3.0.0:
version "3.0.0"
+10 -11
View File
@@ -2,7 +2,6 @@ const path = require('path')
const fs = require('fs')
const projectRoot = path.join(__dirname, '..')
const webBuildJs = path.join(projectRoot, 'web-build', 'static', 'js')
const templateFile = path.join(
projectRoot,
'bskyweb',
@@ -10,18 +9,18 @@ const templateFile = path.join(
'scripts.html',
)
const jsFiles = fs.readdirSync(webBuildJs).filter(name => name.endsWith('.js'))
jsFiles.sort((a, b) => {
// make sure main is written last
if (a.startsWith('main')) return 1
if (b.startsWith('main')) return -1
return a.localeCompare(b)
})
const {entrypoints} = require(path.join(
projectRoot,
'web-build/asset-manifest.json',
))
console.log(`Found ${jsFiles.length} js files in web-build`)
console.log(`Found ${entrypoints.length} entrypoints`)
console.log(`Writing ${templateFile}`)
const outputFile = jsFiles
.map(name => `<script defer="defer" src="/static/js/${name}"></script>`)
const outputFile = entrypoints
.map(name => {
const file = path.basename(name)
return `<script defer="defer" src="/static/js/${file}"></script>`
})
.join('\n')
fs.writeFileSync(templateFile, outputFile)
+14 -14
View File
@@ -175,25 +175,25 @@ function App() {
<A11yProvider>
<KeyboardProvider enabled={false} statusBarTranslucent={true}>
<SessionProvider>
<ShellStateProvider>
<PrefsStateProvider>
<InvitesStateProvider>
<ModalStateProvider>
<DialogStateProvider>
<LightboxStateProvider>
<I18nProvider>
<PrefsStateProvider>
<I18nProvider>
<ShellStateProvider>
<InvitesStateProvider>
<ModalStateProvider>
<DialogStateProvider>
<LightboxStateProvider>
<PortalProvider>
<StarterPackProvider>
<InnerApp />
</StarterPackProvider>
</PortalProvider>
</I18nProvider>
</LightboxStateProvider>
</DialogStateProvider>
</ModalStateProvider>
</InvitesStateProvider>
</PrefsStateProvider>
</ShellStateProvider>
</LightboxStateProvider>
</DialogStateProvider>
</ModalStateProvider>
</InvitesStateProvider>
</ShellStateProvider>
</I18nProvider>
</PrefsStateProvider>
</SessionProvider>
</KeyboardProvider>
</A11yProvider>
+14 -14
View File
@@ -153,25 +153,25 @@ function App() {
return (
<A11yProvider>
<SessionProvider>
<ShellStateProvider>
<PrefsStateProvider>
<InvitesStateProvider>
<ModalStateProvider>
<DialogStateProvider>
<LightboxStateProvider>
<I18nProvider>
<PrefsStateProvider>
<I18nProvider>
<ShellStateProvider>
<InvitesStateProvider>
<ModalStateProvider>
<DialogStateProvider>
<LightboxStateProvider>
<PortalProvider>
<StarterPackProvider>
<InnerApp />
</StarterPackProvider>
</PortalProvider>
</I18nProvider>
</LightboxStateProvider>
</DialogStateProvider>
</ModalStateProvider>
</InvitesStateProvider>
</PrefsStateProvider>
</ShellStateProvider>
</LightboxStateProvider>
</DialogStateProvider>
</ModalStateProvider>
</InvitesStateProvider>
</ShellStateProvider>
</I18nProvider>
</PrefsStateProvider>
</SessionProvider>
</A11yProvider>
)
+1
View File
@@ -490,6 +490,7 @@ function MyProfileTabNavigator() {
getComponent={() => ProfileScreen}
initialParams={{
name: 'me',
hideBackButton: true,
}}
/>
{commonScreens(MyProfileTab as typeof HomeTab)}
+9
View File
@@ -853,6 +853,7 @@ export const atoms = {
mr_auto: {
marginRight: 'auto',
},
/*
* Pointer events & user select
*/
@@ -871,6 +872,7 @@ export const atoms = {
user_select_all: {
userSelect: 'all',
},
/*
* Text decoration
*/
@@ -880,4 +882,11 @@ export const atoms = {
strike_through: {
textDecorationLine: 'line-through',
},
/*
* Display
*/
hidden: {
display: 'none',
},
} as const
+10 -53
View File
@@ -1,5 +1,5 @@
import React from 'react'
import {Dimensions} from 'react-native'
import {useMediaQuery} from 'react-responsive'
import {createThemes, defaultTheme} from '#/alf/themes'
import {Theme, ThemeName} from '#/alf/types'
@@ -12,52 +12,15 @@ export * from '#/alf/util/flatten'
export * from '#/alf/util/platform'
export * from '#/alf/util/themeSelector'
type BreakpointName = keyof typeof breakpoints
/*
* Breakpoints
*/
const breakpoints: {
[key: string]: number
} = {
gtPhone: 500,
gtMobile: 800,
gtTablet: 1300,
}
function getActiveBreakpoints({width}: {width: number}) {
const active: (keyof typeof breakpoints)[] = Object.keys(breakpoints).filter(
breakpoint => width >= breakpoints[breakpoint],
)
return {
active: active[active.length - 1],
gtPhone: active.includes('gtPhone'),
gtMobile: active.includes('gtMobile'),
gtTablet: active.includes('gtTablet'),
}
}
/*
* Context
*/
export const Context = React.createContext<{
themeName: ThemeName
theme: Theme
breakpoints: {
active: BreakpointName | undefined
gtPhone: boolean
gtMobile: boolean
gtTablet: boolean
}
}>({
themeName: 'light',
theme: defaultTheme,
breakpoints: {
active: undefined,
gtPhone: false,
gtMobile: false,
gtTablet: false,
},
})
export function ThemeProvider({
@@ -74,18 +37,6 @@ export function ThemeProvider({
})
}, [])
const theme = themes[themeName]
const [breakpoints, setBreakpoints] = React.useState(() =>
getActiveBreakpoints({width: Dimensions.get('window').width}),
)
React.useEffect(() => {
const listener = Dimensions.addEventListener('change', ({window}) => {
const bp = getActiveBreakpoints({width: window.width})
if (bp.active !== breakpoints.active) setBreakpoints(bp)
})
return listener.remove
}, [breakpoints, setBreakpoints])
return (
<Context.Provider
@@ -93,9 +44,8 @@ export function ThemeProvider({
() => ({
themeName: themeName,
theme: theme,
breakpoints,
}),
[theme, themeName, breakpoints],
[theme, themeName],
)}>
{children}
</Context.Provider>
@@ -107,5 +57,12 @@ export function useTheme() {
}
export function useBreakpoints() {
return React.useContext(Context).breakpoints
const gtPhone = useMediaQuery({minWidth: 500})
const gtMobile = useMediaQuery({minWidth: 800})
const gtTablet = useMediaQuery({minWidth: 1300})
return {
gtPhone,
gtMobile,
gtTablet,
}
}
+56 -4
View File
@@ -1,18 +1,21 @@
import React from 'react'
import {View} from 'react-native'
import {ScrollView} from 'react-native-gesture-handler'
import {AppBskyFeedDefs, AtUri} from '@atproto/api'
import {AppBskyActorDefs, 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 {useGate} from '#/lib/statsig/statsig'
import {logEvent} from '#/lib/statsig/statsig'
import {logger} from '#/logger'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {useGetPopularFeedsQuery} from '#/state/queries/feed'
import {FeedDescriptor} from '#/state/queries/post-feed'
import {useProfilesQuery} from '#/state/queries/profile'
import {useSuggestedFollowsByActorQuery} from '#/state/queries/suggested-follows'
import {useSession} from '#/state/session'
import {useProgressGuide} from '#/state/shell/progress-guide'
import * as userActionHistory from '#/state/userActionHistory'
@@ -173,14 +176,63 @@ function useExperimentalSuggestedUsersQuery() {
}
}
export function SuggestedFollows() {
const t = useTheme()
const {_} = useLingui()
export function SuggestedFollows({feed}: {feed: FeedDescriptor}) {
const gate = useGate()
const [feedType, feedUri] = feed.split('|')
if (feedType === 'author') {
if (gate('show_follow_suggestions_in_profile')) {
return <SuggestedFollowsProfile did={feedUri} />
} else {
return null
}
} else {
return <SuggestedFollowsHome />
}
}
export function SuggestedFollowsProfile({did}: {did: string}) {
const {
isLoading: isSuggestionsLoading,
data,
error,
} = useSuggestedFollowsByActorQuery({
did,
})
return (
<ProfileGrid
isSuggestionsLoading={isSuggestionsLoading}
profiles={data?.suggestions ?? []}
error={error}
/>
)
}
export function SuggestedFollowsHome() {
const {
isLoading: isSuggestionsLoading,
profiles,
error,
} = useExperimentalSuggestedUsersQuery()
return (
<ProfileGrid
isSuggestionsLoading={isSuggestionsLoading}
profiles={profiles}
error={error}
/>
)
}
export function ProfileGrid({
isSuggestionsLoading,
error,
profiles,
}: {
isSuggestionsLoading: boolean
profiles: AppBskyActorDefs.ProfileViewDetailed[]
error: Error | null
}) {
const t = useTheme()
const {_} = useLingui()
const moderationOpts = useModerationOpts()
const navigation = useNavigation<NavigationProp>()
const {gtMobile} = useBreakpoints()
@@ -377,7 +377,7 @@ function Inner({
hide: () => void
}) {
const t = useTheme()
const {_} = useLingui()
const {_, i18n} = useLingui()
const {currentAccount} = useSession()
const moderation = React.useMemo(
() => moderateProfile(profile, moderationOpts),
@@ -393,8 +393,8 @@ function Inner({
profile.viewer?.blocking ||
profile.viewer?.blockedBy ||
profile.viewer?.blockingByList
const following = formatCount(profile.followsCount || 0)
const followers = formatCount(profile.followersCount || 0)
const following = formatCount(i18n, profile.followsCount || 0)
const followers = formatCount(i18n, profile.followersCount || 0)
const pluralizedFollowers = plural(profile.followersCount || 0, {
one: 'follower',
other: 'followers',
+18 -14
View File
@@ -59,20 +59,24 @@ export const QrCode = React.forwardRef<ViewShot, Props>(function QrCode(
<QrCodeInner link={link} />
</View>
<View style={[a.flex_row, a.align_center, {gap: 5}]}>
<Text
style={[
a.font_bold,
a.text_center,
{color: 'white', fontSize: 18},
]}>
<Trans>on</Trans>
</Text>
<Logo width={26} fill="white" />
<View style={[{marginTop: 5, marginLeft: 2.5}]}>
<Logotype width={68} fill="white" />
</View>
</View>
<Text
style={[
a.flex,
a.flex_row,
a.align_center,
a.font_bold,
{color: 'white', fontSize: 18, gap: 6},
]}>
<Trans>
on
<View style={[a.flex_row, a.align_center, {gap: 6}]}>
<Logo width={25} fill="white" />
<View style={[{marginTop: 3.5}]}>
<Logotype width={72} fill="white" />
</View>
</View>
</Trans>
</Text>
</View>
</LinearGradientBackground>
</ViewShot>
+3 -3
View File
@@ -43,7 +43,7 @@ function EmbedDialogInner({
timestamp,
}: Omit<EmbedDialogProps, 'control'>) {
const t = useTheme()
const {_} = useLingui()
const {_, i18n} = useLingui()
const ref = useRef<TextInput>(null)
const [copied, setCopied] = useState(false)
@@ -86,9 +86,9 @@ function EmbedDialogInner({
)} (<a href="${escapeHtml(profileHref)}">@${escapeHtml(
postAuthor.handle,
)}</a>) <a href="${escapeHtml(href)}">${escapeHtml(
niceDate(timestamp),
niceDate(i18n, timestamp),
)}</a></blockquote><script async src="${EMBED_SCRIPT}" charset="utf-8"></script>`
}, [postUri, postCid, record, timestamp, postAuthor])
}, [i18n, postUri, postCid, record, timestamp, postAuthor])
return (
<Dialog.Inner label="Embed post" style={[a.gap_md, {maxWidth: 500}]}>
+6 -5
View File
@@ -11,6 +11,7 @@ import {
ChatBskyConvoDefs,
RichText as RichTextAPI,
} from '@atproto/api'
import {I18n} from '@lingui/core'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
@@ -153,14 +154,14 @@ let MessageItemMetadata = ({
)
const relativeTimestamp = useCallback(
(timestamp: string) => {
(i18n: I18n, timestamp: string) => {
const date = new Date(timestamp)
const now = new Date()
const time = new Intl.DateTimeFormat(undefined, {
const time = i18n.date(date, {
hour: 'numeric',
minute: 'numeric',
}).format(date)
})
const diff = now.getTime() - date.getTime()
@@ -182,13 +183,13 @@ let MessageItemMetadata = ({
return _(msg`Yesterday, ${time}`)
}
return new Intl.DateTimeFormat(undefined, {
return i18n.date(date, {
hour: 'numeric',
minute: 'numeric',
day: 'numeric',
month: 'numeric',
year: 'numeric',
}).format(date)
})
},
[_],
)
@@ -1,12 +1,12 @@
import React from 'react'
import {Pressable, View} from 'react-native'
import {useLingui} from '@lingui/react'
import {android, atoms as a, useTheme, web} from '#/alf'
import * as TextField from '#/components/forms/TextField'
import {useInteractionState} from '#/components/hooks/useInteractionState'
import {CalendarDays_Stroke2_Corner0_Rounded as CalendarDays} from '#/components/icons/CalendarDays'
import {Text} from '#/components/Typography'
import {localizeDate} from './utils'
// looks like a TextField.Input, but is just a button. It'll do something different on each platform on press
// iOS: open a dialog with an inline date picker
@@ -25,6 +25,7 @@ export function DateFieldButton({
isInvalid?: boolean
accessibilityHint?: string
}) {
const {i18n} = useLingui()
const t = useTheme()
const {
@@ -91,7 +92,7 @@ export function DateFieldButton({
t.atoms.text,
{lineHeight: a.text_md.fontSize * 1.1875},
]}>
{localizeDate(value)}
{i18n.date(value, {timeZone: 'UTC'})}
</Text>
</Pressable>
</View>
-11
View File
@@ -1,16 +1,5 @@
import {getLocales} from 'expo-localization'
const LOCALE = getLocales()[0]
// we need the date in the form yyyy-MM-dd to pass to the input
export function toSimpleDateString(date: Date | string): string {
const _date = typeof date === 'string' ? new Date(date) : date
return _date.toISOString().split('T')[0]
}
export function localizeDate(date: Date | string): string {
const _date = typeof date === 'string' ? new Date(date) : date
return new Intl.DateTimeFormat(LOCALE.languageTag, {
timeZone: 'UTC',
}).format(_date)
}
+30 -7
View File
@@ -81,7 +81,15 @@ export class FeedViewPostsSlice {
isParentBlocked,
isParentNotFound,
})
if (!reply || reason) {
if (!reply) {
if (post.record.reply) {
// This reply wasn't properly hydrated by the AppView.
this.isOrphan = true
this.items[0].isParentNotFound = true
}
return
}
if (reason) {
return
}
if (
@@ -366,11 +374,7 @@ export class FeedTuner {
): FeedViewPostsSlice[] => {
for (let i = 0; i < slices.length; i++) {
const slice = slices[i]
if (
slice.isReply &&
!slice.isRepost &&
!shouldDisplayReplyInFollowing(slice.getAuthors(), userDid)
) {
if (slice.isReply && !shouldDisplayReplyInFollowing(slice, userDid)) {
slices.splice(i, 1)
i--
}
@@ -434,9 +438,13 @@ function areSameAuthor(authors: AuthorContext): boolean {
}
function shouldDisplayReplyInFollowing(
authors: AuthorContext,
slice: FeedViewPostsSlice,
userDid: string,
): boolean {
if (slice.isRepost) {
return true
}
const authors = slice.getAuthors()
const {author, parentAuthor, grandparentAuthor, rootAuthor} = authors
if (!isSelfOrFollowing(author, userDid)) {
// Only show replies from self or people you follow.
@@ -450,6 +458,21 @@ function shouldDisplayReplyInFollowing(
// Always show self-threads.
return true
}
if (
parentAuthor &&
parentAuthor.did !== author.did &&
rootAuthor &&
rootAuthor.did === author.did &&
slice.items.length > 2
) {
// If you follow A, show A -> someone[>0 likes] -> A chains too.
// This is different from cases below because you only know one person.
const parentPost = slice.items[1].post
const parentLikeCount = parentPost.likeCount ?? 0
if (parentLikeCount > 0) {
return true
}
}
// From this point on we need at least one more reason to show it.
if (
parentAuthor &&
+25 -3
View File
@@ -1,4 +1,5 @@
import {
AppBskyEmbedDefs,
AppBskyEmbedExternal,
AppBskyEmbedImages,
AppBskyEmbedRecord,
@@ -45,7 +46,12 @@ interface PostOpts {
uri: string
cid: string
}
video?: BlobRef
video?: {
blobRef: BlobRef
altText: string
captions: {lang: string; file: File}[]
aspectRatio?: AppBskyEmbedDefs.AspectRatio
}
extLink?: ExternalEmbedDraft
images?: ImageModel[]
labels?: string[]
@@ -128,19 +134,35 @@ export async function post(agent: BskyAgent, opts: PostOpts) {
// add video embed if present
if (opts.video) {
const captions = await Promise.all(
opts.video.captions
.filter(caption => caption.lang !== '')
.map(async caption => {
const {data} = await agent.uploadBlob(caption.file, {
encoding: 'text/vtt',
})
return {lang: caption.lang, file: data.blob}
}),
)
if (opts.quote) {
embed = {
$type: 'app.bsky.embed.recordWithMedia',
record: embed,
media: {
$type: 'app.bsky.embed.video',
video: opts.video,
video: opts.video.blobRef,
alt: opts.video.altText || undefined,
captions: captions.length === 0 ? undefined : captions,
aspectRatio: opts.video.aspectRatio,
} as AppBskyEmbedVideo.Main,
} as AppBskyEmbedRecordWithMedia.Main
} else {
embed = {
$type: 'app.bsky.embed.video',
video: opts.video,
video: opts.video.blobRef,
alt: opts.video.altText || undefined,
captions: captions.length === 0 ? undefined : captions,
aspectRatio: opts.video.aspectRatio,
} as AppBskyEmbedVideo.Main
}
}
+177
View File
@@ -0,0 +1,177 @@
import React from 'react'
import {View} from 'react-native'
import Animated, {
Easing,
LayoutAnimationConfig,
useReducedMotion,
withTiming,
} from 'react-native-reanimated'
import {i18n} from '@lingui/core'
import {decideShouldRoll} from 'lib/custom-animations/util'
import {s} from 'lib/styles'
import {formatCount} from 'view/com/util/numeric/format'
import {Text} from 'view/com/util/text/Text'
import {atoms as a, useTheme} from '#/alf'
const animationConfig = {
duration: 400,
easing: Easing.out(Easing.cubic),
}
function EnteringUp() {
'worklet'
const animations = {
opacity: withTiming(1, animationConfig),
transform: [{translateY: withTiming(0, animationConfig)}],
}
const initialValues = {
opacity: 0,
transform: [{translateY: 18}],
}
return {
animations,
initialValues,
}
}
function EnteringDown() {
'worklet'
const animations = {
opacity: withTiming(1, animationConfig),
transform: [{translateY: withTiming(0, animationConfig)}],
}
const initialValues = {
opacity: 0,
transform: [{translateY: -18}],
}
return {
animations,
initialValues,
}
}
function ExitingUp() {
'worklet'
const animations = {
opacity: withTiming(0, animationConfig),
transform: [
{
translateY: withTiming(-18, animationConfig),
},
],
}
const initialValues = {
opacity: 1,
transform: [{translateY: 0}],
}
return {
animations,
initialValues,
}
}
function ExitingDown() {
'worklet'
const animations = {
opacity: withTiming(0, animationConfig),
transform: [{translateY: withTiming(18, animationConfig)}],
}
const initialValues = {
opacity: 1,
transform: [{translateY: 0}],
}
return {
animations,
initialValues,
}
}
export function CountWheel({
likeCount,
big,
isLiked,
}: {
likeCount: number
big?: boolean
isLiked: boolean
}) {
const t = useTheme()
const shouldAnimate = !useReducedMotion()
const shouldRoll = decideShouldRoll(isLiked, likeCount)
// Incrementing the key will cause the `Animated.View` to re-render, with the newly selected entering/exiting
// animation
// The initial entering/exiting animations will get skipped, since these will happen on screen mounts and would
// be unnecessary
const [key, setKey] = React.useState(0)
const [prevCount, setPrevCount] = React.useState(likeCount)
const prevIsLiked = React.useRef(isLiked)
const formattedCount = formatCount(i18n, likeCount)
const formattedPrevCount = formatCount(i18n, prevCount)
React.useEffect(() => {
if (isLiked === prevIsLiked.current) {
return
}
const newPrevCount = isLiked ? likeCount - 1 : likeCount + 1
setKey(prev => prev + 1)
setPrevCount(newPrevCount)
prevIsLiked.current = isLiked
}, [isLiked, likeCount])
const enteringAnimation =
shouldAnimate && shouldRoll
? isLiked
? EnteringUp
: EnteringDown
: undefined
const exitingAnimation =
shouldAnimate && shouldRoll
? isLiked
? ExitingUp
: ExitingDown
: undefined
return (
<LayoutAnimationConfig skipEntering skipExiting>
{likeCount > 0 ? (
<View style={[a.justify_center]}>
<Animated.View entering={enteringAnimation} key={key}>
<Text
testID="likeCount"
style={[
big ? a.text_md : {fontSize: 15},
a.user_select_none,
isLiked
? [a.font_bold, s.likeColor]
: {color: t.palette.contrast_500},
]}>
{formattedCount}
</Text>
</Animated.View>
{shouldAnimate && (likeCount > 1 || !isLiked) ? (
<Animated.View
entering={exitingAnimation}
// Add 2 to the key so there are never duplicates
key={key + 2}
style={[a.absolute, {width: 50, opacity: 0}]}
aria-disabled={true}>
<Text
style={[
big ? a.text_md : {fontSize: 15},
a.user_select_none,
isLiked
? [a.font_bold, s.likeColor]
: {color: t.palette.contrast_500},
]}>
{formattedPrevCount}
</Text>
</Animated.View>
) : null}
</View>
) : null}
</LayoutAnimationConfig>
)
}
@@ -0,0 +1,120 @@
import React from 'react'
import {View} from 'react-native'
import {useReducedMotion} from 'react-native-reanimated'
import {i18n} from '@lingui/core'
import {decideShouldRoll} from 'lib/custom-animations/util'
import {s} from 'lib/styles'
import {formatCount} from 'view/com/util/numeric/format'
import {Text} from 'view/com/util/text/Text'
import {atoms as a, useTheme} from '#/alf'
const animationConfig = {
duration: 400,
easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
fill: 'forwards' as FillMode,
}
const enteringUpKeyframe = [
{opacity: 0, transform: 'translateY(18px)'},
{opacity: 1, transform: 'translateY(0)'},
]
const enteringDownKeyframe = [
{opacity: 0, transform: 'translateY(-18px)'},
{opacity: 1, transform: 'translateY(0)'},
]
const exitingUpKeyframe = [
{opacity: 1, transform: 'translateY(0)'},
{opacity: 0, transform: 'translateY(-18px)'},
]
const exitingDownKeyframe = [
{opacity: 1, transform: 'translateY(0)'},
{opacity: 0, transform: 'translateY(18px)'},
]
export function CountWheel({
likeCount,
big,
isLiked,
}: {
likeCount: number
big?: boolean
isLiked: boolean
}) {
const t = useTheme()
const shouldAnimate = !useReducedMotion()
const shouldRoll = decideShouldRoll(isLiked, likeCount)
const countView = React.useRef<HTMLDivElement>(null)
const prevCountView = React.useRef<HTMLDivElement>(null)
const [prevCount, setPrevCount] = React.useState(likeCount)
const prevIsLiked = React.useRef(isLiked)
const formattedCount = formatCount(i18n, likeCount)
const formattedPrevCount = formatCount(i18n, prevCount)
React.useEffect(() => {
if (isLiked === prevIsLiked.current) {
return
}
const newPrevCount = isLiked ? likeCount - 1 : likeCount + 1
if (shouldAnimate && shouldRoll) {
countView.current?.animate?.(
isLiked ? enteringUpKeyframe : enteringDownKeyframe,
animationConfig,
)
prevCountView.current?.animate?.(
isLiked ? exitingUpKeyframe : exitingDownKeyframe,
animationConfig,
)
setPrevCount(newPrevCount)
}
prevIsLiked.current = isLiked
}, [isLiked, likeCount, shouldAnimate, shouldRoll])
if (likeCount < 1) {
return null
}
return (
<View>
<View
// @ts-expect-error is div
ref={countView}>
<Text
testID="likeCount"
style={[
big ? a.text_md : {fontSize: 15},
a.user_select_none,
isLiked
? [a.font_bold, s.likeColor]
: {color: t.palette.contrast_500},
]}>
{formattedCount}
</Text>
</View>
{shouldAnimate && (likeCount > 1 || !isLiked) ? (
<View
style={{position: 'absolute', opacity: 0}}
aria-disabled={true}
// @ts-expect-error is div
ref={prevCountView}>
<Text
style={[
big ? a.text_md : {fontSize: 15},
a.user_select_none,
isLiked
? [a.font_bold, s.likeColor]
: {color: t.palette.contrast_500},
]}>
{formattedPrevCount}
</Text>
</View>
) : null}
</View>
)
}
+135
View File
@@ -0,0 +1,135 @@
import React from 'react'
import {View} from 'react-native'
import Animated, {
Keyframe,
LayoutAnimationConfig,
useReducedMotion,
} from 'react-native-reanimated'
import {s} from 'lib/styles'
import {useTheme} from '#/alf'
import {
Heart2_Filled_Stroke2_Corner0_Rounded as HeartIconFilled,
Heart2_Stroke2_Corner0_Rounded as HeartIconOutline,
} from '#/components/icons/Heart2'
const keyframe = new Keyframe({
0: {
transform: [{scale: 1}],
},
10: {
transform: [{scale: 0.7}],
},
40: {
transform: [{scale: 1.2}],
},
100: {
transform: [{scale: 1}],
},
})
const circle1Keyframe = new Keyframe({
0: {
opacity: 0,
transform: [{scale: 0}],
},
10: {
opacity: 0.4,
},
40: {
transform: [{scale: 1.5}],
},
95: {
opacity: 0.4,
},
100: {
opacity: 0,
transform: [{scale: 1.5}],
},
})
const circle2Keyframe = new Keyframe({
0: {
opacity: 0,
transform: [{scale: 0}],
},
10: {
opacity: 1,
},
40: {
transform: [{scale: 0}],
},
95: {
opacity: 1,
},
100: {
opacity: 0,
transform: [{scale: 1.5}],
},
})
export function AnimatedLikeIcon({
isLiked,
big,
}: {
isLiked: boolean
big?: boolean
}) {
const t = useTheme()
const size = big ? 22 : 18
const shouldAnimate = !useReducedMotion()
return (
<View>
<LayoutAnimationConfig skipEntering>
{isLiked ? (
<Animated.View
entering={shouldAnimate ? keyframe.duration(300) : undefined}>
<HeartIconFilled style={s.likeColor} width={size} />
</Animated.View>
) : (
<HeartIconOutline
style={[{color: t.palette.contrast_500}, {pointerEvents: 'none'}]}
width={size}
/>
)}
{isLiked ? (
<>
<Animated.View
entering={
shouldAnimate ? circle1Keyframe.duration(300) : undefined
}
style={{
position: 'absolute',
backgroundColor: s.likeColor.color,
top: 0,
left: 0,
width: size,
height: size,
zIndex: -1,
pointerEvents: 'none',
borderRadius: size / 2,
}}
/>
<Animated.View
entering={
shouldAnimate ? circle2Keyframe.duration(300) : undefined
}
style={{
position: 'absolute',
backgroundColor: t.atoms.bg.backgroundColor,
top: 0,
left: 0,
width: size,
height: size,
zIndex: -1,
pointerEvents: 'none',
borderRadius: size / 2,
}}
/>
</>
) : null}
</LayoutAnimationConfig>
</View>
)
}
+117
View File
@@ -0,0 +1,117 @@
import React from 'react'
import {View} from 'react-native'
import {useReducedMotion} from 'react-native-reanimated'
import {s} from 'lib/styles'
import {useTheme} from '#/alf'
import {
Heart2_Filled_Stroke2_Corner0_Rounded as HeartIconFilled,
Heart2_Stroke2_Corner0_Rounded as HeartIconOutline,
} from '#/components/icons/Heart2'
const animationConfig = {
duration: 400,
easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
fill: 'forwards' as FillMode,
}
const keyframe = [
{transform: 'scale(1)'},
{transform: 'scale(0.7)'},
{transform: 'scale(1.2)'},
{transform: 'scale(1)'},
]
const circle1Keyframe = [
{opacity: 0, transform: 'scale(0)'},
{opacity: 0.4},
{transform: 'scale(1.5)'},
{opacity: 0.4},
{opacity: 0, transform: 'scale(1.5)'},
]
const circle2Keyframe = [
{opacity: 0, transform: 'scale(0)'},
{opacity: 1},
{transform: 'scale(0)'},
{opacity: 1},
{opacity: 0, transform: 'scale(1.5)'},
]
export function AnimatedLikeIcon({
isLiked,
big,
}: {
isLiked: boolean
big?: boolean
}) {
const t = useTheme()
const size = big ? 22 : 18
const shouldAnimate = !useReducedMotion()
const prevIsLiked = React.useRef(isLiked)
const likeIconRef = React.useRef<HTMLDivElement>(null)
const circle1Ref = React.useRef<HTMLDivElement>(null)
const circle2Ref = React.useRef<HTMLDivElement>(null)
React.useEffect(() => {
if (prevIsLiked.current === isLiked) {
return
}
if (shouldAnimate && isLiked) {
likeIconRef.current?.animate?.(keyframe, animationConfig)
circle1Ref.current?.animate?.(circle1Keyframe, animationConfig)
circle2Ref.current?.animate?.(circle2Keyframe, animationConfig)
}
prevIsLiked.current = isLiked
}, [shouldAnimate, isLiked])
return (
<View>
{isLiked ? (
// @ts-expect-error is div
<View ref={likeIconRef}>
<HeartIconFilled style={s.likeColor} width={size} />
</View>
) : (
<HeartIconOutline
style={[{color: t.palette.contrast_500}, {pointerEvents: 'none'}]}
width={size}
/>
)}
<View
// @ts-expect-error is div
ref={circle1Ref}
style={{
position: 'absolute',
backgroundColor: s.likeColor.color,
top: 0,
left: 0,
width: size,
height: size,
zIndex: -1,
pointerEvents: 'none',
borderRadius: size / 2,
opacity: 0,
}}
/>
<View
// @ts-expect-error is div
ref={circle2Ref}
style={{
position: 'absolute',
backgroundColor: t.atoms.bg.backgroundColor,
top: 0,
left: 0,
width: size,
height: size,
zIndex: -1,
pointerEvents: 'none',
borderRadius: size / 2,
opacity: 0,
}}
/>
</View>
)
}
+21
View File
@@ -0,0 +1,21 @@
// It should roll when:
// - We're going from 1 to 0 (roll backwards)
// - The count is anywhere between 1 and 999
// - The count is going up and is a multiple of 100
// - The count is going down and is 1 less than a multiple of 100
export function decideShouldRoll(isSet: boolean, count: number) {
let shouldRoll = false
if (!isSet && count === 0) {
shouldRoll = true
} else if (count > 0 && count < 1000) {
shouldRoll = true
} else if (count > 0) {
const mod = count % 100
if (isSet && mod === 0) {
shouldRoll = true
} else if (!isSet && mod === 99) {
shouldRoll = true
}
}
return shouldRoll
}
+1 -2
View File
@@ -65,7 +65,6 @@ export function useGenerateStarterPackMutation({
}) {
const {_} = useLingui()
const agent = useAgent()
const starterPackString = _(msg`Starter Pack`)
return useMutation<{uri: string; cid: string}, Error, void>({
mutationFn: async () => {
@@ -106,7 +105,7 @@ export function useGenerateStarterPackMutation({
25,
true,
)
const starterPackName = `${displayName}'s ${starterPackString}`
const starterPackName = _(msg`${displayName}'s Starter Pack`)
const list = await createStarterPackList({
name: starterPackName,
+136 -25
View File
@@ -1,102 +1,213 @@
import {describe, expect, it} from '@jest/globals'
import {MessageDescriptor} from '@lingui/core'
import {addDays, subDays, subHours, subMinutes, subSeconds} from 'date-fns'
import {dateDiff} from '../useTimeAgo'
const lingui: any = (obj: MessageDescriptor) => obj.message
const base = new Date('2024-06-17T00:00:00Z')
describe('dateDiff', () => {
it(`works with numbers`, () => {
expect(dateDiff(subDays(base, 3), Number(base), {lingui})).toEqual('3d')
const earlier = subDays(base, 3)
expect(dateDiff(earlier, Number(base))).toEqual({
value: 3,
unit: 'day',
earlier,
later: base,
})
})
it(`works with strings`, () => {
expect(dateDiff(subDays(base, 3), base.toString(), {lingui})).toEqual('3d')
const earlier = subDays(base, 3)
expect(dateDiff(earlier, base.toString())).toEqual({
value: 3,
unit: 'day',
earlier,
later: base,
})
})
it(`works with dates`, () => {
expect(dateDiff(subDays(base, 3), base, {lingui})).toEqual('3d')
const earlier = subDays(base, 3)
expect(dateDiff(earlier, base)).toEqual({
value: 3,
unit: 'day',
earlier,
later: base,
})
})
it(`equal values return now`, () => {
expect(dateDiff(base, base, {lingui})).toEqual('now')
expect(dateDiff(base, base)).toEqual({
value: 0,
unit: 'now',
earlier: base,
later: base,
})
})
it(`future dates return now`, () => {
expect(dateDiff(addDays(base, 3), base, {lingui})).toEqual('now')
const earlier = addDays(base, 3)
expect(dateDiff(earlier, base)).toEqual({
value: 0,
unit: 'now',
earlier,
later: base,
})
})
it(`values < 5 seconds ago return now`, () => {
const then = subSeconds(base, 4)
expect(dateDiff(then, base, {lingui})).toEqual('now')
expect(dateDiff(then, base)).toEqual({
value: 0,
unit: 'now',
earlier: then,
later: base,
})
})
it(`values >= 5 seconds ago return seconds`, () => {
const then = subSeconds(base, 5)
expect(dateDiff(then, base, {lingui})).toEqual('5s')
expect(dateDiff(then, base)).toEqual({
value: 5,
unit: 'second',
earlier: then,
later: base,
})
})
it(`values < 1 min return seconds`, () => {
const then = subSeconds(base, 59)
expect(dateDiff(then, base, {lingui})).toEqual('59s')
expect(dateDiff(then, base)).toEqual({
value: 59,
unit: 'second',
earlier: then,
later: base,
})
})
it(`values >= 1 min return minutes`, () => {
const then = subSeconds(base, 60)
expect(dateDiff(then, base, {lingui})).toEqual('1m')
expect(dateDiff(then, base)).toEqual({
value: 1,
unit: 'minute',
earlier: then,
later: base,
})
})
it(`minutes round down`, () => {
const then = subSeconds(base, 119)
expect(dateDiff(then, base, {lingui})).toEqual('1m')
expect(dateDiff(then, base)).toEqual({
value: 1,
unit: 'minute',
earlier: then,
later: base,
})
})
it(`values < 1 hour return minutes`, () => {
const then = subMinutes(base, 59)
expect(dateDiff(then, base, {lingui})).toEqual('59m')
expect(dateDiff(then, base)).toEqual({
value: 59,
unit: 'minute',
earlier: then,
later: base,
})
})
it(`values >= 1 hour return hours`, () => {
const then = subMinutes(base, 60)
expect(dateDiff(then, base, {lingui})).toEqual('1h')
expect(dateDiff(then, base)).toEqual({
value: 1,
unit: 'hour',
earlier: then,
later: base,
})
})
it(`hours round down`, () => {
const then = subMinutes(base, 119)
expect(dateDiff(then, base, {lingui})).toEqual('1h')
expect(dateDiff(then, base)).toEqual({
value: 1,
unit: 'hour',
earlier: then,
later: base,
})
})
it(`values < 1 day return hours`, () => {
const then = subHours(base, 23)
expect(dateDiff(then, base, {lingui})).toEqual('23h')
expect(dateDiff(then, base)).toEqual({
value: 23,
unit: 'hour',
earlier: then,
later: base,
})
})
it(`values >= 1 day return days`, () => {
const then = subHours(base, 24)
expect(dateDiff(then, base, {lingui})).toEqual('1d')
expect(dateDiff(then, base)).toEqual({
value: 1,
unit: 'day',
earlier: then,
later: base,
})
})
it(`days round down`, () => {
const then = subHours(base, 47)
expect(dateDiff(then, base, {lingui})).toEqual('1d')
expect(dateDiff(then, base)).toEqual({
value: 1,
unit: 'day',
earlier: then,
later: base,
})
})
it(`values < 30 days return days`, () => {
const then = subDays(base, 29)
expect(dateDiff(then, base, {lingui})).toEqual('29d')
expect(dateDiff(then, base)).toEqual({
value: 29,
unit: 'day',
earlier: then,
later: base,
})
})
it(`values >= 30 days return months`, () => {
const then = subDays(base, 30)
expect(dateDiff(then, base, {lingui})).toEqual('1mo')
expect(dateDiff(then, base)).toEqual({
value: 1,
unit: 'month',
earlier: then,
later: base,
})
})
it(`months round down`, () => {
const then = subDays(base, 59)
expect(dateDiff(then, base, {lingui})).toEqual('1mo')
expect(dateDiff(then, base)).toEqual({
value: 1,
unit: 'month',
earlier: then,
later: base,
})
})
it(`values are rounded by increments of 30`, () => {
const then = subDays(base, 61)
expect(dateDiff(then, base, {lingui})).toEqual('2mo')
expect(dateDiff(then, base)).toEqual({
value: 2,
unit: 'month',
earlier: then,
later: base,
})
})
it(`values < 360 days return months`, () => {
const then = subDays(base, 359)
expect(dateDiff(then, base, {lingui})).toEqual('11mo')
expect(dateDiff(then, base)).toEqual({
value: 11,
unit: 'month',
earlier: then,
later: base,
})
})
it(`values >= 360 days return the earlier value`, () => {
const then = subDays(base, 360)
expect(dateDiff(then, base, {lingui})).toEqual(then.toLocaleDateString())
expect(dateDiff(then, base)).toEqual({
value: 12,
unit: 'month',
earlier: then,
later: base,
})
})
})
+6 -1
View File
@@ -15,5 +15,10 @@ export function useInitialNumToRender({
const finalHeight =
screenHeight - screenHeightOffset - topInset - bottomBarHeight
return Math.floor(finalHeight / minItemHeight) + 1
const minItems = Math.floor(finalHeight / minItemHeight)
if (minItems < 1) {
return 1
}
return minItems
}
+153 -61
View File
@@ -1,25 +1,16 @@
import {useCallback} from 'react'
import {msg, plural} from '@lingui/macro'
import {I18nContext, useLingui} from '@lingui/react'
import {I18n} from '@lingui/core'
import {defineMessage, msg, plural} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {differenceInSeconds} from 'date-fns'
export type TimeAgoOptions = {
lingui: I18nContext['_']
format?: 'long' | 'short'
}
export type DateDiffFormat = 'long' | 'short'
export function useGetTimeAgo() {
const {_} = useLingui()
return useCallback(
(
earlier: number | string | Date,
later: number | string | Date,
options?: Omit<TimeAgoOptions, 'lingui'>,
) => {
return dateDiff(earlier, later, {lingui: _, format: options?.format})
},
[_],
)
type DateDiff = {
value: number
unit: 'now' | 'second' | 'minute' | 'hour' | 'day' | 'month'
earlier: Date
later: Date
}
const NOW = 5
@@ -28,59 +19,160 @@ const HOUR = MINUTE * 60
const DAY = HOUR * 24
const MONTH_30 = DAY * 30
export function useGetTimeAgo() {
const {i18n} = useLingui()
return useCallback(
(
earlier: number | string | Date,
later: number | string | Date,
options?: {format: DateDiffFormat},
) => {
const diff = dateDiff(earlier, later)
return formatDateDiff({diff, i18n, format: options?.format})
},
[i18n],
)
}
/**
* Returns the difference between `earlier` and `later` dates, formatted as a
* natural language string.
* Returns the difference between `earlier` and `later` dates, based on
* opinionated rules.
*
* - All month are considered exactly 30 days.
* - Dates assume `earlier` <= `later`, and will otherwise return 'now'.
* - All values round down
*/
export function dateDiff(
earlier: number | string | Date,
later: number | string | Date,
): DateDiff {
let diff = {
value: 0,
unit: 'now' as DateDiff['unit'],
}
const e = new Date(earlier)
const l = new Date(later)
const diffSeconds = differenceInSeconds(l, e)
if (diffSeconds < NOW) {
diff = {
value: 0,
unit: 'now' as DateDiff['unit'],
}
} else if (diffSeconds < MINUTE) {
diff = {
value: diffSeconds,
unit: 'second' as DateDiff['unit'],
}
} else if (diffSeconds < HOUR) {
const value = Math.floor(diffSeconds / MINUTE)
diff = {
value,
unit: 'minute' as DateDiff['unit'],
}
} else if (diffSeconds < DAY) {
const value = Math.floor(diffSeconds / HOUR)
diff = {
value,
unit: 'hour' as DateDiff['unit'],
}
} else if (diffSeconds < MONTH_30) {
const value = Math.floor(diffSeconds / DAY)
diff = {
value,
unit: 'day' as DateDiff['unit'],
}
} else {
const value = Math.floor(diffSeconds / MONTH_30)
diff = {
value,
unit: 'month' as DateDiff['unit'],
}
}
return {
...diff,
earlier: e,
later: l,
}
}
/**
* Accepts a `DateDiff` and teturns the difference between `earlier` and
* `later` dates, formatted as a natural language string.
*
* - All month are considered exactly 30 days.
* - Dates assume `earlier` <= `later`, and will otherwise return 'now'.
* - Differences >= 360 days are returned as the "M/D/YYYY" string
* - All values round down
*/
export function dateDiff(
earlier: number | string | Date,
later: number | string | Date,
options: TimeAgoOptions,
): string {
const _ = options.lingui
const format = options?.format || 'short'
export function formatDateDiff({
diff,
format = 'short',
i18n,
}: {
diff: DateDiff
format?: DateDiffFormat
i18n: I18n
}): string {
const long = format === 'long'
const diffSeconds = differenceInSeconds(new Date(later), new Date(earlier))
if (diffSeconds < NOW) {
return _(msg`now`)
} else if (diffSeconds < MINUTE) {
return `${diffSeconds}${
long ? ` ${plural(diffSeconds, {one: 'second', other: 'seconds'})}` : 's'
}`
} else if (diffSeconds < HOUR) {
const diff = Math.floor(diffSeconds / MINUTE)
return `${diff}${
long ? ` ${plural(diff, {one: 'minute', other: 'minutes'})}` : 'm'
}`
} else if (diffSeconds < DAY) {
const diff = Math.floor(diffSeconds / HOUR)
return `${diff}${
long ? ` ${plural(diff, {one: 'hour', other: 'hours'})}` : 'h'
}`
} else if (diffSeconds < MONTH_30) {
const diff = Math.floor(diffSeconds / DAY)
return `${diff}${
long ? ` ${plural(diff, {one: 'day', other: 'days'})}` : 'd'
}`
} else {
const diff = Math.floor(diffSeconds / MONTH_30)
if (diff < 12) {
return `${diff}${
long ? ` ${plural(diff, {one: 'month', other: 'months'})}` : 'mo'
}`
} else {
const str = new Date(earlier).toLocaleDateString()
if (long) {
return _(msg`on ${str}`)
switch (diff.unit) {
case 'now': {
return i18n._(msg`now`)
}
case 'second': {
return long
? i18n._(plural(diff.value, {one: '# second', other: '# seconds'}))
: i18n._(
defineMessage({
message: `${diff.value}s`,
comment: `How many seconds have passed, displayed in a narrow form`,
}),
)
}
case 'minute': {
return long
? i18n._(plural(diff.value, {one: '# minute', other: '# minutes'}))
: i18n._(
defineMessage({
message: `${diff.value}m`,
comment: `How many minutes have passed, displayed in a narrow form`,
}),
)
}
case 'hour': {
return long
? i18n._(plural(diff.value, {one: '# hour', other: '# hours'}))
: i18n._(
defineMessage({
message: `${diff.value}h`,
comment: `How many hours have passed, displayed in a narrow form`,
}),
)
}
case 'day': {
return long
? i18n._(plural(diff.value, {one: '# day', other: '# days'}))
: i18n._(
defineMessage({
message: `${diff.value}d`,
comment: `How many days have passed, displayed in a narrow form`,
}),
)
}
case 'month': {
if (diff.value < 12) {
return long
? i18n._(plural(diff.value, {one: '# month', other: '# months'}))
: i18n._(
defineMessage({
message: `${diff.value}mo`,
comment: `How many months have passed, displayed in a narrow form`,
}),
)
}
return str
return i18n.date(new Date(diff.earlier))
}
}
}
+1 -4
View File
@@ -1,9 +1,6 @@
import {getVideoMetaData, Video} from 'react-native-compressor'
export type CompressedVideo = {
uri: string
size: number
}
import {CompressedVideo} from './types'
export async function compressVideo(
file: string,
+33 -8
View File
@@ -1,12 +1,8 @@
import {VideoTooLargeError} from 'lib/media/video/errors'
import {CompressedVideo} from './types'
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,
@@ -15,8 +11,9 @@ export async function compressVideo(
onProgress?: (progress: number) => void
},
): Promise<CompressedVideo> {
const blob = await fetch(file).then(res => res.blob())
const video = URL.createObjectURL(blob)
const {mimeType, base64} = parseDataUrl(file)
const blob = base64ToBlob(base64, mimeType)
const uri = URL.createObjectURL(blob)
if (blob.size > MAX_VIDEO_SIZE) {
throw new VideoTooLargeError()
@@ -24,6 +21,34 @@ export async function compressVideo(
return {
size: blob.size,
uri: video,
uri,
bytes: await blob.arrayBuffer(),
}
}
function parseDataUrl(dataUrl: string) {
const [mimeType, base64] = dataUrl.slice('data:'.length).split(';base64,')
if (!mimeType || !base64) {
throw new Error('Invalid data URL')
}
return {mimeType, base64}
}
function base64ToBlob(base64: string, mimeType: string) {
const byteCharacters = atob(base64)
const byteArrays = []
for (let offset = 0; offset < byteCharacters.length; offset += 512) {
const slice = byteCharacters.slice(offset, offset + 512)
const byteNumbers = new Array(slice.length)
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i)
}
const byteArray = new Uint8Array(byteNumbers)
byteArrays.push(byteArray)
}
return new Blob(byteArrays, {type: mimeType})
}
+6
View File
@@ -0,0 +1,6 @@
export type CompressedVideo = {
uri: string
size: number
// web only, can fall back to uri if missing
bytes?: ArrayBuffer
}
+3 -3
View File
@@ -1,9 +1,9 @@
import {
ComAtprotoLabelDefs,
AppBskyLabelerDefs,
LABELS,
interpretLabelValueDefinition,
ComAtprotoLabelDefs,
InterpretedLabelValueDefinition,
interpretLabelValueDefinition,
LABELS,
} from '@atproto/api'
import {useLingui} from '@lingui/react'
import * as bcp47Match from 'bcp-47-match'
+4 -2
View File
@@ -4,5 +4,7 @@ export type Gate =
| 'fixed_bottom_bar'
| 'onboarding_minimum_interests'
| 'suggested_feeds_interstitial'
| 'video_debug'
| 'videos'
| 'show_follow_suggestions_in_profile'
| 'video_debug' // not recommended
| 'video_upload' // upload videos
| 'video_view_on_posts' // see posted videos
+18
View File
@@ -1,3 +1,6 @@
import {useCallback, useMemo} from 'react'
import Graphemer from 'graphemer'
export function enforceLen(
str: string,
len: number,
@@ -23,6 +26,21 @@ export function enforceLen(
return str
}
export function useEnforceMaxGraphemeCount() {
const splitter = useMemo(() => new Graphemer(), [])
return useCallback(
(text: string, maxCount: number) => {
if (splitter.countGraphemes(text) > maxCount) {
return splitter.splitGraphemes(text).slice(0, maxCount).join('')
} else {
return text
}
},
[splitter],
)
}
// https://stackoverflow.com/a/52171480
export function toHashCode(str: string, seed = 0): number {
let h1 = 0xdeadbeef ^ seed,
+8 -9
View File
@@ -1,13 +1,12 @@
export function niceDate(date: number | string | Date) {
import {I18n} from '@lingui/core'
export function niceDate(i18n: I18n, date: number | string | Date) {
const d = new Date(date)
return `${d.toLocaleDateString('en-us', {
year: 'numeric',
month: 'short',
day: 'numeric',
})} at ${d.toLocaleTimeString(undefined, {
hour: 'numeric',
minute: '2-digit',
})}`
return i18n.date(d, {
dateStyle: 'long',
timeStyle: 'short',
})
}
export function getAge(birthDate: Date): number {
+2 -2
View File
@@ -340,7 +340,7 @@ export function shortLinkToHref(url: string): string {
}
}
export function getHostnameFromUrl(url: string): string | null {
export function getHostnameFromUrl(url: string | URL): string | null {
let urlp
try {
urlp = new URL(url)
@@ -350,7 +350,7 @@ export function getHostnameFromUrl(url: string): string | null {
return urlp.hostname
}
export function getServiceAuthAudFromUrl(url: string): string | null {
export function getServiceAuthAudFromUrl(url: string | URL): string | null {
const hostname = getHostnameFromUrl(url)
if (!hostname) {
return null
File diff suppressed because it is too large Load Diff
+7 -4
View File
@@ -1,5 +1,4 @@
import React from 'react'
import {View} from 'react-native'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useFocusEffect} from '@react-navigation/native'
@@ -7,9 +6,12 @@ import {useFocusEffect} from '@react-navigation/native'
import {CommonNavigatorParams, NativeStackScreenProps} from '#/lib/routes/types'
import {makeRecordUri} from '#/lib/strings/url-helpers'
import {useSetMinimalShellMode} from '#/state/shell'
import {isWeb} from 'platform/detection'
import {PostLikedBy as PostLikedByComponent} from '#/view/com/post-thread/PostLikedBy'
import {ViewHeader} from '#/view/com/util/ViewHeader'
import {CenteredView} from 'view/com/util/Views'
import {atoms as a} from '#/alf'
import {ListHeaderDesktop} from '#/components/Lists'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'PostLikedBy'>
export const PostLikedByScreen = ({route}: Props) => {
@@ -25,9 +27,10 @@ export const PostLikedByScreen = ({route}: Props) => {
)
return (
<View style={a.flex_1}>
<ViewHeader title={_(msg`Liked By`)} />
<CenteredView style={a.h_full_vh} sideBorders={true}>
<ListHeaderDesktop title={_(msg`Liked By`)} />
<ViewHeader title={_(msg`Liked By`)} showBorder={!isWeb} />
<PostLikedByComponent uri={uri} />
</View>
</CenteredView>
)
}
+7 -4
View File
@@ -1,5 +1,4 @@
import React from 'react'
import {View} from 'react-native'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useFocusEffect} from '@react-navigation/native'
@@ -7,9 +6,12 @@ import {useFocusEffect} from '@react-navigation/native'
import {CommonNavigatorParams, NativeStackScreenProps} from '#/lib/routes/types'
import {makeRecordUri} from '#/lib/strings/url-helpers'
import {useSetMinimalShellMode} from '#/state/shell'
import {isWeb} from 'platform/detection'
import {PostQuotes as PostQuotesComponent} from '#/view/com/post-thread/PostQuotes'
import {ViewHeader} from '#/view/com/util/ViewHeader'
import {CenteredView} from 'view/com/util/Views'
import {atoms as a} from '#/alf'
import {ListHeaderDesktop} from '#/components/Lists'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'PostQuotes'>
export const PostQuotesScreen = ({route}: Props) => {
@@ -25,9 +27,10 @@ export const PostQuotesScreen = ({route}: Props) => {
)
return (
<View style={a.flex_1}>
<ViewHeader title={_(msg`Quotes`)} />
<CenteredView style={a.h_full_vh} sideBorders={true}>
<ListHeaderDesktop title={_(msg`Quotes`)} />
<ViewHeader title={_(msg`Quotes`)} showBorder={!isWeb} />
<PostQuotesComponent uri={uri} />
</View>
</CenteredView>
)
}
+7 -4
View File
@@ -1,5 +1,4 @@
import React from 'react'
import {View} from 'react-native'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useFocusEffect} from '@react-navigation/native'
@@ -7,9 +6,12 @@ import {useFocusEffect} from '@react-navigation/native'
import {CommonNavigatorParams, NativeStackScreenProps} from '#/lib/routes/types'
import {makeRecordUri} from '#/lib/strings/url-helpers'
import {useSetMinimalShellMode} from '#/state/shell'
import {isWeb} from 'platform/detection'
import {PostRepostedBy as PostRepostedByComponent} from '#/view/com/post-thread/PostRepostedBy'
import {ViewHeader} from '#/view/com/util/ViewHeader'
import {CenteredView} from 'view/com/util/Views'
import {atoms as a} from '#/alf'
import {ListHeaderDesktop} from '#/components/Lists'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'PostRepostedBy'>
export const PostRepostedByScreen = ({route}: Props) => {
@@ -25,9 +27,10 @@ export const PostRepostedByScreen = ({route}: Props) => {
)
return (
<View style={a.flex_1}>
<ViewHeader title={_(msg`Reposted By`)} />
<CenteredView style={a.h_full_vh} sideBorders={true}>
<ListHeaderDesktop title={_(msg`Reposted By`)} />
<ViewHeader title={_(msg`Reposted By`)} showBorder={!isWeb} />
<PostRepostedByComponent uri={uri} />
</View>
</CenteredView>
)
}
+4 -4
View File
@@ -17,9 +17,9 @@ export function ProfileHeaderMetrics({
profile: Shadow<AppBskyActorDefs.ProfileViewDetailed>
}) {
const t = useTheme()
const {_} = useLingui()
const following = formatCount(profile.followsCount || 0)
const followers = formatCount(profile.followersCount || 0)
const {_, i18n} = useLingui()
const following = formatCount(i18n, profile.followsCount || 0)
const followers = formatCount(i18n, profile.followersCount || 0)
const pluralizedFollowers = plural(profile.followersCount || 0, {
one: 'follower',
other: 'followers',
@@ -54,7 +54,7 @@ export function ProfileHeaderMetrics({
</Text>
</InlineLinkText>
<Text style={[a.font_bold, t.atoms.text, a.text_md]}>
{formatCount(profile.postsCount || 0)}{' '}
{formatCount(i18n, profile.postsCount || 0)}{' '}
<Text style={[t.atoms.text_contrast_medium, a.font_normal, a.text_md]}>
{plural(profile.postsCount || 0, {one: 'post', other: 'posts'})}
</Text>
@@ -10,6 +10,7 @@ import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useGate} from '#/lib/statsig/statsig'
import {logger} from '#/logger'
import {isIOS} from '#/platform/detection'
import {Shadow} from '#/state/cache/types'
@@ -59,6 +60,7 @@ let ProfileHeaderStandard = ({
const profile: Shadow<AppBskyActorDefs.ProfileViewDetailed> =
useProfileShadow(profileUnshadowed)
const t = useTheme()
const gate = useGate()
const {currentAccount, hasSession} = useSession()
const {_} = useLingui()
const {openModal} = useModalControls()
@@ -203,27 +205,29 @@ let ProfileHeaderStandard = ({
{hasSession && (
<>
<MessageProfileButton profile={profile} />
<Button
testID="suggestedFollowsBtn"
size="small"
color={showSuggestedFollows ? 'primary' : 'secondary'}
variant="solid"
shape="round"
onPress={() =>
setShowSuggestedFollows(!showSuggestedFollows)
}
label={_(msg`Show follows similar to ${profile.handle}`)}
style={{width: 36, height: 36}}>
<FontAwesomeIcon
icon="user-plus"
style={
showSuggestedFollows
? {color: t.palette.white}
: t.atoms.text
{!gate('show_follow_suggestions_in_profile') && (
<Button
testID="suggestedFollowsBtn"
size="small"
color={showSuggestedFollows ? 'primary' : 'secondary'}
variant="solid"
shape="round"
onPress={() =>
setShowSuggestedFollows(!showSuggestedFollows)
}
size={14}
/>
</Button>
label={_(msg`Show follows similar to ${profile.handle}`)}
style={{width: 36, height: 36}}>
<FontAwesomeIcon
icon="user-plus"
style={
showSuggestedFollows
? {color: t.palette.white}
: t.atoms.text
}
size={14}
/>
</Button>
)}
</>
)}
@@ -113,7 +113,7 @@ function LandingScreenLoaded({
moderationOpts: ModerationOpts
}) {
const {creator, listItemsSample, feeds} = starterPack
const {_} = useLingui()
const {_, i18n} = useLingui()
const t = useTheme()
const activeStarterPack = useActiveStarterPack()
const setActiveStarterPack = useSetActiveStarterPack()
@@ -225,7 +225,9 @@ function LandingScreenLoaded({
t.atoms.text_contrast_medium,
]}
numberOfLines={1}>
<Trans>{formatCount(JOINED_THIS_WEEK)} joined this week</Trans>
<Trans>
{formatCount(i18n, JOINED_THIS_WEEK)} joined this week
</Trans>
</Text>
</View>
</View>
+2 -1
View File
@@ -2,7 +2,8 @@ import {ImagePickerAsset} from 'expo-image-picker'
import {useMutation} from '@tanstack/react-query'
import {cancelable} from '#/lib/async/cancelable'
import {CompressedVideo, compressVideo} from 'lib/media/video/compress'
import {CompressedVideo} from '#/lib/media/video/types'
import {compressVideo} from 'lib/media/video/compress'
export function useCompressVideoMutation({
onProgress,
+4 -6
View File
@@ -4,7 +4,7 @@ import {useMutation} from '@tanstack/react-query'
import {nanoid} from 'nanoid/non-secure'
import {cancelable} from '#/lib/async/cancelable'
import {CompressedVideo} from '#/lib/media/video/compress'
import {CompressedVideo} from '#/lib/media/video/types'
import {createVideoEndpointUrl} from '#/state/queries/video/util'
import {useAgent, useSession} from '#/state/session'
import {getServiceAuthAudFromUrl} from 'lib/strings/url-helpers'
@@ -28,14 +28,11 @@ export const useUploadVideoMutation = ({
mutationFn: cancelable(async (video: CompressedVideo) => {
const uri = createVideoEndpointUrl('/xrpc/app.bsky.video.uploadVideo', {
did: currentAccount!.did,
name: `${nanoid(12)}.mp4`, // @TODO what are we limiting this to?
name: `${nanoid(12)}.mp4`,
})
if (!currentAccount?.service) {
throw new Error('User is not logged in')
}
const serviceAuthAud = getServiceAuthAudFromUrl(agent.dispatchUrl)
const serviceAuthAud = getServiceAuthAudFromUrl(currentAccount.service)
if (!serviceAuthAud) {
throw new Error('Agent does not have a PDS URL')
}
@@ -44,6 +41,7 @@ export const useUploadVideoMutation = ({
{
aud: serviceAuthAud,
lxm: 'com.atproto.repo.uploadBlob',
exp: Date.now() / 1000 + 60 * 30, // 30 minutes
},
)
+8 -6
View File
@@ -3,7 +3,7 @@ import {useMutation} from '@tanstack/react-query'
import {nanoid} from 'nanoid/non-secure'
import {cancelable} from '#/lib/async/cancelable'
import {CompressedVideo} from '#/lib/media/video/compress'
import {CompressedVideo} from '#/lib/media/video/types'
import {createVideoEndpointUrl} from '#/state/queries/video/util'
import {useAgent, useSession} from '#/state/session'
import {getServiceAuthAudFromUrl} from 'lib/strings/url-helpers'
@@ -30,11 +30,8 @@ export const useUploadVideoMutation = ({
name: `${nanoid(12)}.mp4`, // @TODO: make sure it's always mp4'
})
if (!currentAccount?.service) {
throw new Error('User is not logged in')
}
const serviceAuthAud = getServiceAuthAudFromUrl(agent.dispatchUrl)
const serviceAuthAud = getServiceAuthAudFromUrl(currentAccount.service)
if (!serviceAuthAud) {
throw new Error('Agent does not have a PDS URL')
}
@@ -43,10 +40,15 @@ export const useUploadVideoMutation = ({
{
aud: serviceAuthAud,
lxm: 'com.atproto.repo.uploadBlob',
exp: Date.now() / 1000 + 60 * 30, // 30 minutes
},
)
const bytes = await fetch(video.uri).then(res => res.arrayBuffer())
let bytes = video.bytes
if (!bytes) {
bytes = await fetch(video.uri).then(res => res.arrayBuffer())
}
const xhr = new XMLHttpRequest()
const res = await new Promise<AppBskyVideoDefs.JobStatus>(
+19 -2
View File
@@ -1,4 +1,4 @@
import React from 'react'
import React, {useCallback} from 'react'
import {ImagePickerAsset} from 'expo-image-picker'
import {AppBskyVideoDefs, BlobRef} from '@atproto/api'
import {msg} from '@lingui/macro'
@@ -6,8 +6,8 @@ import {useLingui} from '@lingui/react'
import {QueryClient, useQuery, useQueryClient} from '@tanstack/react-query'
import {logger} from '#/logger'
import {CompressedVideo} from 'lib/media/video/compress'
import {VideoTooLargeError} from 'lib/media/video/errors'
import {CompressedVideo} from 'lib/media/video/types'
import {useCompressVideoMutation} from 'state/queries/video/compress-video'
import {useVideoAgent} from 'state/queries/video/util'
import {useUploadVideoMutation} from 'state/queries/video/video-upload'
@@ -20,6 +20,7 @@ type Action =
| {type: 'SetError'; error: string | undefined}
| {type: 'Reset'}
| {type: 'SetAsset'; asset: ImagePickerAsset}
| {type: 'SetDimensions'; width: number; height: number}
| {type: 'SetVideo'; video: CompressedVideo}
| {type: 'SetJobStatus'; jobStatus: AppBskyVideoDefs.JobStatus}
| {type: 'SetBlobRef'; blobRef: BlobRef}
@@ -58,6 +59,13 @@ function reducer(queryClient: QueryClient) {
}
} else if (action.type === 'SetAsset') {
updatedState = {...state, asset: action.asset}
} else if (action.type === 'SetDimensions') {
updatedState = {
...state,
asset: state.asset
? {...state.asset, width: action.width, height: action.height}
: undefined,
}
} else if (action.type === 'SetVideo') {
updatedState = {...state, video: action.video}
} else if (action.type === 'SetJobStatus') {
@@ -178,11 +186,20 @@ export function useUploadVideo({
dispatch({type: 'Reset'})
}
const updateVideoDimensions = useCallback((width: number, height: number) => {
dispatch({
type: 'SetDimensions',
width,
height,
})
}, [])
return {
state,
dispatch,
selectVideo,
clearVideo,
updateVideoDimensions,
}
}
+20 -7
View File
@@ -5,8 +5,11 @@ import {
AppBskyRichtextFacet,
ModerationDecision,
} from '@atproto/api'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback'
import * as Toast from '#/view/com/util/Toast'
export interface ComposerOptsPostRef {
uri: string
@@ -22,12 +25,7 @@ export interface ComposerOptsQuote {
text: string
facets?: AppBskyRichtextFacet.Main[]
indexedAt: string
author: {
did: string
handle: string
displayName?: string
avatar?: string
}
author: AppBskyActorDefs.ProfileViewBasic
embeds?: AppBskyEmbedRecord.ViewRecord['embeds']
}
export interface ComposerOpts {
@@ -56,10 +54,25 @@ const controlsContext = React.createContext<ControlsContext>({
})
export function Provider({children}: React.PropsWithChildren<{}>) {
const {_} = useLingui()
const [state, setState] = React.useState<StateContext>()
const openComposer = useNonReactiveCallback((opts: ComposerOpts) => {
setState(opts)
const author = opts.replyTo?.author || opts.quote?.author
const isBlocked = Boolean(
author &&
(author.viewer?.blocking ||
author.viewer?.blockedBy ||
author.viewer?.blockingByList),
)
if (isBlocked) {
Toast.show(
_(msg`Cannot interact with a blocked user`),
'exclamation-circle',
)
} else {
setState(opts)
}
})
const closeComposer = useNonReactiveCallback(() => {
+41 -11
View File
@@ -108,6 +108,7 @@ import {TextInput, TextInputRef} from './text-input/TextInput'
import {ThreadgateBtn} from './threadgate/ThreadgateBtn'
import {useExternalLinkFetch} from './useExternalLinkFetch'
import {SelectVideoBtn} from './videos/SelectVideoBtn'
import {SubtitleDialogBtn} from './videos/SubtitleDialog'
import {VideoPreview} from './videos/VideoPreview'
import {VideoTranscodeProgress} from './videos/VideoTranscodeProgress'
@@ -172,10 +173,14 @@ export const ComposePost = observer(function ComposePost({
initQuote,
)
const [videoAltText, setVideoAltText] = useState('')
const [captions, setCaptions] = useState<{lang: string; file: File}[]>([])
const {
selectVideo,
clearVideo,
state: videoUploadState,
updateVideoDimensions,
} = useUploadVideo({
setStatus: setProcessingState,
onSuccess: () => {
@@ -347,7 +352,19 @@ export const ComposePost = observer(function ComposePost({
postgate,
onStateChange: setProcessingState,
langs: toPostLanguages(langPrefs.postLanguage),
video: videoUploadState.blobRef,
video: videoUploadState.blobRef
? {
blobRef: videoUploadState.blobRef,
altText: videoAltText,
captions: captions,
aspectRatio: videoUploadState.asset
? {
width: videoUploadState.asset?.width,
height: videoUploadState.asset?.height,
}
: undefined,
}
: undefined,
})
).uri
try {
@@ -694,16 +711,29 @@ export const ComposePost = observer(function ComposePost({
)}
</View>
) : null}
{videoUploadState.status === 'compressing' &&
videoUploadState.asset ? (
<VideoTranscodeProgress
asset={videoUploadState.asset}
progress={videoUploadState.progress}
clear={clearVideo}
{videoUploadState.asset &&
(videoUploadState.status === 'compressing' ? (
<VideoTranscodeProgress
asset={videoUploadState.asset}
progress={videoUploadState.progress}
clear={clearVideo}
/>
) : videoUploadState.video ? (
<VideoPreview
asset={videoUploadState.asset}
video={videoUploadState.video}
setDimensions={updateVideoDimensions}
clear={clearVideo}
/>
) : null)}
{(videoUploadState.asset || videoUploadState.video) && (
<SubtitleDialogBtn
altText={videoAltText}
setAltText={setVideoAltText}
captions={captions}
setCaptions={setCaptions}
/>
) : videoUploadState.video ? (
<VideoPreview video={videoUploadState.video} clear={clearVideo} />
) : null}
)}
</View>
</Animated.ScrollView>
<SuggestedLanguage text={richtext.text} />
@@ -730,7 +760,7 @@ export const ComposePost = observer(function ComposePost({
) : (
<ToolbarWrapper style={[a.flex_row, a.align_center, a.gap_xs]}>
<SelectPhotoBtn gallery={gallery} disabled={!canSelectImages} />
{gate('videos') && (
{gate('video_upload') && (
<SelectVideoBtn
onSelectVideo={selectVideo}
disabled={!canSelectImages}
@@ -0,0 +1,265 @@
import React, {useCallback} from 'react'
import {StyleProp, View, ViewStyle} from 'react-native'
import RNPickerSelect from 'react-native-picker-select'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {MAX_ALT_TEXT} from '#/lib/constants'
import {useEnforceMaxGraphemeCount} from '#/lib/strings/helpers'
import {LANGUAGES} from '#/locale/languages'
import {isWeb} from '#/platform/detection'
import {useLanguagePrefs} from '#/state/preferences'
import {atoms as a, useTheme, web} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import * as Dialog from '#/components/Dialog'
import * as TextField from '#/components/forms/TextField'
import {CC_Stroke2_Corner0_Rounded as CCIcon} from '#/components/icons/CC'
import {PageText_Stroke2_Corner0_Rounded as PageTextIcon} from '#/components/icons/PageText'
import {TimesLarge_Stroke2_Corner0_Rounded as X} from '#/components/icons/Times'
import {Warning_Stroke2_Corner0_Rounded as WarningIcon} from '#/components/icons/Warning'
import {Text} from '#/components/Typography'
import {SubtitleFilePicker} from './SubtitleFilePicker'
interface Props {
altText: string
captions: {lang: string; file: File}[]
setAltText: (altText: string) => void
setCaptions: React.Dispatch<
React.SetStateAction<{lang: string; file: File}[]>
>
}
export function SubtitleDialogBtn(props: Props) {
const control = Dialog.useDialogControl()
const {_} = useLingui()
return (
<View style={[a.flex_row, a.mt_xs]}>
<Button
label={isWeb ? _('Captions & alt text') : _('Alt text')}
accessibilityHint={
isWeb
? _('Opens captions and alt text dialog')
: _('Opens alt text dialog')
}
size="xsmall"
color="secondary"
variant="ghost"
onPress={control.open}>
<ButtonIcon icon={CCIcon} />
<ButtonText>
{isWeb ? <Trans>Captions & alt text</Trans> : <Trans>Alt text</Trans>}
</ButtonText>
</Button>
<Dialog.Outer control={control}>
<Dialog.Handle />
<SubtitleDialogInner {...props} />
</Dialog.Outer>
</View>
)
}
function SubtitleDialogInner({
altText,
setAltText,
captions,
setCaptions,
}: Props) {
const control = Dialog.useDialogContext()
const {_} = useLingui()
const t = useTheme()
const enforceLen = useEnforceMaxGraphemeCount()
const {primaryLanguage} = useLanguagePrefs()
const handleSelectFile = useCallback(
(file: File) => {
setCaptions(subs => [
...subs,
{
lang: subs.some(s => s.lang === primaryLanguage)
? ''
: primaryLanguage,
file,
},
])
},
[setCaptions, primaryLanguage],
)
const subtitleMissingLanguage = captions.some(sub => sub.lang === '')
return (
<Dialog.ScrollableInner label={_(msg`Video settings`)}>
<View style={a.gap_md}>
<Text style={[a.text_xl, a.font_bold, a.leading_tight]}>
<Trans>Alt text</Trans>
</Text>
<TextField.Root>
<Dialog.Input
label={_(msg`Alt text`)}
placeholder={_(msg`Add alt text (optional)`)}
value={altText}
onChangeText={evt => setAltText(enforceLen(evt, MAX_ALT_TEXT))}
maxLength={MAX_ALT_TEXT * 10}
multiline
numberOfLines={3}
onKeyPress={({nativeEvent}) => {
if (nativeEvent.key === 'Escape') {
control.close()
}
}}
/>
</TextField.Root>
{isWeb && (
<>
<View
style={[
a.border_t,
a.w_full,
t.atoms.border_contrast_medium,
a.my_md,
]}
/>
<Text style={[a.text_xl, a.font_bold, a.leading_tight]}>
<Trans>Captions (.vtt)</Trans>
</Text>
<SubtitleFilePicker
onSelectFile={handleSelectFile}
disabled={subtitleMissingLanguage || captions.length >= 4}
/>
<View>
{captions.map((subtitle, i) => (
<SubtitleFileRow
key={subtitle.lang}
language={subtitle.lang}
file={subtitle.file}
setCaptions={setCaptions}
otherLanguages={LANGUAGES.filter(
lang =>
langCode(lang) === subtitle.lang ||
!captions.some(s => s.lang === langCode(lang)),
)}
style={[i % 2 === 0 && t.atoms.bg_contrast_25]}
/>
))}
</View>
</>
)}
{subtitleMissingLanguage && (
<Text style={[a.text_sm, t.atoms.text_contrast_medium]}>
Ensure you have selected a language for each subtitle file.
</Text>
)}
<View style={web([a.flex_row, a.justify_end])}>
<Button
label={_(msg`Done`)}
size={isWeb ? 'small' : 'medium'}
color="primary"
variant="solid"
onPress={() => control.close()}
style={a.mt_lg}>
<ButtonText>
<Trans>Done</Trans>
</ButtonText>
</Button>
</View>
</View>
<Dialog.Close />
</Dialog.ScrollableInner>
)
}
function SubtitleFileRow({
language,
file,
otherLanguages,
setCaptions,
style,
}: {
language: string
file: File
otherLanguages: {code2: string; code3: string; name: string}[]
setCaptions: React.Dispatch<
React.SetStateAction<{lang: string; file: File}[]>
>
style: StyleProp<ViewStyle>
}) {
const {_} = useLingui()
const t = useTheme()
const handleValueChange = useCallback(
(lang: string) => {
if (lang) {
setCaptions(subs =>
subs.map(s => (s.lang === language ? {lang, file: s.file} : s)),
)
}
},
[setCaptions, language],
)
return (
<View
style={[
a.flex_row,
a.justify_between,
a.py_md,
a.px_lg,
a.rounded_md,
a.gap_md,
style,
]}>
<View style={[a.flex_1, a.gap_xs, a.justify_center]}>
<View style={[a.flex_row, a.align_center, a.gap_sm]}>
{language === '' ? (
<WarningIcon
style={a.flex_shrink_0}
fill={t.palette.negative_500}
size="sm"
/>
) : (
<PageTextIcon style={[t.atoms.text, a.flex_shrink_0]} size="sm" />
)}
<Text
style={[a.flex_1, a.leading_snug, a.font_bold, a.mb_2xs]}
numberOfLines={1}>
{file.name}
</Text>
<RNPickerSelect
placeholder={{
label: _(msg`Select language...`),
value: '',
}}
value={language}
onValueChange={handleValueChange}
items={otherLanguages.map(lang => ({
label: `${lang.name} (${langCode(lang)})`,
value: langCode(lang),
}))}
style={{viewContainer: {maxWidth: 200, flex: 1}}}
/>
</View>
</View>
<Button
label={_(msg`Remove subtitle file`)}
size="tiny"
shape="round"
variant="outline"
color="secondary"
onPress={() =>
setCaptions(subs => subs.filter(s => s.lang !== language))
}
style={[a.ml_sm]}>
<ButtonIcon icon={X} />
</Button>
</View>
)
}
function langCode(lang: {code2: string; code3: string}) {
return lang.code2 || lang.code3
}
@@ -0,0 +1,3 @@
export function SubtitleFilePicker() {
throw new Error('SubtitleFilePicker is a web-only component')
}
@@ -0,0 +1,63 @@
import React, {useRef} from 'react'
import {View} from 'react-native'
import {msg, Trans} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import * as Toast from '#/view/com/util/Toast'
import {atoms as a} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button'
import {CC_Stroke2_Corner0_Rounded as CCIcon} from '#/components/icons/CC'
export function SubtitleFilePicker({
onSelectFile,
disabled,
}: {
onSelectFile: (file: File) => void
disabled?: boolean
}) {
const {_} = useLingui()
const ref = useRef<HTMLInputElement>(null)
const handleClick = () => {
ref.current?.click()
}
const handlePick = (evt: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = evt.target.files?.[0]
if (selectedFile) {
if (selectedFile.type === 'text/vtt') {
onSelectFile(selectedFile)
} else {
Toast.show(_(msg`Only WebVTT (.vtt) files are supported`))
}
}
}
return (
<View style={a.gap_lg}>
<input
type="file"
accept=".vtt"
ref={ref}
style={a.hidden}
onChange={handlePick}
disabled={disabled}
aria-disabled={disabled}
/>
<View style={a.flex_row}>
<Button
onPress={handleClick}
label={_('Select subtitle file (.vtt)')}
size="medium"
color="primary"
variant="solid"
disabled={disabled}>
<ButtonIcon icon={CCIcon} />
<ButtonText>
<Trans>Select subtitle file (.vtt)</Trans>
</ButtonText>
</Button>
</View>
</View>
)
}
+21 -3
View File
@@ -1,38 +1,56 @@
/* eslint-disable @typescript-eslint/no-shadow */
import React from 'react'
import {View} from 'react-native'
import {ImagePickerAsset} from 'expo-image-picker'
import {useVideoPlayer, VideoView} from 'expo-video'
import {CompressedVideo} from '#/lib/media/video/compress'
import {CompressedVideo} from '#/lib/media/video/types'
import {clamp} from '#/lib/numbers'
import {ExternalEmbedRemoveBtn} from 'view/com/composer/ExternalEmbedRemoveBtn'
import {atoms as a} from '#/alf'
import {atoms as a, useTheme} from '#/alf'
export function VideoPreview({
asset,
video,
clear,
}: {
asset: ImagePickerAsset
video: CompressedVideo
setDimensions: (width: number, height: number) => void
clear: () => void
}) {
const t = useTheme()
const player = useVideoPlayer(video.uri, player => {
player.loop = true
player.muted = true
player.play()
})
let aspectRatio = asset.width / asset.height
if (isNaN(aspectRatio)) {
aspectRatio = 16 / 9
}
aspectRatio = clamp(aspectRatio, 1 / 1, 3 / 1)
return (
<View
style={[
a.w_full,
a.rounded_sm,
{aspectRatio: 16 / 9},
{aspectRatio},
a.overflow_hidden,
a.border,
t.atoms.border_contrast_low,
{backgroundColor: 'black'},
]}>
<VideoView
player={player}
style={a.flex_1}
allowsPictureInPicture={false}
nativeControls={false}
contentFit="contain"
/>
<ExternalEmbedRemoveBtn onRemove={clear} />
</View>
@@ -1,27 +1,70 @@
import React from 'react'
import React, {useEffect, useRef} from 'react'
import {View} from 'react-native'
import {ImagePickerAsset} from 'expo-image-picker'
import {CompressedVideo} from '#/lib/media/video/compress'
import {CompressedVideo} from '#/lib/media/video/types'
import {clamp} from '#/lib/numbers'
import {ExternalEmbedRemoveBtn} from 'view/com/composer/ExternalEmbedRemoveBtn'
import {atoms as a} from '#/alf'
export function VideoPreview({
asset,
video,
setDimensions,
clear,
}: {
asset: ImagePickerAsset
video: CompressedVideo
setDimensions: (width: number, height: number) => void
clear: () => void
}) {
const ref = useRef<HTMLVideoElement>(null)
useEffect(() => {
if (!ref.current) return
const abortController = new AbortController()
const {signal} = abortController
ref.current.addEventListener(
'loadedmetadata',
function () {
setDimensions(this.videoWidth, this.videoHeight)
},
{signal},
)
return () => {
abortController.abort()
}
}, [setDimensions])
let aspectRatio = asset.width / asset.height
if (isNaN(aspectRatio)) {
aspectRatio = 16 / 9
}
aspectRatio = clamp(aspectRatio, 1 / 1, 3 / 1)
return (
<View
style={[
a.w_full,
a.rounded_sm,
{aspectRatio: 16 / 9},
{aspectRatio},
a.overflow_hidden,
{backgroundColor: 'black'},
]}>
<ExternalEmbedRemoveBtn onRemove={clear} />
<video src={video.uri} style={a.flex_1} autoPlay loop muted playsInline />
<video
ref={ref}
src={video.uri}
style={a.flex_1}
autoPlay
loop
muted
playsInline
/>
</View>
)
}
@@ -21,8 +21,8 @@ export function VideoTranscodeBackdrop({uri}: {uri: string}) {
}, [])
return (
<Animated.View style={a.flex_1} entering={FadeIn}>
{thumbnail && (
thumbnail && (
<Animated.View style={a.flex_1} entering={FadeIn}>
<Image
style={a.flex_1}
source={thumbnail.path}
@@ -31,7 +31,7 @@ export function VideoTranscodeBackdrop({uri}: {uri: string}) {
blurRadius={15}
contentFit="cover"
/>
)}
</Animated.View>
</Animated.View>
)
)
}
@@ -1,7 +1,3 @@
import React from 'react'
export function VideoTranscodeBackdrop({uri}: {uri: string}) {
return (
<video src={uri} style={{flex: 1, filter: 'blur(10px)'}} muted autoPlay />
)
export function VideoTranscodeBackdrop() {
return null
}
@@ -4,6 +4,8 @@ import {View} from 'react-native'
import ProgressPie from 'react-native-progress/Pie'
import {ImagePickerAsset} from 'expo-image-picker'
import {clamp} from '#/lib/numbers'
import {isWeb} from '#/platform/detection'
import {atoms as a, useTheme} from '#/alf'
import {ExternalEmbedRemoveBtn} from '../ExternalEmbedRemoveBtn'
import {VideoTranscodeBackdrop} from './VideoTranscodeBackdrop'
@@ -19,7 +21,15 @@ export function VideoTranscodeProgress({
}) {
const t = useTheme()
const aspectRatio = asset.width / asset.height
if (isWeb) return null
let aspectRatio = asset.width / asset.height
if (isNaN(aspectRatio)) {
aspectRatio = 16 / 9
}
aspectRatio = clamp(aspectRatio, 1 / 1, 3 / 1)
return (
<View
@@ -29,7 +39,7 @@ export function VideoTranscodeProgress({
t.atoms.bg_contrast_50,
a.rounded_md,
a.overflow_hidden,
{aspectRatio: isNaN(aspectRatio) ? 16 / 9 : aspectRatio},
{aspectRatio},
]}>
<VideoTranscodeBackdrop uri={asset.uri} />
<View
+12 -11
View File
@@ -1,23 +1,24 @@
import React, {useCallback, useMemo, useState} from 'react'
import {AppBskyFeedGetLikes as GetLikes} from '@atproto/api'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {cleanError} from '#/lib/strings/errors'
import {logger} from '#/logger'
import {useLikedByQuery} from '#/state/queries/post-liked-by'
import {useResolveUriQuery} from '#/state/queries/resolve-uri'
import {useInitialNumToRender} from 'lib/hooks/useInitialNumToRender'
import {isWeb} from 'platform/detection'
import {ProfileCardWithFollowBtn} from '#/view/com/profile/ProfileCard'
import {List} from '#/view/com/util/List'
import {
ListFooter,
ListHeaderDesktop,
ListMaybePlaceholder,
} from '#/components/Lists'
import {ListFooter, ListMaybePlaceholder} from '#/components/Lists'
function renderItem({item}: {item: GetLikes.Like}) {
return <ProfileCardWithFollowBtn key={item.actor.did} profile={item.actor} />
function renderItem({item, index}: {item: GetLikes.Like; index: number}) {
return (
<ProfileCardWithFollowBtn
key={item.actor.did}
profile={item.actor}
noBorder={index === 0 && !isWeb}
/>
)
}
function keyExtractor(item: GetLikes.Like) {
@@ -25,7 +26,6 @@ function keyExtractor(item: GetLikes.Like) {
}
export function PostLikedBy({uri}: {uri: string}) {
const {_} = useLingui()
const initialNumToRender = useInitialNumToRender()
const [isPTRing, setIsPTRing] = useState(false)
@@ -78,6 +78,7 @@ export function PostLikedBy({uri}: {uri: string}) {
<ListMaybePlaceholder
isLoading={isLoadingUri || isLoadingLikes}
isError={isError}
sideBorders={false}
/>
)
}
@@ -91,7 +92,6 @@ export function PostLikedBy({uri}: {uri: string}) {
onRefresh={onRefresh}
onEndReached={onEndReached}
onEndReachedThreshold={4}
ListHeaderComponent={<ListHeaderDesktop title={_(msg`Liked By`)} />}
ListFooterComponent={
<ListFooter
isFetchingNextPage={isFetchingNextPage}
@@ -103,6 +103,7 @@ export function PostLikedBy({uri}: {uri: string}) {
desktopFixedHeight
initialNumToRender={initialNumToRender}
windowSize={11}
sideBorders={false}
/>
)
}
+7 -8
View File
@@ -14,24 +14,23 @@ import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {usePostQuotesQuery} from '#/state/queries/post-quotes'
import {useResolveUriQuery} from '#/state/queries/resolve-uri'
import {useInitialNumToRender} from 'lib/hooks/useInitialNumToRender'
import {isWeb} from 'platform/detection'
import {Post} from 'view/com/post/Post'
import {
ListFooter,
ListHeaderDesktop,
ListMaybePlaceholder,
} from '#/components/Lists'
import {ListFooter, ListMaybePlaceholder} from '#/components/Lists'
import {List} from '../util/List'
function renderItem({
item,
index,
}: {
item: {
post: AppBskyFeedDefs.PostView
moderation: ModerationDecision
record: AppBskyFeedPost.Record
}
index: number
}) {
return <Post post={item.post} />
return <Post post={item.post} hideTopBorder={index === 0 && !isWeb} />
}
function keyExtractor(item: {
@@ -45,7 +44,6 @@ function keyExtractor(item: {
export function PostQuotes({uri}: {uri: string}) {
const {_} = useLingui()
const initialNumToRender = useInitialNumToRender()
const [isPTRing, setIsPTRing] = useState(false)
const {
@@ -104,6 +102,7 @@ export function PostQuotes({uri}: {uri: string}) {
<ListMaybePlaceholder
isLoading={isLoadingUri || isLoadingQuotes}
isError={isError}
sideBorders={false}
/>
)
}
@@ -119,7 +118,6 @@ export function PostQuotes({uri}: {uri: string}) {
onRefresh={onRefresh}
onEndReached={onEndReached}
onEndReachedThreshold={4}
ListHeaderComponent={<ListHeaderDesktop title={_(msg`Quotes`)} />}
ListFooterComponent={
<ListFooter
isFetchingNextPage={isFetchingNextPage}
@@ -133,6 +131,7 @@ export function PostQuotes({uri}: {uri: string}) {
desktopFixedHeight
initialNumToRender={initialNumToRender}
windowSize={11}
sideBorders={false}
/>
)
}
+3 -9
View File
@@ -1,7 +1,5 @@
import React, {useCallback, useMemo, useState} from 'react'
import {AppBskyActorDefs as ActorDefs} from '@atproto/api'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {cleanError} from '#/lib/strings/errors'
import {logger} from '#/logger'
@@ -10,11 +8,7 @@ import {useResolveUriQuery} from '#/state/queries/resolve-uri'
import {useInitialNumToRender} from 'lib/hooks/useInitialNumToRender'
import {ProfileCardWithFollowBtn} from '#/view/com/profile/ProfileCard'
import {List} from '#/view/com/util/List'
import {
ListFooter,
ListHeaderDesktop,
ListMaybePlaceholder,
} from '#/components/Lists'
import {ListFooter, ListMaybePlaceholder} from '#/components/Lists'
function renderItem({item}: {item: ActorDefs.ProfileViewBasic}) {
return <ProfileCardWithFollowBtn key={item.did} profile={item} />
@@ -25,7 +19,6 @@ function keyExtractor(item: ActorDefs.ProfileViewBasic) {
}
export function PostRepostedBy({uri}: {uri: string}) {
const {_} = useLingui()
const initialNumToRender = useInitialNumToRender()
const [isPTRing, setIsPTRing] = useState(false)
@@ -78,6 +71,7 @@ export function PostRepostedBy({uri}: {uri: string}) {
<ListMaybePlaceholder
isLoading={isLoadingUri || isLoadingRepostedBy}
isError={isError}
sideBorders={false}
/>
)
}
@@ -93,7 +87,6 @@ export function PostRepostedBy({uri}: {uri: string}) {
onRefresh={onRefresh}
onEndReached={onEndReached}
onEndReachedThreshold={4}
ListHeaderComponent={<ListHeaderDesktop title={_(msg`Reposted By`)} />}
ListFooterComponent={
<ListFooter
isFetchingNextPage={isFetchingNextPage}
@@ -105,6 +98,7 @@ export function PostRepostedBy({uri}: {uri: string}) {
desktopFixedHeight
initialNumToRender={initialNumToRender}
windowSize={11}
sideBorders={false}
/>
)
}
+8 -6
View File
@@ -181,7 +181,7 @@ let PostThreadItemLoaded = ({
threadgateRecord?: AppBskyFeedThreadgate.Record
}): React.ReactNode => {
const pal = usePalette('default')
const {_} = useLingui()
const {_, i18n} = useLingui()
const langPrefs = useLanguagePrefs()
const {openComposer} = useComposerControls()
const [limitLines, setLimitLines] = React.useState(
@@ -388,7 +388,7 @@ let PostThreadItemLoaded = ({
type="lg"
style={pal.textLight}>
<Text type="xl-bold" style={pal.text}>
{formatCount(post.repostCount)}
{formatCount(i18n, post.repostCount)}
</Text>{' '}
<Plural
value={post.repostCount}
@@ -410,7 +410,7 @@ let PostThreadItemLoaded = ({
type="lg"
style={pal.textLight}>
<Text type="xl-bold" style={pal.text}>
{formatCount(post.quoteCount)}
{formatCount(i18n, post.quoteCount)}
</Text>{' '}
<Plural
value={post.quoteCount}
@@ -430,7 +430,7 @@ let PostThreadItemLoaded = ({
type="lg"
style={pal.textLight}>
<Text type="xl-bold" style={pal.text}>
{formatCount(post.likeCount)}
{formatCount(i18n, post.likeCount)}
</Text>{' '}
<Plural value={post.likeCount} one="like" other="likes" />
</Text>
@@ -705,7 +705,7 @@ function ExpandedPostDetails({
translatorUrl: string
}) {
const pal = usePalette('default')
const {_} = useLingui()
const {_, i18n} = useLingui()
const openLink = useOpenLink()
const isRootPost = !('reply' in post.record)
@@ -723,7 +723,9 @@ function ExpandedPostDetails({
s.mt2,
s.mb10,
]}>
<Text style={[a.text_sm, pal.textLight]}>{niceDate(post.indexedAt)}</Text>
<Text style={[a.text_sm, pal.textLight]}>
{niceDate(i18n, post.indexedAt)}
</Text>
{isRootPost && (
<WhoCanReply post={post} isThreadAuthor={isThreadAuthor} />
)}
+29 -14
View File
@@ -101,7 +101,7 @@ const feedInterstitialType = 'interstitialFeeds'
const followInterstitialType = 'interstitialFollows'
const progressGuideInterstitialType = 'interstitialProgressGuide'
const interstials: Record<
'following' | 'discover',
'following' | 'discover' | 'profile',
(FeedItem & {
type:
| 'interstitialFeeds'
@@ -128,6 +128,16 @@ const interstials: Record<
slot: 20,
},
],
profile: [
{
type: followInterstitialType,
params: {
variant: 'default',
},
key: followInterstitialType,
slot: 5,
},
],
}
export function getFeedPostSlice(feedItem: FeedItem): FeedPostSlice | null {
@@ -193,9 +203,7 @@ let Feed = ({
const [isPTRing, setIsPTRing] = React.useState(false)
const checkForNewRef = React.useRef<(() => void) | null>(null)
const lastFetchRef = React.useRef<number>(Date.now())
const [feedType, feedUri] = feed.split('|')
const feedIsDiscover = feedUri === DISCOVER_FEED_URI
const feedIsFollowing = feedType === 'following'
const [feedType, feedUri, feedTab] = feed.split('|')
const gate = useGate()
const opts = React.useMemo(
@@ -339,14 +347,21 @@ let Feed = ({
}
if (hasSession) {
const feedType = feedIsFollowing
? 'following'
: feedIsDiscover
? 'discover'
: undefined
let feedKind: 'following' | 'discover' | 'profile' | undefined
if (feedType === 'following') {
feedKind = 'following'
} else if (feedUri === DISCOVER_FEED_URI) {
feedKind = 'discover'
} else if (
feedType === 'author' &&
(feedTab === 'posts_and_author_threads' ||
feedTab === 'posts_with_replies')
) {
feedKind = 'profile'
}
if (feedType) {
for (const interstitial of interstials[feedType]) {
if (feedKind) {
for (const interstitial of interstials[feedKind]) {
const shouldShow =
(interstitial.type === feedInterstitialType &&
gate('suggested_feeds_interstitial')) ||
@@ -377,9 +392,9 @@ let Feed = ({
isEmpty,
lastFetchedAt,
data,
feedType,
feedUri,
feedIsDiscover,
feedIsFollowing,
feedTab,
gate,
hasSession,
])
@@ -470,7 +485,7 @@ let Feed = ({
} else if (item.type === feedInterstitialType) {
return <SuggestedFeeds />
} else if (item.type === followInterstitialType) {
return <SuggestedFollows />
return <SuggestedFollows feed={feed} />
} else if (item.type === progressGuideInterstitialType) {
return <ProgressGuide />
} else if (item.type === 'slice') {
+18 -8
View File
@@ -8,17 +8,26 @@ import {logger} from '#/logger'
import {useProfileFollowersQuery} from '#/state/queries/profile-followers'
import {useResolveDidQuery} from '#/state/queries/resolve-uri'
import {useInitialNumToRender} from 'lib/hooks/useInitialNumToRender'
import {isWeb} from 'platform/detection'
import {useSession} from 'state/session'
import {
ListFooter,
ListHeaderDesktop,
ListMaybePlaceholder,
} from '#/components/Lists'
import {ListFooter, ListMaybePlaceholder} from '#/components/Lists'
import {List} from '../util/List'
import {ProfileCardWithFollowBtn} from './ProfileCard'
function renderItem({item}: {item: ActorDefs.ProfileViewBasic}) {
return <ProfileCardWithFollowBtn key={item.did} profile={item} />
function renderItem({
item,
index,
}: {
item: ActorDefs.ProfileViewBasic
index: number
}) {
return (
<ProfileCardWithFollowBtn
key={item.did}
profile={item}
noBorder={index === 0 && !isWeb}
/>
)
}
function keyExtractor(item: ActorDefs.ProfileViewBasic) {
@@ -88,6 +97,7 @@ export function ProfileFollowers({name}: {name: string}) {
}
errorMessage={cleanError(resolveError || error)}
onRetry={isError ? refetch : undefined}
sideBorders={false}
/>
)
}
@@ -101,7 +111,6 @@ export function ProfileFollowers({name}: {name: string}) {
onRefresh={onRefresh}
onEndReached={onEndReached}
onEndReachedThreshold={4}
ListHeaderComponent={<ListHeaderDesktop title={_(msg`Followers`)} />}
ListFooterComponent={
<ListFooter
isFetchingNextPage={isFetchingNextPage}
@@ -113,6 +122,7 @@ export function ProfileFollowers({name}: {name: string}) {
desktopFixedHeight
initialNumToRender={initialNumToRender}
windowSize={11}
sideBorders={false}
/>
)
}
+18 -8
View File
@@ -8,17 +8,26 @@ import {logger} from '#/logger'
import {useProfileFollowsQuery} from '#/state/queries/profile-follows'
import {useResolveDidQuery} from '#/state/queries/resolve-uri'
import {useInitialNumToRender} from 'lib/hooks/useInitialNumToRender'
import {isWeb} from 'platform/detection'
import {useSession} from 'state/session'
import {
ListFooter,
ListHeaderDesktop,
ListMaybePlaceholder,
} from '#/components/Lists'
import {ListFooter, ListMaybePlaceholder} from '#/components/Lists'
import {List} from '../util/List'
import {ProfileCardWithFollowBtn} from './ProfileCard'
function renderItem({item}: {item: ActorDefs.ProfileViewBasic}) {
return <ProfileCardWithFollowBtn key={item.did} profile={item} />
function renderItem({
item,
index,
}: {
item: ActorDefs.ProfileViewBasic
index: number
}) {
return (
<ProfileCardWithFollowBtn
key={item.did}
profile={item}
noBorder={index === 0 && !isWeb}
/>
)
}
function keyExtractor(item: ActorDefs.ProfileViewBasic) {
@@ -88,6 +97,7 @@ export function ProfileFollows({name}: {name: string}) {
}
errorMessage={cleanError(resolveError || error)}
onRetry={isError ? refetch : undefined}
sideBorders={false}
/>
)
}
@@ -101,7 +111,6 @@ export function ProfileFollows({name}: {name: string}) {
onRefresh={onRefresh}
onEndReached={onEndReached}
onEndReachedThreshold={4}
ListHeaderComponent={<ListHeaderDesktop title={_(msg`Following`)} />}
ListFooterComponent={
<ListFooter
isFetchingNextPage={isFetchingNextPage}
@@ -113,6 +122,7 @@ export function ProfileFollows({name}: {name: string}) {
desktopFixedHeight
initialNumToRender={initialNumToRender}
windowSize={11}
sideBorders={false}
/>
)
}
+5 -2
View File
@@ -1,6 +1,7 @@
import React, {memo, useCallback} from 'react'
import {StyleProp, StyleSheet, TextStyle, View, ViewStyle} from 'react-native'
import {AppBskyActorDefs, ModerationDecision, ModerationUI} from '@atproto/api'
import {useLingui} from '@lingui/react'
import {useQueryClient} from '@tanstack/react-query'
import {precacheProfile} from '#/state/queries/profile'
@@ -35,6 +36,8 @@ interface PostMetaOpts {
}
let PostMeta = (opts: PostMetaOpts): React.ReactNode => {
const {i18n} = useLingui()
const pal = usePalette('default')
const displayName = opts.author.displayName || opts.author.handle
const handle = opts.author.handle
@@ -101,8 +104,8 @@ let PostMeta = (opts: PostMetaOpts): React.ReactNode => {
type="md"
style={pal.textLight}
text={timeElapsed}
accessibilityLabel={niceDate(opts.timestamp)}
title={niceDate(opts.timestamp)}
accessibilityLabel={niceDate(i18n, opts.timestamp)}
title={niceDate(i18n, opts.timestamp)}
accessibilityHint=""
href={opts.postHref}
onBeforePress={onBeforePressPost}
+8 -4
View File
@@ -1,4 +1,6 @@
import React from 'react'
import {I18n} from '@lingui/core'
import {useLingui} from '@lingui/react'
import {useGetTimeAgo} from '#/lib/hooks/useTimeAgo'
import {useTickEveryMinute} from '#/state/shell'
@@ -10,19 +12,21 @@ export function TimeElapsed({
}: {
timestamp: string
children: ({timeElapsed}: {timeElapsed: string}) => JSX.Element
timeToString?: (timeElapsed: string) => string
timeToString?: (i18n: I18n, timeElapsed: string) => string
}) {
const {i18n} = useLingui()
const ago = useGetTimeAgo()
const format = timeToString ?? ago
const tick = useTickEveryMinute()
const [timeElapsed, setTimeAgo] = React.useState(() =>
format(timestamp, tick),
timeToString ? timeToString(i18n, timestamp) : ago(timestamp, tick),
)
const [prevTick, setPrevTick] = React.useState(tick)
if (prevTick !== tick) {
setPrevTick(tick)
setTimeAgo(format(timestamp, tick))
setTimeAgo(
timeToString ? timeToString(i18n, timestamp) : ago(timestamp, tick),
)
}
return children({timeElapsed})
+1 -1
View File
@@ -47,7 +47,7 @@ export const CenteredView = React.forwardRef(function CenteredView(
if (!isMobile) {
style = addStyle(style, styles.container)
}
if (sideBorders) {
if (sideBorders && !isMobile) {
style = addStyle(style, {
borderLeftWidth: StyleSheet.hairlineWidth,
borderRightWidth: StyleSheet.hairlineWidth,
+12 -16
View File
@@ -1,19 +1,18 @@
import React, {useState, useCallback} from 'react'
import React, {useCallback, useState} from 'react'
import {StyleProp, StyleSheet, TextStyle, View, ViewStyle} from 'react-native'
import DatePicker from 'react-native-date-picker'
import {
FontAwesomeIcon,
FontAwesomeIconStyle,
} from '@fortawesome/react-native-fontawesome'
import {isIOS, isAndroid} from 'platform/detection'
import {Button, ButtonType} from './Button'
import {Text} from '../text/Text'
import {useLingui} from '@lingui/react'
import {usePalette} from 'lib/hooks/usePalette'
import {TypographyVariant} from 'lib/ThemeContext'
import {useTheme} from 'lib/ThemeContext'
import {usePalette} from 'lib/hooks/usePalette'
import {getLocales} from 'expo-localization'
import DatePicker from 'react-native-date-picker'
const LOCALE = getLocales()[0]
import {isAndroid, isIOS} from 'platform/detection'
import {Text} from '../text/Text'
import {Button, ButtonType} from './Button'
interface Props {
testID?: string
@@ -30,16 +29,11 @@ interface Props {
}
export function DateInput(props: Props) {
const {i18n} = useLingui()
const [show, setShow] = useState(false)
const theme = useTheme()
const pal = usePalette('default')
const formatter = React.useMemo(() => {
return new Intl.DateTimeFormat(LOCALE.languageTag, {
timeZone: props.handleAsUTC ? 'UTC' : undefined,
})
}, [props.handleAsUTC])
const onChangeInternal = useCallback(
(date: Date) => {
setShow(false)
@@ -74,7 +68,9 @@ export function DateInput(props: Props) {
<Text
type={props.buttonLabelType}
style={[pal.text, props.buttonLabelStyle]}>
{formatter.format(props.value)}
{i18n.date(props.value, {
timeZone: props.handleAsUTC ? 'UTC' : undefined,
})}
</Text>
</View>
</Button>
+5 -12
View File
@@ -1,19 +1,12 @@
export const formatCount = (num: number) =>
Intl.NumberFormat('en-US', {
import type {I18n} from '@lingui/core'
export const formatCount = (i18n: I18n, num: number) => {
return i18n.number(num, {
notation: 'compact',
maximumFractionDigits: 1,
// `1,953` shouldn't be rounded up to 2k, it should be truncated.
// @ts-expect-error: `roundingMode` doesn't seem to be in the typings yet
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#roundingmode
roundingMode: 'trunc',
}).format(num)
export function formatCountShortOnly(num: number): string {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + 'M'
}
if (num >= 1000) {
return (num / 1000).toFixed(1) + 'K'
}
return String(num)
})
}
+51 -31
View File
@@ -23,7 +23,6 @@ import {makeProfileLink} from '#/lib/routes/links'
import {shareUrl} from '#/lib/sharing'
import {useGate} from '#/lib/statsig/statsig'
import {toShareUrl} from '#/lib/strings/url-helpers'
import {s} from '#/lib/styles'
import {Shadow} from '#/state/cache/types'
import {useFeedFeedbackContext} from '#/state/feed-feedback'
import {
@@ -36,14 +35,12 @@ import {
ProgressGuideAction,
useProgressGuideControls,
} from '#/state/shell/progress-guide'
import {CountWheel} from 'lib/custom-animations/CountWheel'
import {AnimatedLikeIcon} from 'lib/custom-animations/LikeIcon'
import {atoms as a, useTheme} from '#/alf'
import {useDialogControl} from '#/components/Dialog'
import {ArrowOutOfBox_Stroke2_Corner0_Rounded as ArrowOutOfBox} from '#/components/icons/ArrowOutOfBox'
import {Bubble_Stroke2_Corner2_Rounded as Bubble} from '#/components/icons/Bubble'
import {
Heart2_Filled_Stroke2_Corner0_Rounded as HeartIconFilled,
Heart2_Stroke2_Corner0_Rounded as HeartIconOutline,
} from '#/components/icons/Heart2'
import * as Prompt from '#/components/Prompt'
import {PostDropdownBtn} from '../forms/PostDropdownBtn'
import {formatCount} from '../numeric/format'
@@ -75,7 +72,7 @@ let PostCtrls = ({
threadgateRecord?: AppBskyFeedThreadgate.Record
}): React.ReactNode => {
const t = useTheme()
const {_} = useLingui()
const {_, i18n} = useLingui()
const {openComposer} = useComposerControls()
const {currentAccount} = useSession()
const [queueLike, queueUnlike] = usePostLikeMutationQueue(post, logContext)
@@ -89,6 +86,11 @@ let PostCtrls = ({
const {captureAction} = useProgressGuideControls()
const playHaptic = useHaptics()
const gate = useGate()
const isBlocked = Boolean(
post.author.viewer?.blocking ||
post.author.viewer?.blockedBy ||
post.author.viewer?.blockingByList,
)
const shouldShowLoggedOutWarning = React.useMemo(() => {
return (
@@ -104,9 +106,21 @@ let PostCtrls = ({
[t],
) as StyleProp<ViewStyle>
const likeValue = post.viewer?.like ? 1 : 0
const nextExpectedLikeValue = React.useRef(likeValue)
const onPressToggleLike = React.useCallback(async () => {
if (isBlocked) {
Toast.show(
_(msg`Cannot interact with a blocked user`),
'exclamation-circle',
)
return
}
try {
if (!post.viewer?.like) {
nextExpectedLikeValue.current = 1
playHaptic()
sendInteraction({
item: post.uri,
@@ -116,6 +130,7 @@ let PostCtrls = ({
captureAction(ProgressGuideAction.Like)
await queueLike()
} else {
nextExpectedLikeValue.current = 0
await queueUnlike()
}
} catch (e: any) {
@@ -124,6 +139,7 @@ let PostCtrls = ({
}
}
}, [
_,
playHaptic,
post.uri,
post.viewer?.like,
@@ -132,9 +148,18 @@ let PostCtrls = ({
sendInteraction,
captureAction,
feedContext,
isBlocked,
])
const onRepost = useCallback(async () => {
if (isBlocked) {
Toast.show(
_(msg`Cannot interact with a blocked user`),
'exclamation-circle',
)
return
}
try {
if (!post.viewer?.repost) {
sendInteraction({
@@ -152,15 +177,25 @@ let PostCtrls = ({
}
}
}, [
_,
post.uri,
post.viewer?.repost,
queueRepost,
queueUnrepost,
sendInteraction,
feedContext,
isBlocked,
])
const onQuote = useCallback(() => {
if (isBlocked) {
Toast.show(
_(msg`Cannot interact with a blocked user`),
'exclamation-circle',
)
return
}
sendInteraction({
item: post.uri,
event: 'app.bsky.feed.defs#interactionQuote',
@@ -178,6 +213,7 @@ let PostCtrls = ({
onPost: onPostReply,
})
}, [
_,
sendInteraction,
post.uri,
post.cid,
@@ -188,6 +224,7 @@ let PostCtrls = ({
openComposer,
record.text,
onPostReply,
isBlocked,
])
const onShare = useCallback(() => {
@@ -207,8 +244,8 @@ let PostCtrls = ({
a.gap_xs,
a.rounded_full,
a.flex_row,
a.align_center,
a.justify_center,
a.align_center,
{padding: 5},
(pressed || hovered) && t.atoms.bg_contrast_25,
],
@@ -247,7 +284,7 @@ let PostCtrls = ({
big ? a.text_md : {fontSize: 15},
a.user_select_none,
]}>
{formatCount(post.replyCount)}
{formatCount(i18n, post.replyCount)}
</Text>
) : undefined}
</Pressable>
@@ -280,29 +317,12 @@ let PostCtrls = ({
}
accessibilityHint=""
hitSlop={POST_CTRL_HITSLOP}>
{post.viewer?.like ? (
<HeartIconFilled style={s.likeColor} width={big ? 22 : 18} />
) : (
<HeartIconOutline
style={[defaultCtrlColor, {pointerEvents: 'none'}]}
width={big ? 22 : 18}
/>
)}
{typeof post.likeCount !== 'undefined' && post.likeCount > 0 ? (
<Text
testID="likeCount"
style={[
[
big ? a.text_md : {fontSize: 15},
a.user_select_none,
post.viewer?.like
? [a.font_bold, s.likeColor]
: defaultCtrlColor,
],
]}>
{formatCount(post.likeCount)}
</Text>
) : undefined}
<AnimatedLikeIcon isLiked={Boolean(post.viewer?.like)} big={big} />
<CountWheel
likeCount={post.likeCount ?? 0}
big={big}
isLiked={Boolean(post.viewer?.like)}
/>
</Pressable>
</View>
{big && (
@@ -32,7 +32,7 @@ let RepostButton = ({
embeddingDisabled,
}: Props): React.ReactNode => {
const t = useTheme()
const {_} = useLingui()
const {_, i18n} = useLingui()
const requireAuth = useRequireAuth()
const dialogControl = Dialog.useDialogControl()
const playHaptic = useHaptics()
@@ -79,7 +79,7 @@ let RepostButton = ({
big ? a.text_md : {fontSize: 15},
isReposted && a.font_bold,
]}>
{formatCount(repostCount)}
{formatCount(i18n, repostCount)}
</Text>
) : undefined}
</Button>
@@ -128,6 +128,7 @@ const RepostInner = ({
repostCount?: number
big?: boolean
}) => {
const {i18n} = useLingui()
return (
<View style={[a.flex_row, a.align_center, a.gap_xs, {padding: 5}]}>
<Repost style={color} width={big ? 22 : 18} />
@@ -140,7 +141,7 @@ const RepostInner = ({
isReposted && [a.font_bold],
a.user_select_none,
]}>
{formatCount(repostCount)}
{formatCount(i18n, repostCount)}
</Text>
) : undefined}
</View>
+3 -5
View File
@@ -31,7 +31,7 @@ export function VideoEmbed({embed}: {embed: AppBskyEmbedVideo.View}) {
)
const gate = useGate()
if (!gate('videos')) {
if (!gate('video_view_on_posts')) {
return null
}
@@ -50,7 +50,7 @@ export function VideoEmbed({embed}: {embed: AppBskyEmbedVideo.View}) {
a.rounded_sm,
a.overflow_hidden,
{aspectRatio},
{backgroundColor: t.palette.black},
{backgroundColor: 'black'},
a.my_xs,
]}>
<ErrorBoundary renderError={renderError} key={key}>
@@ -78,9 +78,7 @@ export function VideoEmbed({embed}: {embed: AppBskyEmbedVideo.View}) {
setActiveSource(embed.playlist)
}}
label={_(msg`Play video`)}
variant="ghost"
color="secondary"
size="large">
color="secondary">
<PlayIcon width={48} fill={t.palette.white} />
</Button>
</>
@@ -9,13 +9,12 @@ import {
HLSUnsupportedError,
VideoEmbedInnerWeb,
} from '#/view/com/util/post-embeds/VideoEmbedInner/VideoEmbedInnerWeb'
import {atoms as a, useTheme} from '#/alf'
import {atoms as a} from '#/alf'
import {ErrorBoundary} from '../ErrorBoundary'
import {useActiveVideoWeb} from './ActiveVideoWebContext'
import * as VideoFallback from './VideoEmbedInner/VideoFallback'
export function VideoEmbed({embed}: {embed: AppBskyEmbedVideo.View}) {
const t = useTheme()
const ref = useRef<HTMLDivElement>(null)
const gate = useGate()
const {active, setActive, sendPosition, currentActiveView} =
@@ -47,7 +46,7 @@ export function VideoEmbed({embed}: {embed: AppBskyEmbedVideo.View}) {
[key],
)
if (!gate('videos')) {
if (!gate('video_view_on_posts')) {
return null
}
@@ -64,7 +63,7 @@ export function VideoEmbed({embed}: {embed: AppBskyEmbedVideo.View}) {
style={[
a.w_full,
{aspectRatio},
{backgroundColor: t.palette.black},
{backgroundColor: 'black'},
a.relative,
a.rounded_sm,
a.my_xs,
@@ -29,9 +29,9 @@ export function TimeIndicator({time}: {time: number}) {
paddingHorizontal: 6,
paddingVertical: 3,
position: 'absolute',
left: 5,
bottom: 5,
minHeight: 20,
left: 6,
bottom: 6,
minHeight: 21,
justifyContent: 'center',
},
]}>
@@ -167,17 +167,20 @@ function VideoControls({
/>
<Animated.View
entering={FadeInDown.duration(300)}
style={{
backgroundColor: 'rgba(0, 0, 0, 0.5)',
borderRadius: 6,
paddingHorizontal: 6,
paddingVertical: 3,
position: 'absolute',
bottom: 5,
right: 5,
minHeight: 20,
justifyContent: 'center',
}}>
style={[
a.absolute,
a.rounded_full,
a.justify_center,
{
backgroundColor: 'rgba(0, 0, 0, 0.5)',
paddingHorizontal: 4,
paddingVertical: 4,
bottom: 6,
right: 6,
minHeight: 21,
minWidth: 21,
},
]}>
<Pressable
onPress={toggleMuted}
style={a.flex_1}
@@ -186,9 +189,9 @@ function VideoControls({
accessibilityRole="button"
hitSlop={HITSLOP_30}>
{isMuted ? (
<MuteIcon width={14} fill={t.palette.white} />
<MuteIcon width={13} fill={t.palette.white} />
) : (
<UnmuteIcon width={14} fill={t.palette.white} />
<UnmuteIcon width={13} fill={t.palette.white} />
)}
</Pressable>
</Animated.View>
@@ -253,7 +253,7 @@ export function Controls({
style={a.flex_1}
onPress={onPressEmptySpace}
/>
{active && !showControls && !focused && (
{active && !showControls && !focused && duration > 0 && (
<TimeIndicator time={Math.floor(duration - currentTime)} />
)}
<View
@@ -475,21 +475,8 @@ function Scrubber({
if (isFirefox && scrubberActive) {
document.body.classList.add('force-no-clicks')
const abortController = new AbortController()
const {signal} = abortController
document.documentElement.addEventListener(
'mouseleave',
() => {
isSeekingRef.current = false
onSeekEnd()
setScrubberActive(false)
},
{signal},
)
return () => {
document.body.classList.remove('force-no-clicks')
abortController.abort()
}
}
}, [scrubberActive, onSeekEnd])
@@ -548,7 +535,8 @@ function Scrubber({
}}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}>
onPointerUp={onPointerUp}
onPointerCancel={onPointerUp}>
<View
style={[
a.w_full,
@@ -557,7 +545,7 @@ function Scrubber({
{backgroundColor: 'rgba(255, 255, 255, 0.4)'},
{height: hovered || scrubberActive ? 6 : 3},
]}>
{currentTime > 0 && duration > 0 && (
{duration > 0 && (
<View
style={[
a.h_full,
+3 -8
View File
@@ -18,7 +18,6 @@ import {useWebMediaQueries} from '#/lib/hooks/useWebMediaQueries'
import {CommonNavigatorParams} from '#/lib/routes/types'
import {cleanError} from '#/lib/strings/errors'
import {useModalControls} from '#/state/modals'
import {useLanguagePrefs} from '#/state/preferences'
import {
useAppPasswordDeleteMutation,
useAppPasswordsQuery,
@@ -218,9 +217,8 @@ function AppPassword({
privileged?: boolean
}) {
const pal = usePalette('default')
const {_} = useLingui()
const {_, i18n} = useLingui()
const control = useDialogControl()
const {contentLanguages} = useLanguagePrefs()
const deleteMutation = useAppPasswordDeleteMutation()
const onDelete = React.useCallback(async () => {
@@ -232,9 +230,6 @@ function AppPassword({
control.open()
}, [control])
const primaryLocale =
contentLanguages.length > 0 ? contentLanguages[0] : 'en-US'
return (
<TouchableOpacity
testID={testID}
@@ -250,14 +245,14 @@ function AppPassword({
<Text type="md" style={[pal.text, styles.pr10]} numberOfLines={1}>
<Trans>
Created{' '}
{Intl.DateTimeFormat(primaryLocale, {
{i18n.date(createdAt, {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
}).format(new Date(createdAt))}
})}
</Trans>
</Text>
{privileged && (
+15 -10
View File
@@ -1,12 +1,16 @@
import React from 'react'
import {View} from 'react-native'
import {useFocusEffect} from '@react-navigation/native'
import {NativeStackScreenProps, CommonNavigatorParams} from 'lib/routes/types'
import {ViewHeader} from '../com/util/ViewHeader'
import {ProfileFollowers as ProfileFollowersComponent} from '../com/profile/ProfileFollowers'
import {useSetMinimalShellMode} from '#/state/shell'
import {useLingui} from '@lingui/react'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useFocusEffect} from '@react-navigation/native'
import {useSetMinimalShellMode} from '#/state/shell'
import {CommonNavigatorParams, NativeStackScreenProps} from 'lib/routes/types'
import {isWeb} from 'platform/detection'
import {CenteredView} from 'view/com/util/Views'
import {atoms as a} from '#/alf'
import {ListHeaderDesktop} from '#/components/Lists'
import {ProfileFollowers as ProfileFollowersComponent} from '../com/profile/ProfileFollowers'
import {ViewHeader} from '../com/util/ViewHeader'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'ProfileFollowers'>
export const ProfileFollowersScreen = ({route}: Props) => {
@@ -21,9 +25,10 @@ export const ProfileFollowersScreen = ({route}: Props) => {
)
return (
<View style={{flex: 1}}>
<ViewHeader title={_(msg`Followers`)} />
<CenteredView style={a.h_full_vh} sideBorders={true}>
<ListHeaderDesktop title={_(msg`Followers`)} />
<ViewHeader title={_(msg`Followers`)} showBorder={!isWeb} />
<ProfileFollowersComponent name={name} />
</View>
</CenteredView>
)
}
+15 -10
View File
@@ -1,12 +1,16 @@
import React from 'react'
import {View} from 'react-native'
import {useFocusEffect} from '@react-navigation/native'
import {NativeStackScreenProps, CommonNavigatorParams} from 'lib/routes/types'
import {ViewHeader} from '../com/util/ViewHeader'
import {ProfileFollows as ProfileFollowsComponent} from '../com/profile/ProfileFollows'
import {useSetMinimalShellMode} from '#/state/shell'
import {useLingui} from '@lingui/react'
import {msg} from '@lingui/macro'
import {useLingui} from '@lingui/react'
import {useFocusEffect} from '@react-navigation/native'
import {useSetMinimalShellMode} from '#/state/shell'
import {CommonNavigatorParams, NativeStackScreenProps} from 'lib/routes/types'
import {isWeb} from 'platform/detection'
import {CenteredView} from 'view/com/util/Views'
import {atoms as a} from '#/alf'
import {ListHeaderDesktop} from '#/components/Lists'
import {ProfileFollows as ProfileFollowsComponent} from '../com/profile/ProfileFollows'
import {ViewHeader} from '../com/util/ViewHeader'
type Props = NativeStackScreenProps<CommonNavigatorParams, 'ProfileFollows'>
export const ProfileFollowsScreen = ({route}: Props) => {
@@ -21,9 +25,10 @@ export const ProfileFollowsScreen = ({route}: Props) => {
)
return (
<View style={{flex: 1}}>
<ViewHeader title={_(msg`Following`)} />
<CenteredView style={a.h_full_vh} sideBorders={true}>
<ListHeaderDesktop title={_(msg`Following`)} />
<ViewHeader title={_(msg`Following`)} showBorder={!isWeb} />
<ProfileFollowsComponent name={name} />
</View>
</CenteredView>
)
}
+4 -4
View File
@@ -30,7 +30,7 @@ import {colors, s} from 'lib/styles'
import {useTheme} from 'lib/ThemeContext'
import {isWeb} from 'platform/detection'
import {NavSignupCard} from '#/view/shell/NavSignupCard'
import {formatCountShortOnly} from 'view/com/util/numeric/format'
import {formatCount} from 'view/com/util/numeric/format'
import {Text} from 'view/com/util/text/Text'
import {UserAvatar} from 'view/com/util/UserAvatar'
import {atoms as a} from '#/alf'
@@ -68,7 +68,7 @@ let DrawerProfileCard = ({
account: SessionAccount
onPressProfile: () => void
}): React.ReactNode => {
const {_} = useLingui()
const {_, i18n} = useLingui()
const pal = usePalette('default')
const {data: profile} = useProfileQuery({did: account.did})
@@ -108,7 +108,7 @@ let DrawerProfileCard = ({
<Text type="xl" style={pal.textLight}>
<Trans>
<Text type="xl-medium" style={pal.text}>
{formatCountShortOnly(profile?.followersCount ?? 0)}
{formatCount(i18n, profile?.followersCount ?? 0)}
</Text>{' '}
<Plural
value={profile?.followersCount || 0}
@@ -123,7 +123,7 @@ let DrawerProfileCard = ({
<Text type="xl" style={pal.textLight}>
<Trans>
<Text type="xl-medium" style={pal.text}>
{formatCountShortOnly(profile?.followsCount ?? 0)}
{formatCount(i18n, profile?.followsCount ?? 0)}
</Text>{' '}
<Plural
value={profile?.followsCount || 0}
+6 -6
View File
@@ -9918,14 +9918,14 @@ caniuse-api@^3.0.0:
lodash.uniq "^4.5.0"
caniuse-lite@^1.0.0, caniuse-lite@^1.0.30001517, caniuse-lite@^1.0.30001520:
version "1.0.30001596"
resolved "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001596.tgz"
integrity sha512-zpkZ+kEr6We7w63ORkoJ2pOfBwBkY/bJrG/UZ90qNb45Isblu8wzDgevEOrRL1r9dWayHjYiiyCMEXPn4DweGQ==
version "1.0.30001655"
resolved "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001655.tgz"
integrity sha512-jRGVy3iSGO5Uutn2owlb5gR6qsGngTw9ZTb4ali9f3glshcNmJ2noam4Mo9zia5P9Dk3jNNydy7vQjuE5dQmfg==
caniuse-lite@^1.0.30001587:
version "1.0.30001620"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001620.tgz#78bb6f35b8fe315b96b8590597094145d0b146b4"
integrity sha512-WJvYsOjd1/BYUY6SNGUosK9DUidBPDTnOARHp3fSmFO1ekdxaY6nKRttEVrfMmYi80ctS0kz1wiWmm14fVc3ew==
version "1.0.30001655"
resolved "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001655.tgz"
integrity sha512-jRGVy3iSGO5Uutn2owlb5gR6qsGngTw9ZTb4ali9f3glshcNmJ2noam4Mo9zia5P9Dk3jNNydy7vQjuE5dQmfg==
case-anything@^2.1.13:
version "2.1.13"