Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions packages/common/src/hooks/useImageSize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ export const useImageSize = <
preloadImageFn?: (url: string) => Promise<void>
}) => {
const [imageUrl, setImageUrl] = useState<Maybe<string>>(undefined)
// When upgrading from a smaller cached image to the target size, holds the
// smaller URL so callers can show it as a blurred backdrop while the
// high-res crossfades in (avoids the opacity-reset flash on source change).
const [priorityLowResUrl, setPriorityLowResUrl] =
useState<Maybe<string>>(undefined)
const [failedUrls, setFailedUrls] = useState<Set<string>>(new Set())

const fetchWithFallback = useCallback(
Expand Down Expand Up @@ -150,10 +155,21 @@ export const useImageSize = <
}

if (smallerSize) {
setImageUrl(artwork[smallerSize])
const finalUrl = await fetchWithFallback(targetUrl)
IMAGE_CACHE.add(finalUrl)
setImageUrl(finalUrl)
// Set the target URL optimistically so the main image slot starts
// loading the high-res immediately. The smaller cached URL is passed
// back as priorityLowResUrl so callers can show it as a blurred
// backdrop — this eliminates the opacity-reset flash that occurred
// when we previously did setImageUrl(small) then setImageUrl(large).
setPriorityLowResUrl(artwork[smallerSize])
setImageUrl(targetUrl)
try {
const finalUrl = await fetchWithFallback(targetUrl)
IMAGE_CACHE.add(finalUrl)
if (finalUrl !== targetUrl) setImageUrl(finalUrl)
} catch (e) {
// Fall back to the smaller size if high-res is unreachable.
setImageUrl(artwork[smallerSize])
}
return
}

Expand Down Expand Up @@ -190,5 +206,5 @@ export const useImageSize = <
resolveImageUrl()
}, [resolveImageUrl])

return { imageUrl, onError }
return { imageUrl, priorityLowResUrl, onError }
}
9 changes: 8 additions & 1 deletion packages/mobile/src/components/image/CollectionImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,11 @@ export const useCollectionImage = ({
})
const artwork = artworkData?.artwork
const hasNoArtwork = artworkData?.hasNoArtwork ?? false
const { imageUrl, onError: onImageError } = useImageSize({
const {
imageUrl,
priorityLowResUrl,
onError: onImageError
} = useImageSize({
artwork,
targetSize: size,
defaultImage: '',
Expand All @@ -98,6 +102,7 @@ export const useCollectionImage = ({

return {
source: primitiveToImageSource(imageUrl),
priorityLowResSource: primitiveToImageSource(priorityLowResUrl),
hasNoArtwork: false,
onError: onImageError
}
Expand All @@ -121,6 +126,7 @@ export const CollectionImage = (props: CollectionImageProps) => {
const collectionImageSource = useCollectionImage({ collectionId, size })
const {
source: loadedSource,
priorityLowResSource,
onError: onImageError,
hasNoArtwork
} = collectionImageSource
Expand Down Expand Up @@ -160,6 +166,7 @@ export const CollectionImage = (props: CollectionImageProps) => {
<Artwork
{...other}
source={source}
priorityLowResSource={priorityLowResSource}
onLoad={onLoad}
onError={handleError}
style={style}
Expand Down
9 changes: 8 additions & 1 deletion packages/mobile/src/components/image/TrackImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,11 @@ export const useTrackImage = ({
})
const artwork = artworkData?.artwork
const hasNoArtwork = artworkData?.hasNoArtwork ?? false
const { imageUrl, onError: onImageError } = useImageSize({
const {
imageUrl,
priorityLowResUrl,
onError: onImageError
} = useImageSize({
artwork,
targetSize: size,
defaultImage: '',
Expand Down Expand Up @@ -97,6 +101,7 @@ export const useTrackImage = ({

return {
source: primitiveToImageSource(imageUrl),
priorityLowResSource: primitiveToImageSource(priorityLowResUrl),
hasNoArtwork: false,
onError: onImageError
}
Expand Down Expand Up @@ -129,6 +134,7 @@ export const TrackImage = (props: TrackImageProps) => {
const trackImageSource = useTrackImage({ trackId, size })
const {
source: loadedSource,
priorityLowResSource,
onError: onImageError,
hasNoArtwork
} = trackImageSource
Expand Down Expand Up @@ -176,6 +182,7 @@ export const TrackImage = (props: TrackImageProps) => {
return (
<Artwork
source={source}
priorityLowResSource={priorityLowResSource}
onLoad={onLoad}
onError={handleError}
borderRadius={borderRadius}
Expand Down
22 changes: 19 additions & 3 deletions packages/mobile/src/components/image/UserImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ export const useProfilePicture = ({
})

const { profile_picture, updatedProfilePicture } = partialUser ?? {}
const { imageUrl, onError: onImageError } = useImageSize({
const {
imageUrl,
priorityLowResUrl,
onError: onImageError
} = useImageSize({
artwork: profile_picture,
targetSize: size,
defaultImage: '',
Expand All @@ -54,6 +58,7 @@ export const useProfilePicture = ({

return {
source: primitiveToImageSource(imageUrl),
priorityLowResSource: primitiveToImageSource(priorityLowResUrl),
isFallbackImage: false,
onError: onImageError
}
Expand All @@ -63,7 +68,11 @@ export type UserImageProps = UseUserImageOptions & Partial<ImageProps>

export const UserImage = (props: UserImageProps) => {
const { userId, size, onError, ...imageProps } = props
const { source, onError: onImageError } = useProfilePicture({ userId, size })
const {
source,
priorityLowResSource,
onError: onImageError
} = useProfilePicture({ userId, size })

const handleError = (error: { nativeEvent: { error: string } }) => {
if (source && typeof source === 'object' && 'uri' in source) {
Expand All @@ -72,5 +81,12 @@ export const UserImage = (props: UserImageProps) => {
onError?.(error)
}

return <Image {...imageProps} source={source} onError={handleError} />
return (
<Image
{...imageProps}
source={source}
priorityLowResSource={priorityLowResSource}
onError={handleError}
/>
)
}
4 changes: 0 additions & 4 deletions packages/mobile/src/screens/root-screen/RootScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,6 @@ export type RootScreenParamList = {
export const RootScreen = () => {
const { updateRequired } = useUpdateRequired()
const dispatch = useDispatch()
// Keep the native splash up until the query-client cache is fully restored
// from AsyncStorage. The skeleton→real content swap happens under the splash,
// so the user never sees the brief layout settling that caused a visible
// "slide down/up" glitch on content load.
const isRestoring = useIsRestoring()
usePrefetchTrendingImages()
const { data: accountStatus } = useAccountStatus()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
import {
TRENDING_INITIAL_PAGE_SIZE,
TRENDING_LOAD_MORE_PAGE_SIZE
} from '@audius/common/api'
import { TRENDING_INITIAL_PAGE_SIZE } from '@audius/common/api'
import { range } from 'lodash'
import { ScrollView, View } from 'react-native'

import { TrackLineup } from 'app/components/lineup/TrackLineup'
import { LineupTileSkeleton } from 'app/components/lineup-tile'

/**
* Skeleton placeholder used by ScreenSecondaryContent on the Trending screen
* during the deferred-render window. Rendering TrackLineup with empty trackIds
* + isPending guarantees the skeleton tiles match the loaded lineup exactly
* (same SectionList row, same item wrapper, same LineupTileSkeleton sizing).
* Skeleton placeholder rendered by ScreenSecondaryContent while the trending
* lineup is restoring or loading.
*
* Previously this rendered TrackLineup (isPending), but TrackLineup routes
* through the custom SectionList which, inside the collapsible-tab context,
* uses Tabs.SectionList. That component inserts top padding equal to the
* collapsible header height, creating a blank gap above the skeleton tiles.
*
* A plain ScrollView has no such padding and always starts tiles at the top.
*/
export const TrendingLineupSkeletons = () => (
<TrackLineup
trackIds={[]}
source='DISCOVER_TRENDING_WEEK'
isPending
initialPageSize={TRENDING_INITIAL_PAGE_SIZE}
pageSize={TRENDING_LOAD_MORE_PAGE_SIZE}
isTrending
rankIconCount={5}
itemStyles={{ paddingTop: 16, paddingBottom: 0 }}
/>
<ScrollView scrollEnabled={false}>
{range(TRENDING_INITIAL_PAGE_SIZE).map((i) => (
<View key={i} style={{ padding: 16, paddingBottom: 0 }}>
<LineupTileSkeleton noShimmer />
</View>
))}
</ScrollView>
)
76 changes: 60 additions & 16 deletions packages/mobile/src/services/query-persister.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,71 @@ import AsyncStorage from '@react-native-async-storage/async-storage'
import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
import type { PersistQueryClientOptions } from '@tanstack/react-query-persist-client'

import { queryClient } from 'app/services/query-client'

// Bump when the persisted shape changes incompatibly so existing snapshots
// are dropped on next launch.
const QUERY_CACHE_BUSTER = 'v2'
const QUERY_CACHE_STORAGE_KEY = 'tanquery-cache'
const QUERY_CACHE_MAX_AGE_MS = 1000 * 60 * 60 * 24

// Narrow positive allowlist: only the queries needed to paint the Trending
// screen instantly on a warm cold-start. A wide allowlist inflates the cached
// JSON blob and forces a large JSON.stringify on the JS thread every time any
// allowlisted query updates — causing periodic freezes. We can broaden this
// later per-screen once we've confirmed the overhead is acceptable.
// Top-level query keys that are eligible for persistence at all.
const PERSIST_QUERY_KEY_ALLOWLIST: ReadonlySet<string> = new Set([
// Account / identity.
QUERY_KEYS.account,
QUERY_KEYS.accountUser,
QUERY_KEYS.walletAddresses,

// Entity caches — needed for trending tiles to render without a network
// round-trip (tracks + their owners).
QUERY_KEYS.user,
QUERY_KEYS.track,

// Trending lineup (the initial landing screen).
QUERY_KEYS.trending,
QUERY_KEYS.trendingIds
])

// Cached per dehydration pass so we don't re-query for every track/user entry.
// Invalidated after 200 ms so a new pass always gets fresh data.
let _trendingCache: {
trackIds: Set<number>
userIds: Set<number>
} | null = null
let _trendingCacheAt = 0

const getTrendingData = () => {
const now = Date.now()
if (_trendingCache && now - _trendingCacheAt < 200) return _trendingCache

// Use getQueriesData (prefix match) rather than getQueryData (exact match)
// because the stored key encodes genre as null when no genre is selected,
// but JSON.stringify drops undefined keys — { genre: undefined } hashes to
// {} while { genre: null } hashes to {"genre":null}, making exact lookups
// miss. Prefix matching finds the trendingIds query regardless of genre.
const trendingIdsQueries = queryClient.getQueriesData<{
week?: number[]
}>({ queryKey: [QUERY_KEYS.trendingIds] })
const trendingIds = trendingIdsQueries[0]?.[1]

const trackIds = new Set<number>(trendingIds?.week ?? [])

// Collect owner IDs from the trending tracks so we persist their user data.
const userIds = new Set<number>()
const accountUser = queryClient.getQueryData<{ user_id?: number }>([
QUERY_KEYS.accountUser
])
if (accountUser?.user_id) userIds.add(accountUser.user_id)
for (const trackId of trackIds) {
const track = queryClient.getQueryData<{ owner_id?: number }>([
QUERY_KEYS.track,
trackId
])
if (track?.owner_id) userIds.add(track.owner_id)
}

_trendingCache = { trackIds, userIds }
_trendingCacheAt = now
return _trendingCache
}

const queryClientPersister = createAsyncStoragePersister({
storage: AsyncStorage,
key: QUERY_CACHE_STORAGE_KEY,
// Coalesce writes: 1 write per 5 s max. Aggressive throttling keeps the
// JSON.stringify work (which runs on the JS thread) from firing too
// often and causing periodic frame drops.
throttleTime: 5000
})

Expand All @@ -51,8 +83,20 @@ export const queryClientPersistOptions: Omit<
const topKey = query.queryKey?.[0]
if (typeof topKey !== 'string') return false
if (!PERSIST_QUERY_KEY_ALLOWLIST.has(topKey)) return false
// Skip errored / pending queries — let them refetch from scratch.
return query.state.status === 'success'
if (query.state.status !== 'success') return false

// Limit track and user entries to only what's needed for the Trending
// screen. Without this gate every track/user ever fetched in the session
// accumulates in the blob, making the JSON.parse on next cold-start
// progressively slower.
if (topKey === QUERY_KEYS.track) {
return getTrendingData().trackIds.has(query.queryKey[1] as number)
}
if (topKey === QUERY_KEYS.user) {
return getTrendingData().userIds.has(query.queryKey[1] as number)
}

return true
}
}
}
Loading