perf(mobile): optimize long list rendering (#28)
This commit was merged in pull request #28.
This commit is contained in:
1 parent
1ec2d28501
commit
e8f5b13cfd
18 files changed
+1200
-726
No files matched your search
@@ -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
|
||||
|
||||
@@ -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() {
|
||||
}}
|
||||
/>
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={album.tracks}
|
||||
keyExtractor={(track) => track.id}
|
||||
style={{ flex: 1, backgroundColor }}
|
||||
@@ -184,57 +189,86 @@ export default function AlbumScreen() {
|
||||
</View>
|
||||
}
|
||||
renderItem={({ item: track, index }) => (
|
||||
<MediaContextMenu
|
||||
<AlbumTrackRow
|
||||
track={track}
|
||||
album={album}
|
||||
index={index}
|
||||
favorited={isSongFavorite(track.id)}
|
||||
navigation={{
|
||||
artist: { id: album.artist.id },
|
||||
album: { id: album.id },
|
||||
}}
|
||||
share={{
|
||||
type: "song",
|
||||
albumId: album.id,
|
||||
songId: track.id,
|
||||
}}
|
||||
onAction={(action) =>
|
||||
void handleAlbumTrackAction(track, album, action)
|
||||
}
|
||||
>
|
||||
<Pressable
|
||||
style={[styles.trackRow, { borderBottomColor: colors.border }]}
|
||||
onPress={() => void playFromSong(track.id, songIds)}
|
||||
>
|
||||
<Text
|
||||
style={[styles.trackNumber, { color: colors.mutedForeground }]}
|
||||
>
|
||||
{track.track || index + 1}
|
||||
</Text>
|
||||
<View style={styles.trackMeta}>
|
||||
<Text
|
||||
style={[styles.trackTitle, { color: colors.foreground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{track.title}
|
||||
</Text>
|
||||
{track.artists ? (
|
||||
<Text
|
||||
style={{ color: colors.mutedForeground }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{track.artists.join(", ")}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
{formatDuration(track.durationSeconds)}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</MediaContextMenu>
|
||||
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<void>
|
||||
onAction: (
|
||||
track: BrowseAlbumTrack,
|
||||
album: BrowseAlbumDetail,
|
||||
action: MediaAction
|
||||
) => Promise<void>
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
|
||||
return (
|
||||
<MediaContextMenu
|
||||
favorited={favorited}
|
||||
navigation={{
|
||||
artist: { id: album.artist.id },
|
||||
album: { id: album.id },
|
||||
}}
|
||||
share={{
|
||||
type: "song",
|
||||
albumId: album.id,
|
||||
songId: track.id,
|
||||
}}
|
||||
onAction={(action) => void onAction(track, album, action)}
|
||||
>
|
||||
<Pressable
|
||||
style={[styles.trackRow, { borderBottomColor: colors.border }]}
|
||||
onPress={() => void onPlay(track.id, songIds)}
|
||||
>
|
||||
<Text style={[styles.trackNumber, { color: colors.mutedForeground }]}>
|
||||
{track.track || index + 1}
|
||||
</Text>
|
||||
<View style={styles.trackMeta}>
|
||||
<Text
|
||||
style={[styles.trackTitle, { color: colors.foreground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{track.title}
|
||||
</Text>
|
||||
{track.artists ? (
|
||||
<Text style={{ color: colors.mutedForeground }} numberOfLines={1}>
|
||||
{track.artists.join(", ")}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
{formatDuration(track.durationSeconds)}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</MediaContextMenu>
|
||||
)
|
||||
})
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
hero: {
|
||||
|
||||
@@ -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<BrowseArtist>) => (
|
||||
<ArtistRow
|
||||
artist={artist}
|
||||
serverUrl={serverUrl}
|
||||
favorited={isArtistFavorite(artist.id)}
|
||||
onOpen={handleOpenArtist}
|
||||
onAction={handleArtistAction}
|
||||
/>
|
||||
),
|
||||
[handleArtistAction, handleOpenArtist, isArtistFavorite, serverUrl]
|
||||
)
|
||||
|
||||
const handleChangeText = useCallback(
|
||||
(event: { nativeEvent: { text: string } }) => {
|
||||
onQueryChange(event.nativeEvent.text)
|
||||
@@ -76,46 +104,70 @@ export default function ArtistsScreen() {
|
||||
{searchBar}
|
||||
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={artists}
|
||||
keyExtractor={(artist) => 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 }) => (
|
||||
<MediaContextMenu
|
||||
favorited={isArtistFavorite(artist.id)}
|
||||
share={{ type: "artist", artistId: artist.id }}
|
||||
onAction={(action) => void handleArtistAction(artist, action)}
|
||||
>
|
||||
<Pressable
|
||||
style={[styles.row, { borderBottomColor: colors.border }]}
|
||||
onPress={() => push(`/artist/${artist.id}`)}
|
||||
>
|
||||
<CoverImage
|
||||
uri={artistCoverUrl(config.serverUrl, artist.id)}
|
||||
hasCover={artist.photo != null}
|
||||
style={styles.avatar}
|
||||
/>
|
||||
<Text
|
||||
style={[styles.name, { color: colors.foreground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{artist.name}
|
||||
</Text>
|
||||
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
|
||||
</Pressable>
|
||||
</MediaContextMenu>
|
||||
)}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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<void>
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
|
||||
return (
|
||||
<MediaContextMenu
|
||||
favorited={favorited}
|
||||
share={{ type: "artist", artistId: artist.id }}
|
||||
onAction={(action) => void onAction(artist, action)}
|
||||
>
|
||||
<Pressable
|
||||
style={[styles.row, { borderBottomColor: colors.border }]}
|
||||
onPress={() => onOpen(artist.id)}
|
||||
>
|
||||
<CoverImage
|
||||
uri={artistCoverUrl(serverUrl, artist.id)}
|
||||
hasCover={artist.photo != null}
|
||||
style={styles.avatar}
|
||||
/>
|
||||
<Text
|
||||
style={[styles.name, { color: colors.foreground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{artist.name}
|
||||
</Text>
|
||||
<Ionicons name="chevron-forward" size={16} color={colors.mutedForeground} />
|
||||
</Pressable>
|
||||
</MediaContextMenu>
|
||||
)
|
||||
})
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
listContent: { paddingBottom: contentBottomInset },
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
@@ -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<BrowseSong>) => (
|
||||
<SongListRow
|
||||
song={item}
|
||||
favorited={isSongFavorite(item.id)}
|
||||
onPlay={handlePlaySong}
|
||||
onAction={handleSongMenuAction}
|
||||
/>
|
||||
),
|
||||
[handlePlaySong, handleSongMenuAction, isSongFavorite]
|
||||
)
|
||||
|
||||
const handleChangeText = useCallback(
|
||||
(event: { nativeEvent: { text: string } }) => {
|
||||
onQueryChange(event.nativeEvent.text)
|
||||
@@ -74,49 +97,25 @@ export default function SongsScreen() {
|
||||
{searchBar}
|
||||
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={songs}
|
||||
keyExtractor={(item) => 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 }) => (
|
||||
<SongRow
|
||||
song={item}
|
||||
onPress={() =>
|
||||
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 },
|
||||
})
|
||||
@@ -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 (
|
||||
<PlaylistContent
|
||||
playlist={playlist}
|
||||
songs={songs}
|
||||
allSongIds={allSongIds}
|
||||
coverUri={coverUri}
|
||||
backgroundColor={backgroundColor}
|
||||
onEndReached={() => {
|
||||
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 = (
|
||||
<SongRow
|
||||
return {
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
headerRight: () => (
|
||||
<MediaActionMenu
|
||||
selectedCount={songIds.length}
|
||||
playlistLabel={PLAYLIST_LABEL}
|
||||
share={{
|
||||
type: "playlist",
|
||||
playlistId: playlistId ?? "favorites",
|
||||
}}
|
||||
includeActions={canEdit ? OWNER_MENU_ACTIONS : undefined}
|
||||
onAction={handlePlaylistMenuAction}
|
||||
>
|
||||
<Pressable hitSlop={8}>
|
||||
<Ionicons
|
||||
name="ellipsis-horizontal"
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
),
|
||||
}
|
||||
}, [
|
||||
canEdit,
|
||||
colors.foreground,
|
||||
deletePlaylist,
|
||||
handlePlaylistDetailAction,
|
||||
playlistId,
|
||||
router,
|
||||
songIds,
|
||||
])
|
||||
|
||||
const renderItem = useCallback(
|
||||
({ item: song }: ListRenderItemInfo<BrowseSong>) => (
|
||||
<PlaylistSongRow
|
||||
song={song}
|
||||
onPress={() => 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 (
|
||||
<ContextMenu.Items>
|
||||
<SwiftUIButton
|
||||
label="Share"
|
||||
systemImage="square.and.arrow.up"
|
||||
onPress={() =>
|
||||
void shareMediaLink(serverUrl, {
|
||||
type: "song",
|
||||
albumId: song.album.id,
|
||||
songId: song.id,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<SwiftUIButton
|
||||
label="Add to Another Playlist"
|
||||
systemImage="text.badge.plus"
|
||||
onPress={() => void handleSongAction(song, "playlist")}
|
||||
/>
|
||||
<SwiftUIButton
|
||||
label="Play Next"
|
||||
systemImage="text.line.first.and.arrowtriangle.forward"
|
||||
onPress={() => void handleSongAction(song, "play-next")}
|
||||
/>
|
||||
<SwiftUIButton
|
||||
label="Play Last"
|
||||
systemImage="text.line.last.and.arrowtriangle.forward"
|
||||
onPress={() => void handleSongAction(song, "play-last")}
|
||||
/>
|
||||
<SwiftUIButton
|
||||
label="Shuffle"
|
||||
systemImage="shuffle"
|
||||
onPress={() => void handleSongAction(song, "shuffle")}
|
||||
/>
|
||||
<SwiftUIButton
|
||||
label="Go to Artist"
|
||||
systemImage="person"
|
||||
onPress={() => void handleSongAction(song, "go-artist")}
|
||||
/>
|
||||
<SwiftUIButton
|
||||
label="Go to Album"
|
||||
systemImage="opticaldisc"
|
||||
onPress={() => void handleSongAction(song, "go-album")}
|
||||
/>
|
||||
<SwiftUIButton
|
||||
label={isSongFavorite(song.id) ? "Unfavorite" : "Favorite"}
|
||||
systemImage={isSongFavorite(song.id) ? "star.fill" : "star"}
|
||||
onPress={() => void handleSongAction(song, "favorite")}
|
||||
/>
|
||||
</ContextMenu.Items>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
headerRight: () => (
|
||||
<MediaActionMenu
|
||||
selectedCount={songIds.length}
|
||||
playlistLabel="Add to Another Playlist"
|
||||
share={{
|
||||
type: "playlist",
|
||||
playlistId: playlist.id ?? "favorites",
|
||||
}}
|
||||
includeActions={
|
||||
playlist.isOwner && playlist.id
|
||||
? [
|
||||
"share",
|
||||
"playlist",
|
||||
"play-next",
|
||||
"play-last",
|
||||
"shuffle",
|
||||
"favorite",
|
||||
"delete-playlist",
|
||||
]
|
||||
: undefined
|
||||
}
|
||||
onAction={handlePlaylistMenuAction}
|
||||
>
|
||||
<Pressable hitSlop={8}>
|
||||
<Ionicons
|
||||
name="ellipsis-horizontal"
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
),
|
||||
}}
|
||||
<Stack.Screen options={screenOptions} />
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={songs}
|
||||
keyExtractor={songKey}
|
||||
renderItem={renderItem}
|
||||
style={{ flex: 1, backgroundColor }}
|
||||
contentContainerStyle={styles.listContent}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={onEndReached}
|
||||
onEndReachedThreshold={0.5}
|
||||
ListHeaderComponent={
|
||||
<PlaylistHero
|
||||
coverUri={coverUri}
|
||||
hasCover={playlist.cover != null}
|
||||
title={playlist.title}
|
||||
ownerName={playlist.owner.name}
|
||||
isSubscribed={isSubscribed}
|
||||
showSubscribe={!playlist.isOwner && playlistId !== null}
|
||||
onSubscribeToggle={handleSubscribeToggle}
|
||||
onPlay={handlePlay}
|
||||
onShuffle={handleShuffle}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{shouldUseNativeSwipeList ? (
|
||||
<Host style={[styles.iosSwipeListHost, { backgroundColor }]}>
|
||||
<List
|
||||
modifiers={[
|
||||
listStyle("plain"),
|
||||
listSectionSpacing(0),
|
||||
listRowSpacing(0),
|
||||
scrollContentBackground("hidden"),
|
||||
]}
|
||||
>
|
||||
<SwipeActions modifiers={nativeListRowModifiers}>
|
||||
<RNHostView matchContents>
|
||||
<PlaylistHero
|
||||
coverUri={coverUri}
|
||||
hasCover={playlist.cover != null}
|
||||
title={playlist.title}
|
||||
ownerName={playlist.owner.name}
|
||||
colors={colors}
|
||||
onPlay={() => playlist.id && void playPlaylist(playlist.id, allSongIds)}
|
||||
onShuffle={() =>
|
||||
playlist.id && void playPlaylistShuffled(playlist.id, allSongIds)
|
||||
}
|
||||
/>
|
||||
</RNHostView>
|
||||
</SwipeActions>
|
||||
{songs.map((song, index) => {
|
||||
const nearEnd = index >= songs.length - NATIVE_LOAD_MORE_THRESHOLD
|
||||
return (
|
||||
<SwipeActions
|
||||
key={song.id}
|
||||
modifiers={[
|
||||
...nativeSongRowModifiers,
|
||||
...(nearEnd ? [onAppear(maybeLoadMore)] : []),
|
||||
]}
|
||||
>
|
||||
<ContextMenu>
|
||||
<ContextMenu.Trigger>
|
||||
<RNHostView matchContents>
|
||||
<View style={styles.nativeSongRow}>
|
||||
{renderSongRow(song, false)}
|
||||
</View>
|
||||
</RNHostView>
|
||||
</ContextMenu.Trigger>
|
||||
{renderNativeSongContextMenu(song)}
|
||||
</ContextMenu>
|
||||
<SwipeActions.Actions edge="trailing">
|
||||
<SwiftUIButton
|
||||
label=""
|
||||
systemImage="minus.circle.fill"
|
||||
role="destructive"
|
||||
onPress={() => void handleRemoveSong(song.id)}
|
||||
/>
|
||||
</SwipeActions.Actions>
|
||||
</SwipeActions>
|
||||
)
|
||||
})}
|
||||
</List>
|
||||
</Host>
|
||||
) : (
|
||||
<FlatList
|
||||
data={songs}
|
||||
keyExtractor={(song) => song.id}
|
||||
style={{ flex: 1, backgroundColor }}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={maybeLoadMore}
|
||||
onEndReachedThreshold={0.5}
|
||||
ListHeaderComponent={
|
||||
<PlaylistHero
|
||||
coverUri={coverUri}
|
||||
hasCover={playlist.cover != null}
|
||||
title={playlist.title}
|
||||
ownerName={playlist.owner.name}
|
||||
colors={colors}
|
||||
isSubscribed={playlist.isSubscribed}
|
||||
showSubscribe={!playlist.isOwner && !!playlist.id}
|
||||
onSubscribeToggle={() => 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 <View>{row}</View>
|
||||
}
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
friction={2}
|
||||
rightThreshold={56}
|
||||
overshootRight={false}
|
||||
enableTrackpadTwoFingerGesture
|
||||
containerStyle={{ backgroundColor: colors.destructive }}
|
||||
childrenContainerStyle={{ backgroundColor }}
|
||||
renderRightActions={(_progress, _translation, swipeable) => (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Remove ${song.title} from playlist`}
|
||||
onPress={() => {
|
||||
swipeable.close()
|
||||
void handleRemoveSong(song.id)
|
||||
}}
|
||||
style={[
|
||||
styles.removeAction,
|
||||
{ backgroundColor: colors.destructive },
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name="trash"
|
||||
size={22}
|
||||
color={colors.primaryForeground}
|
||||
/>
|
||||
<Text
|
||||
style={[
|
||||
styles.removeActionText,
|
||||
{ color: colors.primaryForeground },
|
||||
]}
|
||||
>
|
||||
Remove
|
||||
</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
>
|
||||
{row}
|
||||
</ReanimatedSwipeable>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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 = (
|
||||
<SongListRow
|
||||
song={song}
|
||||
favorited={favorited}
|
||||
playlistLabel={PLAYLIST_LABEL}
|
||||
onPlay={onPlay}
|
||||
onAction={onAction}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!removable) {
|
||||
return row
|
||||
}
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
friction={2}
|
||||
rightThreshold={56}
|
||||
overshootRight={false}
|
||||
enableTrackpadTwoFingerGesture
|
||||
containerStyle={{ backgroundColor: colors.destructive }}
|
||||
childrenContainerStyle={{ backgroundColor }}
|
||||
renderRightActions={(_progress, _translation, swipeable) => (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Remove ${song.title} from playlist`}
|
||||
onPress={() => {
|
||||
swipeable.close()
|
||||
onRemove(song.id)
|
||||
}}
|
||||
style={[styles.removeAction, { backgroundColor: colors.destructive }]}
|
||||
>
|
||||
<Ionicons name="trash" size={22} color={colors.primaryForeground} />
|
||||
<Text
|
||||
style={[
|
||||
styles.removeActionText,
|
||||
{ color: colors.primaryForeground },
|
||||
]}
|
||||
>
|
||||
Remove
|
||||
</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
>
|
||||
{row}
|
||||
</ReanimatedSwipeable>
|
||||
)
|
||||
})
|
||||
|
||||
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<typeof useThemeColors>
|
||||
isSubscribed?: boolean
|
||||
showSubscribe?: boolean
|
||||
onSubscribeToggle?: () => void
|
||||
onPlay: () => void
|
||||
onShuffle: () => void
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
|
||||
return (
|
||||
<View style={styles.hero}>
|
||||
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
|
||||
@@ -546,10 +479,11 @@ function PlaylistHero({
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
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",
|
||||
|
||||
@@ -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<BrowseSong>) => (
|
||||
<SongListRow
|
||||
song={song}
|
||||
favorited={isSongFavorite(song.id)}
|
||||
playlistLabel="Add to Another Playlist"
|
||||
onPlay={handlePlaySong}
|
||||
onAction={handleSongMenuAction}
|
||||
/>
|
||||
),
|
||||
[handlePlaySong, handleSongMenuAction, isSongFavorite]
|
||||
)
|
||||
|
||||
if (
|
||||
favorites === undefined ||
|
||||
(status === "LoadingFirstPage" && !isCached) ||
|
||||
!config
|
||||
) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen options={SCREEN_OPTIONS} />
|
||||
<CollectionDetailSkeleton />
|
||||
</>
|
||||
)
|
||||
@@ -47,12 +102,7 @@ export default function FavoritesScreen() {
|
||||
if (favorites === null) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen options={SCREEN_OPTIONS} />
|
||||
<View style={[styles.empty, { backgroundColor: colors.background }]}>
|
||||
<Text style={{ color: colors.mutedForeground }}>
|
||||
Sign in to view your favorites.
|
||||
@@ -62,92 +112,95 @@ export default function FavoritesScreen() {
|
||||
)
|
||||
}
|
||||
|
||||
const songIds = favorites.songs.map((song: BrowseSong) => song.id)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen options={SCREEN_OPTIONS} />
|
||||
<FlatList
|
||||
data={favorites.songs}
|
||||
keyExtractor={(song) => 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={
|
||||
<View style={styles.hero}>
|
||||
<View
|
||||
style={[
|
||||
styles.cover,
|
||||
{
|
||||
backgroundColor: colors.coverPlaceholder,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Ionicons name="star" size={120} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
{favorites.title}
|
||||
</Text>
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playInOrder(songIds)}
|
||||
style={styles.playButton}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playShuffled(songIds)}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
}
|
||||
renderItem={({ item: song }: { item: BrowseSong }) => (
|
||||
<SongRow
|
||||
song={song}
|
||||
onPress={() => 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),
|
||||
}}
|
||||
<FavoritesHero
|
||||
title={favorites.title}
|
||||
onPlay={handlePlay}
|
||||
onShuffle={handleShuffle}
|
||||
/>
|
||||
)}
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<View style={styles.hero}>
|
||||
<View
|
||||
style={[
|
||||
styles.cover,
|
||||
styles.coverPlaceholder,
|
||||
{ backgroundColor: colors.coverPlaceholder },
|
||||
]}
|
||||
>
|
||||
<Ionicons name="star" size={120} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>{title}</Text>
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={onPlay}
|
||||
style={styles.playButton}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={onShuffle}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
})
|
||||
|
||||
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",
|
||||
|
||||
@@ -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<QueueItem, "key"> & {
|
||||
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<QueueItem[]>(
|
||||
() => queueSongIds.map((songId, queueIndex) => ({ songId, queueIndex })),
|
||||
[queueSongIds]
|
||||
)
|
||||
const items = useMemo<QueueItem[]>(() => {
|
||||
const occurrences = new Map<string, number>()
|
||||
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}
|
||||
</View>
|
||||
}
|
||||
{...longListProps}
|
||||
data={items}
|
||||
keyExtractor={(item) => `${item.songId}-${item.queueIndex}`}
|
||||
keyExtractor={queueItemKey}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
initialNumToRender={15}
|
||||
renderItem={({ item }) => (
|
||||
<QueueRow
|
||||
{...item}
|
||||
songId={item.songId}
|
||||
queueIndex={item.queueIndex}
|
||||
isLast={item.queueIndex === queueSongIds.length - 1}
|
||||
isCurrent={item.queueIndex === 0}
|
||||
onSkipTo={skipToQueueIndex}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import { Image, type ImageContentFit, type ImageStyle } from "expo-image"
|
||||
import { memo } from "react"
|
||||
import { memo, useMemo } from "react"
|
||||
import {
|
||||
PixelRatio,
|
||||
StyleProp,
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
} from "@/lib/urls"
|
||||
|
||||
const DEFAULT_SOURCE_SIZE: CoverImageSize = 1024
|
||||
const PIXEL_RATIO = PixelRatio.get()
|
||||
|
||||
function sourceSize(style: ImageStyle): CoverImageSize {
|
||||
const layoutSizes = [
|
||||
@@ -28,7 +29,7 @@ function sourceSize(style: ImageStyle): CoverImageSize {
|
||||
|
||||
if (layoutSizes.length === 0) return DEFAULT_SOURCE_SIZE
|
||||
|
||||
const requiredPixels = Math.max(...layoutSizes) * PixelRatio.get()
|
||||
const requiredPixels = Math.max(...layoutSizes) * PIXEL_RATIO
|
||||
return (
|
||||
coverImageSizes.find((size) => 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 (
|
||||
<View style={[style, placeholderStyle]}>
|
||||
<View
|
||||
style={[
|
||||
style,
|
||||
placeholderBaseStyle,
|
||||
{ backgroundColor: colors.coverPlaceholder },
|
||||
]}
|
||||
>
|
||||
{placeholderVariant === "icon" ? (
|
||||
<Ionicons
|
||||
name="musical-note"
|
||||
@@ -88,11 +99,9 @@ export const CoverImage = memo(function CoverImage({
|
||||
)
|
||||
}
|
||||
|
||||
const sourceUri = withCoverImageSize(uri, sourceSize(flatStyle))
|
||||
|
||||
return (
|
||||
<Image
|
||||
source={{ uri: sourceUri }}
|
||||
source={source}
|
||||
style={[style, { backgroundColor: colors.coverPlaceholder }]}
|
||||
contentFit={contentFit}
|
||||
transition={150}
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import { memo, useCallback, type ReactElement } from "react"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
import {
|
||||
FlatList,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type ListRenderItemInfo,
|
||||
} from "react-native"
|
||||
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import { MediaContextMenu } from "@/components/media-context-menu"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import { longListProps } from "@/lib/list"
|
||||
import type {
|
||||
BrowseAlbum,
|
||||
BrowseArtist,
|
||||
@@ -23,6 +31,8 @@ import {
|
||||
|
||||
export type MediaItem = BrowseAlbum | BrowseArtist | PlaylistSummary
|
||||
|
||||
const GRID_INITIAL_ROWS = 5
|
||||
|
||||
export const AlbumCard = memo(function AlbumCard({
|
||||
album,
|
||||
width = carouselCardWidth,
|
||||
@@ -206,12 +216,24 @@ export function MediaGridList({
|
||||
}) {
|
||||
const cardWidth = useTwoColumnCardWidth()
|
||||
const colors = useThemeColors()
|
||||
const renderItem = useCallback(
|
||||
({ item }: ListRenderItemInfo<MediaItem>) => (
|
||||
<View style={{ width: cardWidth }}>
|
||||
<CarouselCard item={item} width={cardWidth} />
|
||||
</View>
|
||||
),
|
||||
[cardWidth]
|
||||
)
|
||||
|
||||
return (
|
||||
<FlatList
|
||||
data={content}
|
||||
keyExtractor={(item) => 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 }) => (
|
||||
<View style={{ width: cardWidth }}>
|
||||
<CarouselCard item={item} width={cardWidth} />
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function mediaItemKey(item: MediaItem) {
|
||||
return item.id
|
||||
}
|
||||
|
||||
function renderCarouselItem({ item }: ListRenderItemInfo<MediaItem>) {
|
||||
return (
|
||||
<View>
|
||||
<CarouselCard item={item} width={carouselCardWidth} />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function ContentCarouselBody({
|
||||
title,
|
||||
href,
|
||||
@@ -271,15 +300,11 @@ function ContentCarouselBody({
|
||||
</Pressable>
|
||||
<FlatList
|
||||
data={content}
|
||||
keyExtractor={(item) => item.id}
|
||||
keyExtractor={mediaItemKey}
|
||||
renderItem={renderCarouselItem}
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
contentContainerStyle={styles.carouselContent}
|
||||
renderItem={({ item }) => (
|
||||
<View>
|
||||
<CarouselCard item={item} width={carouselCardWidth} />
|
||||
</View>
|
||||
)}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { MenuView, type MenuAction } from "@expo/ui/community/menu"
|
||||
import type { ReactNode } from "react"
|
||||
import type { StyleProp, ViewStyle } from "react-native"
|
||||
import { requireNativeView } from "expo"
|
||||
import type { ComponentType, ReactNode } from "react"
|
||||
import {
|
||||
Platform,
|
||||
type StyleProp,
|
||||
type ViewProps,
|
||||
type ViewStyle,
|
||||
} from "react-native"
|
||||
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import type { MediaShareContext } from "@/lib/media-links"
|
||||
@@ -190,7 +196,69 @@ function MediaMenuBase({
|
||||
)
|
||||
}
|
||||
|
||||
// Long-press menus are mounted once per list row. `MenuView` hosts a SwiftUI
|
||||
// view tree per row, which makes opening long lists stall the main thread, so
|
||||
// on iOS rows use the UIKit context menu view that ships with expo-router.
|
||||
const NativeContextMenuView =
|
||||
Platform.OS === "ios"
|
||||
? requireNativeView<
|
||||
ViewProps & { disableForceFlatten?: boolean; children: ReactNode }
|
||||
>("ExpoRouterNativeLinkPreview", "NativeLinkPreviewView")
|
||||
: null
|
||||
|
||||
const NativeContextMenuAction: ComponentType<{
|
||||
identifier: string
|
||||
title: string
|
||||
icon?: string
|
||||
onSelected: () => void
|
||||
}> | null =
|
||||
Platform.OS === "ios"
|
||||
? requireNativeView(
|
||||
"ExpoRouterNativeLinkPreview",
|
||||
"LinkPreviewNativeActionView"
|
||||
)
|
||||
: null
|
||||
|
||||
function NativeMediaContextMenu({
|
||||
children,
|
||||
onAction,
|
||||
share,
|
||||
...actionConfig
|
||||
}: MediaMenuWrapperProps) {
|
||||
const { config } = useServerConfig()
|
||||
|
||||
if (!NativeContextMenuView || !NativeContextMenuAction) {
|
||||
return children
|
||||
}
|
||||
|
||||
const handleAction = (action: MediaAction) => {
|
||||
if (action === "share" && share && config) {
|
||||
void shareMediaLink(config.serverUrl, share)
|
||||
return
|
||||
}
|
||||
onAction(action)
|
||||
}
|
||||
|
||||
return (
|
||||
<NativeContextMenuView style={{ display: "contents" }} disableForceFlatten>
|
||||
{children}
|
||||
{buildMediaMenuActions({ ...actionConfig, share }).map((action) => (
|
||||
<NativeContextMenuAction
|
||||
key={action.id}
|
||||
identifier={action.id ?? action.title}
|
||||
title={action.title}
|
||||
icon={typeof action.image === "string" ? action.image : undefined}
|
||||
onSelected={() => handleAction(action.id as MediaAction)}
|
||||
/>
|
||||
))}
|
||||
</NativeContextMenuView>
|
||||
)
|
||||
}
|
||||
|
||||
export function MediaContextMenu(props: MediaMenuWrapperProps) {
|
||||
if (Platform.OS === "ios") {
|
||||
return <NativeMediaContextMenu {...props} />
|
||||
}
|
||||
return <MediaMenuBase {...props} shouldOpenOnLongPress />
|
||||
}
|
||||
|
||||
|
||||
@@ -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}
|
||||
</MediaContextMenu>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* 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 (
|
||||
<SongRow
|
||||
song={song}
|
||||
onPress={handlePress}
|
||||
contextMenu={{
|
||||
favorited,
|
||||
playlistLabel,
|
||||
navigation: {
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
},
|
||||
share: {
|
||||
type: "song",
|
||||
albumId: song.album.id,
|
||||
songId: song.id,
|
||||
},
|
||||
onAction: (action) => onAction(song, action),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
})
|
||||
|
||||
export const tabContentBottomInset = spacing.lg
|
||||
export const contentBottomInset = miniPlayerHeight + spacing.lg
|
||||
|
||||
@@ -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<BrowseSong>) => (
|
||||
<SongListRow
|
||||
song={song}
|
||||
favorited={isSongFavorite(song.id)}
|
||||
onPlay={handlePlaySong}
|
||||
onAction={handleSongMenuAction}
|
||||
/>
|
||||
),
|
||||
[handlePlaySong, handleSongMenuAction, isSongFavorite]
|
||||
)
|
||||
|
||||
if (isSearching) {
|
||||
return <SongListSkeleton />
|
||||
@@ -89,25 +116,7 @@ function SearchResultsBody({ searchQuery }: { searchQuery: string }) {
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
renderItem={({ item: song }: { item: BrowseSong }) => (
|
||||
<SongRow
|
||||
song={song}
|
||||
onPress={() => 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 ? (
|
||||
<View style={styles.section}>
|
||||
|
||||
+132
-103
@@ -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 extends FunctionReference<"mutation">>(
|
||||
mutation: Mutation,
|
||||
optimisticUpdate: OptimisticUpdate<FunctionArgs<Mutation>>
|
||||
): ReactMutation<Mutation> {
|
||||
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(
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
const { createRequire } = require("module");
|
||||
|
||||
const expoRequire = createRequire(require.resolve("expo/package.json"));
|
||||
const { withPodfile } = expoRequire("@expo/config-plugins");
|
||||
|
||||
const MARKER = "Xcode 26 rejects Pod deployment targets below iOS 15.0";
|
||||
|
||||
const DEPLOYMENT_TARGET_FIX = `
|
||||
# ${MARKER}. Resource bundles keep the podspec
|
||||
# version (AsyncStorage 13.4, RNSVG 12.4); React Native only bumps native targets.
|
||||
installer.pods_project.targets.each do |target|
|
||||
target.build_configurations.each do |build_config|
|
||||
deployment_target = build_config.build_settings['IPHONEOS_DEPLOYMENT_TARGET']
|
||||
next if deployment_target.nil?
|
||||
next unless deployment_target.to_s.match?(/\\A\\d+(?:\\.\\d+)?\\z/)
|
||||
if deployment_target.to_f < 15.1
|
||||
build_config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.1'
|
||||
end
|
||||
end
|
||||
end
|
||||
`;
|
||||
|
||||
function insertPodDeploymentTargetFix(contents) {
|
||||
if (contents.includes(MARKER)) {
|
||||
return contents;
|
||||
}
|
||||
|
||||
const call = "react_native_post_install(";
|
||||
const start = contents.indexOf(call);
|
||||
if (start === -1) {
|
||||
throw new Error(
|
||||
"Podfile is missing react_native_post_install, so the iOS deployment target fix could not be applied.",
|
||||
);
|
||||
}
|
||||
|
||||
let depth = 0;
|
||||
for (let index = start + call.length - 1; index < contents.length; index += 1) {
|
||||
const character = contents[index];
|
||||
if (character === "(") {
|
||||
depth += 1;
|
||||
} else if (character === ")") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
const end = index + 1;
|
||||
return `${contents.slice(0, end)}\n${DEPLOYMENT_TARGET_FIX}${contents.slice(end)}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
"Podfile has an unbalanced react_native_post_install call, so the iOS deployment target fix could not be applied.",
|
||||
);
|
||||
}
|
||||
|
||||
/** Raise Pod target deployment targets to the Xcode 26 minimum. */
|
||||
function withIosPodDeploymentTarget(config) {
|
||||
return withPodfile(config, (mod) => {
|
||||
mod.modResults.contents = insertPodDeploymentTargetFix(mod.modResults.contents);
|
||||
return mod;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = withIosPodDeploymentTarget;
|
||||
module.exports.insertPodDeploymentTargetFix = insertPodDeploymentTargetFix;
|
||||
@@ -0,0 +1,125 @@
|
||||
const { createRequire } = require("module");
|
||||
|
||||
const expoRequire = createRequire(require.resolve("expo/package.json"));
|
||||
const { withAppDelegate, withInfoPlist } = expoRequire("@expo/config-plugins");
|
||||
|
||||
const WINDOW_BLOCK = `#if os(iOS) || os(tvOS)
|
||||
window = UIWindow(frame: UIScreen.main.bounds)
|
||||
factory.startReactNative(
|
||||
withModuleName: "main",
|
||||
in: window,
|
||||
launchOptions: launchOptions)
|
||||
#endif`;
|
||||
|
||||
const SCENE_DELEGATE = `
|
||||
@objc(SceneDelegate)
|
||||
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
|
||||
var window: UIWindow?
|
||||
|
||||
func scene(
|
||||
_ scene: UIScene,
|
||||
willConnectTo session: UISceneSession,
|
||||
options connectionOptions: UIScene.ConnectionOptions
|
||||
) {
|
||||
guard let windowScene = scene as? UIWindowScene,
|
||||
let appDelegate = UIApplication.shared.delegate as? AppDelegate
|
||||
else {
|
||||
return
|
||||
}
|
||||
|
||||
if let existingWindow = window {
|
||||
existingWindow.windowScene = windowScene
|
||||
return
|
||||
}
|
||||
|
||||
let window = UIWindow(windowScene: windowScene)
|
||||
self.window = window
|
||||
appDelegate.window = window
|
||||
appDelegate.reactNativeFactory?.startReactNative(
|
||||
withModuleName: "main",
|
||||
in: window,
|
||||
launchOptions: appDelegate.launchOptions
|
||||
)
|
||||
|
||||
deliver(connectionOptions, to: appDelegate)
|
||||
}
|
||||
|
||||
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
|
||||
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
|
||||
for context in URLContexts {
|
||||
_ = appDelegate.application(UIApplication.shared, open: context.url, options: [:])
|
||||
}
|
||||
}
|
||||
|
||||
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
|
||||
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
|
||||
_ = appDelegate.application(
|
||||
UIApplication.shared,
|
||||
continue: userActivity,
|
||||
restorationHandler: { _ in }
|
||||
)
|
||||
}
|
||||
|
||||
private func deliver(
|
||||
_ connectionOptions: UIScene.ConnectionOptions,
|
||||
to appDelegate: AppDelegate
|
||||
) {
|
||||
for context in connectionOptions.urlContexts {
|
||||
_ = appDelegate.application(UIApplication.shared, open: context.url, options: [:])
|
||||
}
|
||||
for userActivity in connectionOptions.userActivities {
|
||||
_ = appDelegate.application(
|
||||
UIApplication.shared,
|
||||
continue: userActivity,
|
||||
restorationHandler: { _ in }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
function enableSceneLifecycle(contents) {
|
||||
if (contents.includes("@objc(SceneDelegate)")) {
|
||||
return contents;
|
||||
}
|
||||
if (!contents.includes(WINDOW_BLOCK)) {
|
||||
throw new Error(
|
||||
"AppDelegate.swift is missing the UIWindow startup block, so the UIScene lifecycle could not be applied.",
|
||||
);
|
||||
}
|
||||
|
||||
let next = contents.replace(
|
||||
"var window: UIWindow?\n",
|
||||
"var window: UIWindow?\n var launchOptions: [UIApplication.LaunchOptionsKey: Any]?\n",
|
||||
);
|
||||
next = next.replace(
|
||||
WINDOW_BLOCK,
|
||||
" // The window is created in SceneDelegate. This SDK refuses to launch without a UIScene.\n self.launchOptions = launchOptions",
|
||||
);
|
||||
return `${next.trimEnd()}\n${SCENE_DELEGATE}`;
|
||||
}
|
||||
|
||||
/** Adopt the UIScene lifecycle required by the current iOS SDK. */
|
||||
function withIosSceneLifecycle(config) {
|
||||
config = withInfoPlist(config, (mod) => {
|
||||
mod.modResults.UIApplicationSceneManifest = {
|
||||
UIApplicationSupportsMultipleScenes: false,
|
||||
UISceneConfigurations: {
|
||||
UIWindowSceneSessionRoleApplication: [
|
||||
{
|
||||
UISceneConfigurationName: "Default Configuration",
|
||||
UISceneDelegateClassName: "SceneDelegate",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
return mod;
|
||||
});
|
||||
|
||||
return withAppDelegate(config, (mod) => {
|
||||
mod.modResults.contents = enableSceneLifecycle(mod.modResults.contents);
|
||||
return mod;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = withIosSceneLifecycle;
|
||||
Reference in new issue
Block a user