From e8f5b13cfdb179084709f0a46c42a6207e9db7be Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Sat, 17 Oct 2026 15:14:34 -0400 Subject: [PATCH] perf(mobile): optimize long list rendering (#28) --- apps/mobile/app.json | 4 +- .../app/(app)/(tabs)/home/album/[id].tsx | 132 ++-- .../app/(app)/(tabs)/home/browse/artists.tsx | 112 +++- .../app/(app)/(tabs)/home/browse/songs.tsx | 73 +-- .../app/(app)/(tabs)/home/playlist/[id].tsx | 619 ++++++++---------- .../(app)/(tabs)/home/playlist/favorites.tsx | 229 ++++--- apps/mobile/app/(app)/(tabs)/home/queue.tsx | 29 +- apps/mobile/components/cover-image.tsx | 37 +- apps/mobile/components/media-cards.tsx | 51 +- apps/mobile/components/media-context-menu.tsx | 72 +- apps/mobile/components/player.tsx | 55 +- apps/mobile/components/search-results.tsx | 53 +- apps/mobile/contexts/favorites.tsx | 235 ++++--- apps/mobile/lib/list.ts | 9 + apps/mobile/lib/song-cache.ts | 24 +- apps/mobile/lib/urls.ts | 3 + .../plugins/with-ios-pod-deployment-target.js | 64 ++ .../plugins/with-ios-scene-lifecycle.js | 125 ++++ 18 files changed, 1200 insertions(+), 726 deletions(-) create mode 100644 apps/mobile/lib/list.ts create mode 100644 apps/mobile/plugins/with-ios-pod-deployment-target.js create mode 100644 apps/mobile/plugins/with-ios-scene-lifecycle.js diff --git a/apps/mobile/app.json b/apps/mobile/app.json index fc83bd4..cb77f71 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -65,7 +65,9 @@ } ], "expo-image", - "expo-status-bar" + "expo-status-bar", + "./plugins/with-ios-pod-deployment-target.js", + "./plugins/with-ios-scene-lifecycle.js" ], "experiments": { "typedRoutes": true diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx index cbdb52c..8ec6b43 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -1,5 +1,5 @@ import { Stack, useLocalSearchParams } from "expo-router" -import { useEffect } from "react" +import { memo, useEffect, useMemo } from "react" import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" import { Ionicons } from "@expo/vector-icons" @@ -8,6 +8,7 @@ import { CoverImage } from "@/components/cover-image" import { MediaActionMenu, MediaContextMenu, + type MediaAction, } from "@/components/media-actions-sheet" import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" @@ -20,9 +21,10 @@ import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" -import type { BrowseAlbumTrack } from "@otunes/convex/types" +import type { BrowseAlbumDetail, BrowseAlbumTrack } from "@otunes/convex/types" import { formatDuration, formatMetadata } from "@/lib/format" import { useAppNavigation } from "@/lib/app-navigation" +import { longListProps } from "@/lib/list" import { albumDetailSongs, rememberSongs } from "@/lib/song-cache" import { albumCoverUrl } from "@/lib/urls" import { radius, spacing, useThemeColors } from "@/lib/theme" @@ -58,6 +60,11 @@ export default function AlbumScreen() { } }, [album]) + const songIds = useMemo( + () => album?.tracks.map((track) => track.id) ?? [], + [album?.tracks] + ) + if (album === undefined || !config) { return ( <> @@ -90,9 +97,6 @@ export default function AlbumScreen() { ) } - const songIds = album.tracks.map( - (track: BrowseAlbumTrack) => track.id as Id<"songs"> - ) const metadata = formatMetadata(album.genre, album.year) return ( @@ -126,6 +130,7 @@ export default function AlbumScreen() { }} /> track.id} style={{ flex: 1, backgroundColor }} @@ -184,57 +189,86 @@ export default function AlbumScreen() { } renderItem={({ item: track, index }) => ( - - void handleAlbumTrackAction(track, album, action) - } - > - void playFromSong(track.id, songIds)} - > - - {track.track || index + 1} - - - - {track.title} - - {track.artists ? ( - - {track.artists.join(", ")} - - ) : null} - - - {formatDuration(track.durationSeconds)} - - - + songIds={songIds} + onPlay={playFromSong} + onAction={handleAlbumTrackAction} + /> )} /> ) } +const AlbumTrackRow = memo(function AlbumTrackRow({ + track, + album, + index, + favorited, + songIds, + onPlay, + onAction, +}: { + track: BrowseAlbumTrack + album: BrowseAlbumDetail + index: number + favorited: boolean + songIds: Id<"songs">[] + onPlay: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise + onAction: ( + track: BrowseAlbumTrack, + album: BrowseAlbumDetail, + action: MediaAction + ) => Promise +}) { + const colors = useThemeColors() + + return ( + void onAction(track, album, action)} + > + void onPlay(track.id, songIds)} + > + + {track.track || index + 1} + + + + {track.title} + + {track.artists ? ( + + {track.artists.join(", ")} + + ) : null} + + + {formatDuration(track.durationSeconds)} + + + + ) +}) + const styles = StyleSheet.create({ empty: { flex: 1, alignItems: "center", justifyContent: "center" }, hero: { diff --git a/apps/mobile/app/(app)/(tabs)/home/browse/artists.tsx b/apps/mobile/app/(app)/(tabs)/home/browse/artists.tsx index 91caf3f..42999a1 100644 --- a/apps/mobile/app/(app)/(tabs)/home/browse/artists.tsx +++ b/apps/mobile/app/(app)/(tabs)/home/browse/artists.tsx @@ -1,9 +1,18 @@ import { Ionicons } from "@expo/vector-icons" import { Stack } from "expo-router" -import { useCallback } from "react" -import { FlatList, Pressable, StyleSheet, Text } from "react-native" +import { memo, useCallback } from "react" +import { + FlatList, + Pressable, + StyleSheet, + Text, + type ListRenderItemInfo, +} from "react-native" -import { MediaContextMenu } from "@/components/media-context-menu" +import { + MediaContextMenu, + type MediaAction, +} from "@/components/media-context-menu" import { CoverImage } from "@/components/cover-image" import { ArtistListSkeleton } from "@/components/skeletons" import { contentBottomInset } from "@/components/player" @@ -17,6 +26,7 @@ import { useAppNavigation } from "@/lib/app-navigation" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { api } from "@otunes/convex/_generated/api" import type { BrowseArtist } from "@otunes/convex/types" +import { longListProps } from "@/lib/list" import { artistCoverUrl } from "@/lib/urls" import { spacing, useThemeColors } from "@/lib/theme" @@ -43,6 +53,24 @@ export default function ArtistsScreen() { ? undefined : results + const serverUrl = config?.serverUrl ?? "" + const handleOpenArtist = useCallback( + (artistId: string) => push(`/artist/${artistId}`), + [push] + ) + const renderItem = useCallback( + ({ item: artist }: ListRenderItemInfo) => ( + + ), + [handleArtistAction, handleOpenArtist, isArtistFavorite, serverUrl] + ) + const handleChangeText = useCallback( (event: { nativeEvent: { text: string } }) => { onQueryChange(event.nativeEvent.text) @@ -76,46 +104,70 @@ export default function ArtistsScreen() { {searchBar} artist.id} + keyExtractor={artistKey} + renderItem={renderItem} style={{ flex: 1, backgroundColor: colors.background }} - contentContainerStyle={{ paddingBottom: contentBottomInset }} + contentContainerStyle={styles.listContent} contentInsetAdjustmentBehavior="automatic" onEndReached={() => { if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE) }} onEndReachedThreshold={0.5} - renderItem={({ item: artist }: { item: BrowseArtist }) => ( - void handleArtistAction(artist, action)} - > - push(`/artist/${artist.id}`)} - > - - - {artist.name} - - - - - )} /> ) } +function artistKey(artist: BrowseArtist) { + return artist.id +} + +const ArtistRow = memo(function ArtistRow({ + artist, + serverUrl, + favorited, + onOpen, + onAction, +}: { + artist: BrowseArtist + serverUrl: string + favorited: boolean + onOpen: (artistId: string) => void + onAction: (artist: BrowseArtist, action: MediaAction) => Promise +}) { + const colors = useThemeColors() + + return ( + void onAction(artist, action)} + > + onOpen(artist.id)} + > + + + {artist.name} + + + + + ) +}) + const styles = StyleSheet.create({ + listContent: { paddingBottom: contentBottomInset }, row: { flexDirection: "row", alignItems: "center", diff --git a/apps/mobile/app/(app)/(tabs)/home/browse/songs.tsx b/apps/mobile/app/(app)/(tabs)/home/browse/songs.tsx index 5b7fd3d..204c67a 100644 --- a/apps/mobile/app/(app)/(tabs)/home/browse/songs.tsx +++ b/apps/mobile/app/(app)/(tabs)/home/browse/songs.tsx @@ -1,8 +1,9 @@ import { Stack } from "expo-router" import { useCallback, useState } from "react" -import { FlatList, StyleSheet } from "react-native" +import { FlatList, StyleSheet, type ListRenderItemInfo } from "react-native" -import { contentBottomInset, SongRow } from "@/components/player" +import type { MediaAction } from "@/components/media-context-menu" +import { contentBottomInset, SongListRow } from "@/components/player" import { SongListSkeleton } from "@/components/skeletons" import { useFavorites } from "@/contexts/favorites" import { usePlaybackActions } from "@/contexts/playback" @@ -13,8 +14,8 @@ import { import { useDebouncedSearch } from "@/hooks/use-debounced-search" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { api } from "@otunes/convex/_generated/api" -import type { Id } from "@otunes/convex/_generated/dataModel" -import { spacing } from "@/lib/theme" +import type { BrowseSong } from "@otunes/convex/types" +import { longListProps } from "@/lib/list" const PAGE_SIZE = 50 @@ -41,6 +42,28 @@ export default function SongsScreen() { ? undefined : results + const handlePlaySong = useCallback( + (song: BrowseSong) => + void playFromLibrarySong(song.id, { sortKey, sortDirection }), + [playFromLibrarySong, sortDirection, sortKey] + ) + const handleSongMenuAction = useCallback( + (song: BrowseSong, action: MediaAction) => + void handleSongAction(song, action), + [handleSongAction] + ) + const renderItem = useCallback( + ({ item }: ListRenderItemInfo) => ( + + ), + [handlePlaySong, handleSongMenuAction, isSongFavorite] + ) + const handleChangeText = useCallback( (event: { nativeEvent: { text: string } }) => { onQueryChange(event.nativeEvent.text) @@ -74,49 +97,25 @@ export default function SongsScreen() { {searchBar} item.id} - contentContainerStyle={{ paddingBottom: contentBottomInset }} + keyExtractor={songKey} + renderItem={renderItem} + contentContainerStyle={styles.listContent} contentInsetAdjustmentBehavior="automatic" onEndReached={() => { if (!searchQuery && status === "CanLoadMore") loadMore(PAGE_SIZE) }} onEndReachedThreshold={0.5} - renderItem={({ item }) => ( - - void playFromLibrarySong(item.id as Id<"songs">, { - sortKey, - sortDirection, - }) - } - contextMenu={{ - favorited: isSongFavorite(item.id), - navigation: { - artist: { id: item.artist.id }, - album: { id: item.album.id }, - }, - share: { - type: "song", - albumId: item.album.id, - songId: item.id, - }, - onAction: (action) => void handleSongAction(item, action), - }} - /> - )} /> ) } +function songKey(song: BrowseSong) { + return song.id +} + const styles = StyleSheet.create({ - sortRow: { - flexDirection: "row", - justifyContent: "space-around", - paddingVertical: spacing.sm, - borderBottomWidth: StyleSheet.hairlineWidth, - }, - sortButton: { padding: spacing.sm }, + listContent: { paddingBottom: contentBottomInset }, }) diff --git a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx index 513be43..995a307 100644 --- a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx @@ -1,32 +1,13 @@ import { useMutation } from "convex/react" -import { useEffect } from "react" -import { - Button as SwiftUIButton, - ContextMenu, - Host, - List, - RNHostView, - SwipeActions, -} from "@expo/ui/swift-ui" -import { - frame, - listRowBackground, - listRowInsets, - listRowSeparator, - listSectionSpacing, - listRowSpacing, - listStyle, - onAppear, - scrollContentBackground, -} from "@expo/ui/swift-ui/modifiers" +import { memo, useCallback, useEffect, useMemo } from "react" import { Stack, useLocalSearchParams, useRouter } from "expo-router" import { FlatList, - Platform, Pressable, StyleSheet, Text, View, + type ListRenderItemInfo, } from "react-native" import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable" import { Ionicons } from "@expo/vector-icons" @@ -39,7 +20,7 @@ import { } from "@/components/media-actions-sheet" import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" -import { contentBottomInset, SongRow } from "@/components/player" +import { contentBottomInset, SongListRow } from "@/components/player" import { useFavorites } from "@/contexts/favorites" import { usePlaybackActions } from "@/contexts/playback" import { useServerConfig } from "@/contexts/server-config" @@ -51,19 +32,27 @@ import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { api } from "@otunes/convex/_generated/api" import type { Id } from "@otunes/convex/_generated/dataModel" -import type { BrowseSong } from "@otunes/convex/types" -import { shareMediaLink } from "@/lib/share-media-link" +import type { BrowsePlaylistDetail, BrowseSong } from "@otunes/convex/types" +import { longListProps } from "@/lib/list" import { rememberSongs } from "@/lib/song-cache" import { showError, showSuccess } from "@/lib/toast" import { playlistCoverUrl } from "@/lib/urls" import { radius, spacing, useThemeColors } from "@/lib/theme" const PAGE_SIZE = 50 -const NATIVE_LOAD_MORE_THRESHOLD = 10 +const PLAYLIST_LABEL = "Add to Another Playlist" +const OWNER_MENU_ACTIONS: MediaAction[] = [ + "share", + "playlist", + "play-next", + "play-last", + "shuffle", + "favorite", + "delete-playlist", +] export default function PlaylistScreen() { const { id } = useLocalSearchParams<{ id: string }>() - const router = useRouter() const colors = useThemeColors() const { config } = useServerConfig() const playlistId = typeof id === "string" ? (id as Id<"playlists">) : null @@ -90,14 +79,6 @@ export default function PlaylistScreen() { api.playlists.getPlaylistSongIds, playlistId ? { playlistId } : "skip" ) - const { playPlaylist, playPlaylistShuffled, playFromSong } = - usePlaybackActions() - const { isSongFavorite } = useFavorites() - const { handleSongAction, handlePlaylistDetailAction } = useMediaMenuActions() - const subscribe = useMutation(api.playlists.subscribeToPlaylist) - const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist) - const deletePlaylist = useMutation(api.playlists.deletePlaylist) - const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist) const coverUri = config && playlist ? playlistCoverUrl(config.serverUrl, playlist.id ?? "favorites") @@ -148,21 +129,96 @@ export default function PlaylistScreen() { ) } - const songIds = allSongIds ?? songs.map((song) => song.id) - const serverUrl = config.serverUrl + return ( + { + if (status === "CanLoadMore") loadMore(PAGE_SIZE) + }} + /> + ) +} - function maybeLoadMore() { - if (status === "CanLoadMore") loadMore(PAGE_SIZE) - } +function PlaylistContent({ + playlist, + songs, + allSongIds, + coverUri, + backgroundColor, + onEndReached, +}: { + playlist: BrowsePlaylistDetail + songs: BrowseSong[] + allSongIds: Id<"songs">[] | undefined + coverUri: string + backgroundColor: string + onEndReached: () => void +}) { + const router = useRouter() + const colors = useThemeColors() + const { playPlaylist, playPlaylistShuffled, playFromSong } = + usePlaybackActions() + const { isSongFavorite } = useFavorites() + const { handleSongAction, handlePlaylistDetailAction } = useMediaMenuActions() + const subscribe = useMutation(api.playlists.subscribeToPlaylist) + const unsubscribe = useMutation(api.playlists.unsubscribeFromPlaylist) + const deletePlaylist = useMutation(api.playlists.deletePlaylist) + const removeSongs = useMutation(api.playlists.removeSongsFromPlaylist) - async function handleSubscribeToggle() { - if (!playlist?.id) return + const playlistId = playlist.id + const isSubscribed = playlist.isSubscribed + const canEdit = playlist.isOwner && playlistId !== null + const loadedSongIds = useMemo(() => songs.map((song) => song.id), [songs]) + const songIds = allSongIds ?? loadedSongIds + + const handlePlaySong = useCallback( + (song: BrowseSong) => void playFromSong(song.id, songIds), + [playFromSong, songIds] + ) + + const handleSongMenuAction = useCallback( + (song: BrowseSong, action: MediaAction) => + void handleSongAction(song, action), + [handleSongAction] + ) + + const handleRemoveSong = useCallback( + async (songId: Id<"songs">) => { + if (!playlistId) return + try { + await removeSongs({ playlistId, songIds: [songId] }) + showSuccess("Removed from playlist") + } catch (error) { + showError( + error instanceof Error + ? error.message + : "Failed to remove from playlist" + ) + } + }, + [playlistId, removeSongs] + ) + + const handlePlay = useCallback(() => { + if (playlistId) void playPlaylist(playlistId, allSongIds) + }, [allSongIds, playPlaylist, playlistId]) + + const handleShuffle = useCallback(() => { + if (playlistId) void playPlaylistShuffled(playlistId, allSongIds) + }, [allSongIds, playPlaylistShuffled, playlistId]) + + const handleSubscribeToggle = useCallback(async () => { + if (!playlistId) return try { - if (playlist.isSubscribed) { - await unsubscribe({ playlistId: playlist.id }) + if (isSubscribed) { + await unsubscribe({ playlistId }) showSuccess("Unsubscribed") } else { - await subscribe({ playlistId: playlist.id }) + await subscribe({ playlistId }) showSuccess("Subscribed") } } catch (error) { @@ -170,318 +226,194 @@ export default function PlaylistScreen() { error instanceof Error ? error.message : "Failed to update subscription" ) } - } + }, [isSubscribed, playlistId, subscribe, unsubscribe]) - async function handleDelete() { - if (!playlist?.id) return - try { - await deletePlaylist({ playlistId: playlist.id }) - showSuccess("Playlist deleted") - router.back() - } catch (error) { - showError( - error instanceof Error ? error.message : "Failed to delete playlist" - ) - } - } - - function handlePlaylistMenuAction(action: MediaAction) { - if (action === "delete-playlist") { - void handleDelete() - return + const screenOptions = useMemo(() => { + async function handleDelete() { + if (!playlistId) return + try { + await deletePlaylist({ playlistId }) + showSuccess("Playlist deleted") + router.back() + } catch (error) { + showError( + error instanceof Error ? error.message : "Failed to delete playlist" + ) + } } - void handlePlaylistDetailAction(songIds, action) - } + function handlePlaylistMenuAction(action: MediaAction) { + if (action === "delete-playlist") { + void handleDelete() + return + } - async function handleRemoveSong(songId: Id<"songs">) { - if (!playlist?.id) return - try { - await removeSongs({ playlistId: playlist.id, songIds: [songId] }) - showSuccess("Removed from playlist") - } catch (error) { - showError( - error instanceof Error - ? error.message - : "Failed to remove from playlist" - ) + void handlePlaylistDetailAction(songIds, action) } - } - function renderSongRow(song: BrowseSong, includeContextMenu = true) { - const row = ( - ( + + + + + + ), + } + }, [ + canEdit, + colors.foreground, + deletePlaylist, + handlePlaylistDetailAction, + playlistId, + router, + songIds, + ]) + + const renderItem = useCallback( + ({ item: song }: ListRenderItemInfo) => ( + void playFromSong(song.id, songIds)} - contextMenu={ - includeContextMenu - ? { - favorited: isSongFavorite(song.id), - playlistLabel: "Add to Another Playlist", - navigation: { - artist: { id: song.artist.id }, - album: { id: song.album.id }, - }, - share: { - type: "song", - albumId: song.album.id, - songId: song.id, - }, - onAction: (action) => void handleSongAction(song, action), - } - : undefined - } + favorited={isSongFavorite(song.id)} + removable={canEdit} + backgroundColor={backgroundColor} + onPlay={handlePlaySong} + onAction={handleSongMenuAction} + onRemove={handleRemoveSong} /> - ) - - return row - } - - function renderNativeSongContextMenu(song: BrowseSong) { - return ( - - - void shareMediaLink(serverUrl, { - type: "song", - albumId: song.album.id, - songId: song.id, - }) - } - /> - void handleSongAction(song, "playlist")} - /> - void handleSongAction(song, "play-next")} - /> - void handleSongAction(song, "play-last")} - /> - void handleSongAction(song, "shuffle")} - /> - void handleSongAction(song, "go-artist")} - /> - void handleSongAction(song, "go-album")} - /> - void handleSongAction(song, "favorite")} - /> - - ) - } - - const nativeListRowModifiers = [ - listRowBackground(backgroundColor), - listRowInsets({ top: 0, leading: 0, bottom: 0, trailing: 0 }), - listRowSeparator("hidden"), - ] - const nativeSongRowModifiers = [frame({ height: 32 })] - const shouldUseNativeSwipeList = - Platform.OS === "ios" && playlist.isOwner && playlist.id + ), + [ + backgroundColor, + canEdit, + handlePlaySong, + handleRemoveSong, + handleSongMenuAction, + isSongFavorite, + ] + ) return ( <> - ( - - - - - - ), - }} + + + } /> - {shouldUseNativeSwipeList ? ( - - - - - playlist.id && void playPlaylist(playlist.id, allSongIds)} - onShuffle={() => - playlist.id && void playPlaylistShuffled(playlist.id, allSongIds) - } - /> - - - {songs.map((song, index) => { - const nearEnd = index >= songs.length - NATIVE_LOAD_MORE_THRESHOLD - return ( - - - - - - {renderSongRow(song, false)} - - - - {renderNativeSongContextMenu(song)} - - - void handleRemoveSong(song.id)} - /> - - - ) - })} - - - ) : ( - song.id} - style={{ flex: 1, backgroundColor }} - contentContainerStyle={{ paddingBottom: contentBottomInset }} - contentInsetAdjustmentBehavior="automatic" - onEndReached={maybeLoadMore} - onEndReachedThreshold={0.5} - ListHeaderComponent={ - void handleSubscribeToggle()} - onPlay={() => playlist.id && void playPlaylist(playlist.id, allSongIds)} - onShuffle={() => - playlist.id && void playPlaylistShuffled(playlist.id, allSongIds) - } - /> - } - renderItem={({ item: song }) => { - const row = renderSongRow(song) - - if (!playlist.isOwner || !playlist.id) { - return {row} - } - - return ( - ( - { - swipeable.close() - void handleRemoveSong(song.id) - }} - style={[ - styles.removeAction, - { backgroundColor: colors.destructive }, - ]} - > - - - Remove - - - )} - > - {row} - - ) - }} - /> - )} ) } -function PlaylistHero({ +function songKey(song: BrowseSong) { + return song.id +} + +const PlaylistSongRow = memo(function PlaylistSongRow({ + song, + favorited, + removable, + backgroundColor, + onPlay, + onAction, + onRemove, +}: { + song: BrowseSong + favorited: boolean + removable: boolean + backgroundColor: string + onPlay: (song: BrowseSong) => void + onAction: (song: BrowseSong, action: MediaAction) => void + onRemove: (songId: Id<"songs">) => void +}) { + const colors = useThemeColors() + const row = ( + + ) + + if (!removable) { + return row + } + + return ( + ( + { + swipeable.close() + onRemove(song.id) + }} + style={[styles.removeAction, { backgroundColor: colors.destructive }]} + > + + + Remove + + + )} + > + {row} + + ) +}) + +const PlaylistHero = memo(function PlaylistHero({ coverUri, hasCover, title, ownerName, - colors, isSubscribed, showSubscribe = false, onSubscribeToggle, @@ -492,13 +424,14 @@ function PlaylistHero({ hasCover: boolean title: string ownerName: string - colors: ReturnType isSubscribed?: boolean showSubscribe?: boolean onSubscribeToggle?: () => void onPlay: () => void onShuffle: () => void }) { + const colors = useThemeColors() + return ( @@ -546,10 +479,11 @@ function PlaylistHero({ ) -} +}) const styles = StyleSheet.create({ empty: { flex: 1, alignItems: "center", justifyContent: "center" }, + listContent: { paddingBottom: contentBottomInset }, hero: { alignItems: "center", padding: spacing.lg, gap: spacing.sm }, cover: { width: 200, @@ -572,15 +506,6 @@ const styles = StyleSheet.create({ alignItems: "center", justifyContent: "center", }, - iosSwipeListHost: { - flex: 1, - alignSelf: "stretch", - width: "100%", - }, - nativeSongRow: { - height: 64, - overflow: "hidden", - }, removeAction: { width: 96, alignItems: "center", diff --git a/apps/mobile/app/(app)/(tabs)/home/playlist/favorites.tsx b/apps/mobile/app/(app)/(tabs)/home/playlist/favorites.tsx index 7549d8f..1f4a24a 100644 --- a/apps/mobile/app/(app)/(tabs)/home/playlist/favorites.tsx +++ b/apps/mobile/app/(app)/(tabs)/home/playlist/favorites.tsx @@ -1,44 +1,99 @@ -import { useEffect } from "react" -import { FlatList, Pressable, StyleSheet, Text, View } from "react-native" +import { memo, useCallback, useEffect, useMemo } from "react" +import { + FlatList, + Pressable, + StyleSheet, + Text, + View, + type ListRenderItemInfo, +} from "react-native" import { CollectionDetailSkeleton } from "@/components/skeletons" import { Button } from "@/components/ui/primitives" -import { contentBottomInset, SongRow } from "@/components/player" +import { contentBottomInset, SongListRow } from "@/components/player" import { useFavorites } from "@/contexts/favorites" import { usePlaybackActions } from "@/contexts/playback" import { useServerConfig } from "@/contexts/server-config" -import { useCachedQuery } from "@/hooks/use-cached-query" +import { + useCachedPaginatedQuery, + useCachedQuery, +} from "@/hooks/use-cached-query" import { useMediaMenuActions } from "@/hooks/use-media-menu-actions" import { api } from "@otunes/convex/_generated/api" +import type { MediaAction } from "@/components/media-context-menu" import type { BrowseSong } from "@otunes/convex/types" +import { longListProps } from "@/lib/list" import { rememberSongs } from "@/lib/song-cache" import { radius, spacing, useThemeColors } from "@/lib/theme" import { Ionicons } from "@expo/vector-icons" import { Stack } from "expo-router" +const PAGE_SIZE = 50 +const SCREEN_OPTIONS = { title: "", headerLargeTitle: false } + export default function FavoritesScreen() { const colors = useThemeColors() const { config } = useServerConfig() - const favorites = useCachedQuery(api.favorites.browseFavoritesPlaylistDetail) + const favorites = useCachedQuery(api.favorites.browseFavoritesSummary) + const { + results: songs, + status, + loadMore, + isCached, + } = useCachedPaginatedQuery( + api.favorites.browseFavoritesSongsPaginated, + {}, + { initialNumItems: PAGE_SIZE } + ) const { playInOrder, playShuffled, playFromSong } = usePlaybackActions() const { isSongFavorite } = useFavorites() const { handleSongAction } = useMediaMenuActions() + const loadedSongIds = useMemo(() => songs.map((song) => song.id), [songs]) + const songIds = favorites?.songIds ?? loadedSongIds useEffect(() => { - if (favorites) { - rememberSongs(favorites.songs) - } - }, [favorites]) + rememberSongs(songs) + }, [songs]) - if (favorites === undefined || !config) { + const handlePlaySong = useCallback( + (song: BrowseSong) => void playFromSong(song.id, songIds), + [playFromSong, songIds] + ) + const handleSongMenuAction = useCallback( + (song: BrowseSong, action: MediaAction) => + void handleSongAction(song, action), + [handleSongAction] + ) + const handlePlay = useCallback( + () => void playInOrder(songIds), + [playInOrder, songIds] + ) + const handleShuffle = useCallback( + () => void playShuffled(songIds), + [playShuffled, songIds] + ) + + const renderItem = useCallback( + ({ item: song }: ListRenderItemInfo) => ( + + ), + [handlePlaySong, handleSongMenuAction, isSongFavorite] + ) + + if ( + favorites === undefined || + (status === "LoadingFirstPage" && !isCached) || + !config + ) { return ( <> - + ) @@ -47,12 +102,7 @@ export default function FavoritesScreen() { if (favorites === null) { return ( <> - + Sign in to view your favorites. @@ -62,92 +112,95 @@ export default function FavoritesScreen() { ) } - const songIds = favorites.songs.map((song: BrowseSong) => song.id) - return ( <> - + song.id} + {...longListProps} + data={songs} + keyExtractor={songKey} + renderItem={renderItem} style={{ flex: 1, backgroundColor: colors.background }} - contentContainerStyle={{ paddingBottom: contentBottomInset }} + contentContainerStyle={styles.listContent} contentInsetAdjustmentBehavior="automatic" + onEndReached={() => { + if (status === "CanLoadMore") loadMore(PAGE_SIZE) + }} + onEndReachedThreshold={0.5} ListHeaderComponent={ - - - - - - {favorites.title} - - -