diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx
index cbdb52c..da446d0 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,7 +21,7 @@ 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 { albumDetailSongs, rememberSongs } from "@/lib/song-cache"
@@ -58,6 +59,11 @@ export default function AlbumScreen() {
}
}, [album])
+ const songIds = useMemo(
+ () => album?.tracks.map((track) => track.id) ?? [],
+ [album?.tracks]
+ )
+
if (album === undefined || !config) {
return (
<>
@@ -90,9 +96,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 (
@@ -184,57 +187,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}
-
-
-
-
- }
- renderItem={({ item: song }: { item: BrowseSong }) => (
- void playFromSong(song.id, songIds)}
- contextMenu={{
- 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),
- }}
+
- )}
+ }
/>
>
)
}
+function songKey(song: BrowseSong) {
+ return song.id
+}
+
+const FavoritesHero = memo(function FavoritesHero({
+ title,
+ onPlay,
+ onShuffle,
+}: {
+ title: string
+ onPlay: () => void
+ onShuffle: () => void
+}) {
+ const colors = useThemeColors()
+
+ return (
+
+
+
+
+ {title}
+
+
+
+
+
+
+
+ )
+})
+
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,
height: 200,
borderRadius: radius.lg,
},
+ coverPlaceholder: {
+ alignItems: "center",
+ justifyContent: "center",
+ overflow: "hidden",
+ },
title: { fontSize: 24, fontWeight: "800" },
actions: {
flexDirection: "row",
diff --git a/apps/mobile/app/(app)/(tabs)/home/queue.tsx b/apps/mobile/app/(app)/(tabs)/home/queue.tsx
index a404fbc..c5e12a0 100644
--- a/apps/mobile/app/(app)/(tabs)/home/queue.tsx
+++ b/apps/mobile/app/(app)/(tabs)/home/queue.tsx
@@ -7,10 +7,16 @@ import { contentBottomInset, SongRow } from "@/components/player"
import { SongRowSkeleton } from "@/components/skeletons"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import type { Id } from "@otunes/convex/_generated/dataModel"
+import { longListProps } from "@/lib/list"
import { useSong, useSongs } from "@/lib/song-cache"
import { spacing, useThemeColors } from "@/lib/theme"
-type QueueItem = { songId: Id<"songs">; queueIndex: number }
+/** `key` stays stable when earlier songs leave the queue, so rows are not remounted on skip. */
+type QueueItem = { songId: Id<"songs">; queueIndex: number; key: string }
+
+function queueItemKey(item: QueueItem) {
+ return item.key
+}
const QueueRow = memo(function QueueRow({
songId,
@@ -19,7 +25,7 @@ const QueueRow = memo(function QueueRow({
isCurrent,
onSkipTo,
onMove,
-}: QueueItem & {
+}: Omit & {
isLast: boolean
isCurrent: boolean
onSkipTo: (index: number) => void
@@ -62,10 +68,14 @@ export default function QueueScreen() {
const { skipToQueueIndex, clearQueue, reorderQueue } = usePlaybackActions()
const historySongs = useSongs(queueHistorySongIds)
- const items = useMemo(
- () => queueSongIds.map((songId, queueIndex) => ({ songId, queueIndex })),
- [queueSongIds]
- )
+ const items = useMemo(() => {
+ const occurrences = new Map()
+ return queueSongIds.map((songId, queueIndex) => {
+ const occurrence = occurrences.get(songId) ?? 0
+ occurrences.set(songId, occurrence + 1)
+ return { songId, queueIndex, key: `${songId}:${occurrence}` }
+ })
+ }, [queueSongIds])
const moveSong = useCallback(
(fromIndex: number, direction: -1 | 1) => {
@@ -119,14 +129,15 @@ export default function QueueScreen() {
) : null}
}
+ {...longListProps}
data={items}
- keyExtractor={(item) => `${item.songId}-${item.queueIndex}`}
+ keyExtractor={queueItemKey}
contentContainerStyle={{ paddingBottom: contentBottomInset }}
contentInsetAdjustmentBehavior="automatic"
- initialNumToRender={15}
renderItem={({ item }) => (
size >= requiredPixels) ??
DEFAULT_SOURCE_SIZE
@@ -49,6 +50,12 @@ function placeholderIconSize(style: ImageStyle): number {
return 48
}
+const placeholderBaseStyle: ViewStyle = {
+ alignItems: "center",
+ justifyContent: "center",
+ overflow: "hidden",
+}
+
export const CoverImage = memo(function CoverImage({
uri,
hasCover,
@@ -65,18 +72,22 @@ export const CoverImage = memo(function CoverImage({
placeholderVariant?: "icon" | "solid"
}) {
const colors = useThemeColors()
- const flatStyle = StyleSheet.flatten(style) ?? {}
+ const flatStyle = useMemo(() => StyleSheet.flatten(style) ?? {}, [style])
+ const sourceUri = useMemo(
+ () => (hasCover ? withCoverImageSize(uri, sourceSize(flatStyle)) : ""),
+ [flatStyle, hasCover, uri]
+ )
+ const source = useMemo(() => ({ uri: sourceUri }), [sourceUri])
if (!hasCover) {
- const placeholderStyle: ViewStyle = {
- backgroundColor: colors.coverPlaceholder,
- alignItems: "center",
- justifyContent: "center",
- overflow: "hidden",
- }
-
return (
-
+
{placeholderVariant === "icon" ? (
) => (
+
+
+
+ ),
+ [cardWidth]
+ )
return (
item.id}
+ keyExtractor={mediaItemKey}
+ renderItem={renderItem}
numColumns={2}
+ initialNumToRender={GRID_INITIAL_ROWS}
+ maxToRenderPerBatch={GRID_INITIAL_ROWS}
+ windowSize={longListProps.windowSize}
style={{ flex: 1, backgroundColor: colors.background }}
contentContainerStyle={[
contentInset ? styles.gridListContent : styles.gridListContentInset,
@@ -225,15 +247,22 @@ export function MediaGridList({
ListHeaderComponent={ListHeaderComponent}
onEndReached={onEndReached}
onEndReachedThreshold={0.5}
- renderItem={({ item }) => (
-
-
-
- )}
/>
)
}
+function mediaItemKey(item: MediaItem) {
+ return item.id
+}
+
+function renderCarouselItem({ item }: ListRenderItemInfo) {
+ return (
+
+
+
+ )
+}
+
function ContentCarouselBody({
title,
href,
@@ -271,15 +300,11 @@ function ContentCarouselBody({
item.id}
+ keyExtractor={mediaItemKey}
+ renderItem={renderCarouselItem}
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.carouselContent}
- renderItem={({ item }) => (
-
-
-
- )}
/>
)
diff --git a/apps/mobile/components/player.tsx b/apps/mobile/components/player.tsx
index cace95c..93d4a59 100644
--- a/apps/mobile/components/player.tsx
+++ b/apps/mobile/components/player.tsx
@@ -3,20 +3,17 @@ import { useServerConfig } from "@/contexts/server-config"
import type { BrowseSong } from "@otunes/convex/types"
import { formatDuration } from "@/lib/format"
import { albumCoverUrl } from "@/lib/urls"
-import {
- miniPlayerHeight,
- spacing,
- tabBarHeight,
- useThemeColors,
-} from "@/lib/theme"
+import { miniPlayerHeight, spacing, useThemeColors } from "@/lib/theme"
+import { memo, useCallback } from "react"
import { Pressable, StyleSheet, Text, View } from "react-native"
import {
MediaContextMenu,
+ type MediaAction,
type MediaMenuConfig,
} from "@/components/media-context-menu"
-export function SongRow({
+export const SongRow = memo(function SongRow({
song,
onPress,
contextMenu,
@@ -67,7 +64,49 @@ export function SongRow({
{row}
)
-}
+})
+
+/**
+ * A `SongRow` with the standard song context menu. Pass stable `onPlay` and
+ * `onAction` callbacks so rows in long lists only re-render when their own
+ * song or favorite state changes.
+ */
+export const SongListRow = memo(function SongListRow({
+ song,
+ favorited,
+ playlistLabel,
+ onPlay,
+ onAction,
+}: {
+ song: BrowseSong
+ favorited: boolean
+ playlistLabel?: string
+ onPlay: (song: BrowseSong) => void
+ onAction: (song: BrowseSong, action: MediaAction) => void
+}) {
+ const handlePress = useCallback(() => onPlay(song), [onPlay, song])
+
+ return (
+ onAction(song, action),
+ }}
+ />
+ )
+})
export const tabContentBottomInset = spacing.lg
export const contentBottomInset = miniPlayerHeight + spacing.lg
diff --git a/apps/mobile/components/search-results.tsx b/apps/mobile/components/search-results.tsx
index d523f82..b1498d7 100644
--- a/apps/mobile/components/search-results.tsx
+++ b/apps/mobile/components/search-results.tsx
@@ -1,8 +1,15 @@
-import { memo, useMemo } from "react"
-import { FlatList, StyleSheet, Text, View } from "react-native"
+import { memo, useCallback, useMemo } from "react"
+import {
+ FlatList,
+ StyleSheet,
+ Text,
+ View,
+ type ListRenderItemInfo,
+} from "react-native"
import { ContentCarousel } from "@/components/media-cards"
-import { tabContentBottomInset, SongRow } from "@/components/player"
+import type { MediaAction } from "@/components/media-context-menu"
+import { tabContentBottomInset, SongListRow } from "@/components/player"
import { SongListSkeleton } from "@/components/skeletons"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions } from "@/contexts/playback"
@@ -47,6 +54,26 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
() => results?.songs.map((song) => song.id) ?? [],
[results?.songs]
)
+ 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 renderItem = useCallback(
+ ({ item: song }: ListRenderItemInfo) => (
+
+ ),
+ [handlePlaySong, handleSongMenuAction, isSongFavorite]
+ )
if (isSearching) {
return
@@ -89,25 +116,7 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
) : null}
>
}
- renderItem={({ item: song }: { item: BrowseSong }) => (
- void playFromSong(song.id, songIds)}
- contextMenu={{
- favorited: isSongFavorite(song.id),
- 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),
- }}
- />
- )}
+ renderItem={renderItem}
ListFooterComponent={
playlistResults && playlistResults.length > 0 ? (
diff --git a/apps/mobile/contexts/favorites.tsx b/apps/mobile/contexts/favorites.tsx
index c145d0c..0c7829b 100644
--- a/apps/mobile/contexts/favorites.tsx
+++ b/apps/mobile/contexts/favorites.tsx
@@ -1,9 +1,12 @@
-import { useMutation } from "convex/react"
+import type { OptimisticUpdate } from "convex/browser"
+import { useMutation, type ReactMutation } from "convex/react"
+import type { FunctionArgs, FunctionReference } from "convex/server"
import {
createContext,
useCallback,
useContext,
useMemo,
+ useRef,
type ReactNode,
} from "react"
@@ -12,6 +15,19 @@ import { api } from "@otunes/convex/_generated/api"
import type { Id } from "@otunes/convex/_generated/dataModel"
import { showError, showSuccess } from "@/lib/toast"
+/**
+ * `useMutation(...).withOptimisticUpdate(...)` with a stable identity. The
+ * update is captured on first render, so it must not close over render state.
+ */
+function useOptimisticMutation>(
+ mutation: Mutation,
+ optimisticUpdate: OptimisticUpdate>
+): ReactMutation {
+ const base = useMutation(mutation)
+ const updateRef = useRef(optimisticUpdate)
+ return useMemo(() => base.withOptimisticUpdate(updateRef.current), [base])
+}
+
type FavoritesContextValue = {
isSongFavorite: (songId: string) => boolean
isAlbumFavorite: (albumId: string) => boolean
@@ -34,102 +50,113 @@ export function useFavorites() {
export function FavoritesProvider({ children }: { children: ReactNode }) {
const favorites = useCachedQuery(api.favorites.getUserFavorites)
- const favoriteSong = useMutation(
- api.favorites.favoriteSong
- ).withOptimisticUpdate((store, { songId }) => {
- const current = store.getQuery(api.favorites.getUserFavorites, {})
- if (!current || current.favoriteSongs.includes(songId)) return
- store.setQuery(
- api.favorites.getUserFavorites,
- {},
- {
- ...current,
- favoriteSongs: [...current.favoriteSongs, songId],
- }
- )
- })
- const unfavoriteSong = useMutation(
- api.favorites.unfavoriteSong
- ).withOptimisticUpdate((store, { songId }) => {
- const current = store.getQuery(api.favorites.getUserFavorites, {})
- if (!current) return
- store.setQuery(
- api.favorites.getUserFavorites,
- {},
- {
- ...current,
- favoriteSongs: current.favoriteSongs.filter((id) => id !== songId),
- }
- )
- })
- const favoriteAlbum = useMutation(
- api.favorites.favoriteAlbum
- ).withOptimisticUpdate((store, { albumId }) => {
- const current = store.getQuery(api.favorites.getUserFavorites, {})
- if (!current || current.favoriteAlbums.includes(albumId)) return
- store.setQuery(
- api.favorites.getUserFavorites,
- {},
- {
- ...current,
- favoriteAlbums: [...current.favoriteAlbums, albumId],
- }
- )
- })
- const unfavoriteAlbum = useMutation(
- api.favorites.unfavoriteAlbum
- ).withOptimisticUpdate((store, { albumId }) => {
- const current = store.getQuery(api.favorites.getUserFavorites, {})
- if (!current) return
- store.setQuery(
- api.favorites.getUserFavorites,
- {},
- {
- ...current,
- favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId),
- }
- )
- })
- const favoriteArtist = useMutation(
- api.favorites.favoriteArtist
- ).withOptimisticUpdate((store, { artistId }) => {
- const current = store.getQuery(api.favorites.getUserFavorites, {})
- if (!current || current.favoriteArtists.includes(artistId)) return
- store.setQuery(
- api.favorites.getUserFavorites,
- {},
- {
- ...current,
- favoriteArtists: [...current.favoriteArtists, artistId],
- }
- )
- })
- const unfavoriteArtist = useMutation(
- api.favorites.unfavoriteArtist
- ).withOptimisticUpdate((store, { artistId }) => {
- const current = store.getQuery(api.favorites.getUserFavorites, {})
- if (!current) return
- store.setQuery(
- api.favorites.getUserFavorites,
- {},
- {
- ...current,
- favoriteArtists: current.favoriteArtists.filter(
- (id) => id !== artistId
- ),
- }
- )
- })
- const favoriteSongsMutation = useMutation(
- api.favorites.favoriteSongs
- ).withOptimisticUpdate((store, { songIds }) => {
- const current = store.getQuery(api.favorites.getUserFavorites, {})
- if (!current) return
- store.setQuery(api.favorites.getUserFavorites, {}, {
- ...current,
- favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])],
- })
- })
+ const favoriteSong = useOptimisticMutation(
+ api.favorites.favoriteSong,
+ (store, { songId }) => {
+ const current = store.getQuery(api.favorites.getUserFavorites, {})
+ if (!current || current.favoriteSongs.includes(songId)) return
+ store.setQuery(
+ api.favorites.getUserFavorites,
+ {},
+ {
+ ...current,
+ favoriteSongs: [...current.favoriteSongs, songId],
+ }
+ )
+ }
+ )
+ const unfavoriteSong = useOptimisticMutation(
+ api.favorites.unfavoriteSong,
+ (store, { songId }) => {
+ const current = store.getQuery(api.favorites.getUserFavorites, {})
+ if (!current) return
+ store.setQuery(
+ api.favorites.getUserFavorites,
+ {},
+ {
+ ...current,
+ favoriteSongs: current.favoriteSongs.filter((id) => id !== songId),
+ }
+ )
+ }
+ )
+ const favoriteAlbum = useOptimisticMutation(
+ api.favorites.favoriteAlbum,
+ (store, { albumId }) => {
+ const current = store.getQuery(api.favorites.getUserFavorites, {})
+ if (!current || current.favoriteAlbums.includes(albumId)) return
+ store.setQuery(
+ api.favorites.getUserFavorites,
+ {},
+ {
+ ...current,
+ favoriteAlbums: [...current.favoriteAlbums, albumId],
+ }
+ )
+ }
+ )
+ const unfavoriteAlbum = useOptimisticMutation(
+ api.favorites.unfavoriteAlbum,
+ (store, { albumId }) => {
+ const current = store.getQuery(api.favorites.getUserFavorites, {})
+ if (!current) return
+ store.setQuery(
+ api.favorites.getUserFavorites,
+ {},
+ {
+ ...current,
+ favoriteAlbums: current.favoriteAlbums.filter((id) => id !== albumId),
+ }
+ )
+ }
+ )
+ const favoriteArtist = useOptimisticMutation(
+ api.favorites.favoriteArtist,
+ (store, { artistId }) => {
+ const current = store.getQuery(api.favorites.getUserFavorites, {})
+ if (!current || current.favoriteArtists.includes(artistId)) return
+ store.setQuery(
+ api.favorites.getUserFavorites,
+ {},
+ {
+ ...current,
+ favoriteArtists: [...current.favoriteArtists, artistId],
+ }
+ )
+ }
+ )
+ const unfavoriteArtist = useOptimisticMutation(
+ api.favorites.unfavoriteArtist,
+ (store, { artistId }) => {
+ const current = store.getQuery(api.favorites.getUserFavorites, {})
+ if (!current) return
+ store.setQuery(
+ api.favorites.getUserFavorites,
+ {},
+ {
+ ...current,
+ favoriteArtists: current.favoriteArtists.filter(
+ (id) => id !== artistId
+ ),
+ }
+ )
+ }
+ )
+ const favoriteSongsMutation = useOptimisticMutation(
+ api.favorites.favoriteSongs,
+ (store, { songIds }) => {
+ const current = store.getQuery(api.favorites.getUserFavorites, {})
+ if (!current) return
+ store.setQuery(
+ api.favorites.getUserFavorites,
+ {},
+ {
+ ...current,
+ favoriteSongs: [...new Set([...current.favoriteSongs, ...songIds])],
+ }
+ )
+ }
+ )
const songIds = useMemo(
() => new Set(favorites?.favoriteSongs.map(String) ?? []),
@@ -143,11 +170,13 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
() => new Set(favorites?.favoriteArtists.map(String) ?? []),
[favorites?.favoriteArtists]
)
+ const idsRef = useRef({ songIds, albumIds, artistIds })
+ idsRef.current = { songIds, albumIds, artistIds }
const toggleSongFavorite = useCallback(
async (songId: Id<"songs">) => {
try {
- if (songIds.has(songId)) {
+ if (idsRef.current.songIds.has(songId)) {
await unfavoriteSong({ songId })
showSuccess("Removed from favorites")
} else {
@@ -160,13 +189,13 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
)
}
},
- [songIds, favoriteSong, unfavoriteSong]
+ [favoriteSong, unfavoriteSong]
)
const toggleAlbumFavorite = useCallback(
async (albumId: Id<"albums">) => {
try {
- if (albumIds.has(albumId)) {
+ if (idsRef.current.albumIds.has(albumId)) {
await unfavoriteAlbum({ albumId })
showSuccess("Removed from favorites")
} else {
@@ -179,13 +208,13 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
)
}
},
- [albumIds, favoriteAlbum, unfavoriteAlbum]
+ [favoriteAlbum, unfavoriteAlbum]
)
const toggleArtistFavorite = useCallback(
async (artistId: Id<"artists">) => {
try {
- if (artistIds.has(artistId)) {
+ if (idsRef.current.artistIds.has(artistId)) {
await unfavoriteArtist({ artistId })
showSuccess("Removed from favorites")
} else {
@@ -198,7 +227,7 @@ export function FavoritesProvider({ children }: { children: ReactNode }) {
)
}
},
- [artistIds, favoriteArtist, unfavoriteArtist]
+ [favoriteArtist, unfavoriteArtist]
)
const favoriteSongs = useCallback(
diff --git a/apps/mobile/lib/list.ts b/apps/mobile/lib/list.ts
new file mode 100644
index 0000000..457b118
--- /dev/null
+++ b/apps/mobile/lib/list.ts
@@ -0,0 +1,9 @@
+/**
+ * `FlatList` windowing for long media lists: enough rows to fill the first
+ * screen, and a smaller render window than the default 21 screens.
+ */
+export const longListProps = {
+ initialNumToRender: 14,
+ maxToRenderPerBatch: 10,
+ windowSize: 11,
+} as const
diff --git a/apps/mobile/lib/song-cache.ts b/apps/mobile/lib/song-cache.ts
index 4efc05e..36203e8 100644
--- a/apps/mobile/lib/song-cache.ts
+++ b/apps/mobile/lib/song-cache.ts
@@ -2,6 +2,7 @@ import { useConvex } from "convex/react"
import { useEffect, useMemo, useSyncExternalStore } from "react"
import type { Id } from "@otunes/convex/_generated/dataModel"
+import type { BrowseSong } from "@otunes/convex/types"
import {
getCachedSong,
getSongsVersion,
@@ -43,7 +44,24 @@ export function useSongs(songIds: readonly Id<"songs">[]) {
return songs
}
-export function useSong(songId: Id<"songs"> | null) {
- const songIds = useMemo(() => (songId ? [songId] : []), [songId])
- return useSongs(songIds)[0] ?? null
+/**
+ * Like `useSongs` for one song, but only re-renders when that song changes
+ * once it is cached.
+ */
+export function useSong(songId: Id<"songs"> | null): BrowseSong | null {
+ const convex = useConvex()
+ // While the song is missing the snapshot is the cache version, so every
+ // cache change re-renders and retries the fetch below.
+ const snapshot = useSyncExternalStore(subscribeSongs, () =>
+ songId ? (getCachedSong(songId) ?? getSongsVersion()) : null
+ )
+ const song = typeof snapshot === "object" ? snapshot : null
+
+ useEffect(() => {
+ if (songId && !song && isPersistentCacheLoaded()) {
+ requestSongs(convex, [songId])
+ }
+ }, [convex, songId, song, snapshot])
+
+ return song
}
diff --git a/apps/mobile/lib/urls.ts b/apps/mobile/lib/urls.ts
index bb2186e..62ae507 100644
--- a/apps/mobile/lib/urls.ts
+++ b/apps/mobile/lib/urls.ts
@@ -7,6 +7,9 @@ export const coverImageSizes = [64, 128, 192, 256, 384, 512, 768, 1024] as const
export type CoverImageSize = (typeof coverImageSizes)[number]
export function withCoverImageSize(uri: string, size: CoverImageSize) {
+ if (!uri.includes("?") && !uri.includes("#")) {
+ return `${uri}?size=${size}`
+ }
const url = new URL(uri)
url.searchParams.set("size", String(size))
return url.toString()