Compare commits
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
|
||||
|
||||
@@ -16,17 +16,18 @@ export default function HomeLayout() {
|
||||
screenOptions={({ route }) => ({
|
||||
...baseOptions,
|
||||
title: tabStackScreenTitles[route.name] ?? "Home",
|
||||
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
|
||||
headerRight:
|
||||
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
|
||||
unstable_headerRightItems:
|
||||
route.name === "settings"
|
||||
? undefined
|
||||
: () => [
|
||||
route.name === "index"
|
||||
? () => [
|
||||
{
|
||||
type: "custom",
|
||||
element: <ProfileHeaderButton />,
|
||||
hidesSharedBackground: true,
|
||||
},
|
||||
],
|
||||
]
|
||||
: undefined,
|
||||
})}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
import { Stack, useLocalSearchParams } from "expo-router"
|
||||
import { useEffect } from "react"
|
||||
import { Stack, useIsFocused, useLocalSearchParams } from "expo-router"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
import { memo, useCallback, useEffect, useMemo } from "react"
|
||||
import { FlatList, Pressable, StyleSheet, Text, View } from "react-native"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
|
||||
import {
|
||||
CollectionDivider,
|
||||
collectionInset,
|
||||
DiscHeader,
|
||||
} from "@/components/collection-list"
|
||||
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"
|
||||
@@ -16,13 +23,15 @@ import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlaybackActions } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
|
||||
import { useCoverPalette } from "@/hooks/use-cover-palette"
|
||||
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 type { CoverPalette } from "@/lib/cover-palette"
|
||||
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"
|
||||
@@ -44,12 +53,16 @@ export default function AlbumScreen() {
|
||||
handleAlbumTrackAction,
|
||||
isAlbumFavorite: isAlbumFav,
|
||||
} = useMediaMenuActions()
|
||||
const isFocused = useIsFocused()
|
||||
const coverUri =
|
||||
config && album ? albumCoverUrl(config.serverUrl, album.id) : ""
|
||||
const backgroundColor = useCoverBackgroundColor(
|
||||
config && typeof id === "string" ? albumCoverUrl(config.serverUrl, id) : ""
|
||||
const { palette, settled } = useCoverPalette(
|
||||
coverUri,
|
||||
album?.cover != null,
|
||||
colors.background
|
||||
album ? album.cover != null : album === null ? false : undefined
|
||||
)
|
||||
const songIds = useMemo(
|
||||
() => album?.tracks.map((track) => track.id as Id<"songs">) ?? [],
|
||||
[album]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -58,7 +71,37 @@ export default function AlbumScreen() {
|
||||
}
|
||||
}, [album])
|
||||
|
||||
if (album === undefined || !config) {
|
||||
const listItems = useMemo(() => albumListItems(album?.tracks ?? []), [album])
|
||||
|
||||
const renderItem = useCallback(
|
||||
({ item }: { item: AlbumListItem }) => {
|
||||
if (item.type === "disc") {
|
||||
return <DiscHeader label={item.label} color={palette.foreground} />
|
||||
}
|
||||
return album ? (
|
||||
<AlbumTrackRow
|
||||
track={item.track}
|
||||
number={item.number}
|
||||
album={album}
|
||||
songIds={songIds}
|
||||
palette={palette}
|
||||
favorited={isSongFavorite(item.track.id)}
|
||||
onPlay={playFromSong}
|
||||
onAction={handleAlbumTrackAction}
|
||||
/>
|
||||
) : null
|
||||
},
|
||||
[
|
||||
album,
|
||||
handleAlbumTrackAction,
|
||||
isSongFavorite,
|
||||
palette,
|
||||
playFromSong,
|
||||
songIds,
|
||||
]
|
||||
)
|
||||
|
||||
if (album === undefined || !config || !settled) {
|
||||
return (
|
||||
<>
|
||||
<Stack.Screen
|
||||
@@ -90,17 +133,19 @@ export default function AlbumScreen() {
|
||||
)
|
||||
}
|
||||
|
||||
const songIds = album.tracks.map(
|
||||
(track: BrowseAlbumTrack) => track.id as Id<"songs">
|
||||
)
|
||||
const metadata = formatMetadata(album.genre, album.year)
|
||||
const favorited = isAlbumFavorite(album.id)
|
||||
|
||||
return (
|
||||
<>
|
||||
{isFocused ? (
|
||||
<StatusBar style={palette.isDark ? "light" : "dark"} />
|
||||
) : null}
|
||||
<Stack.Screen
|
||||
options={{
|
||||
title: "",
|
||||
headerLargeTitle: false,
|
||||
headerTintColor: palette.foreground,
|
||||
headerRight: () => (
|
||||
<MediaActionMenu
|
||||
selectedCount={album.tracks.length}
|
||||
@@ -118,7 +163,7 @@ export default function AlbumScreen() {
|
||||
<Ionicons
|
||||
name="ellipsis-horizontal"
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
color={palette.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
@@ -126,115 +171,204 @@ export default function AlbumScreen() {
|
||||
}}
|
||||
/>
|
||||
<FlatList
|
||||
data={album.tracks}
|
||||
keyExtractor={(track) => track.id}
|
||||
style={{ flex: 1, backgroundColor }}
|
||||
{...longListProps}
|
||||
data={listItems}
|
||||
keyExtractor={albumListItemKey}
|
||||
style={{ flex: 1, backgroundColor: palette.background }}
|
||||
contentContainerStyle={{ paddingBottom: contentBottomInset }}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
indicatorStyle={palette.isDark ? "white" : "black"}
|
||||
ListHeaderComponent={
|
||||
<View style={styles.hero}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={album.cover != null}
|
||||
style={styles.cover}
|
||||
/>
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>
|
||||
{album.title}
|
||||
</Text>
|
||||
<Pressable onPress={() => push(`/artist/${album.artist.id}`)}>
|
||||
<Text style={[styles.artist, { color: colors.mutedForeground }]}>
|
||||
{album.artist.name}
|
||||
</Text>
|
||||
</Pressable>
|
||||
{metadata ? (
|
||||
<Text style={{ color: colors.mutedForeground }}>{metadata}</Text>
|
||||
) : null}
|
||||
<View style={styles.actions}>
|
||||
<Pressable
|
||||
onPress={() => void toggleAlbumFavorite(album.id)}
|
||||
hitSlop={8}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Ionicons
|
||||
name={isAlbumFavorite(album.id) ? "star" : "star-outline"}
|
||||
size={24}
|
||||
color={
|
||||
isAlbumFavorite(album.id)
|
||||
? colors.primary
|
||||
: colors.foreground
|
||||
}
|
||||
/>
|
||||
</Pressable>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playAlbum(album.id, songIds)}
|
||||
style={styles.playButton}
|
||||
<View>
|
||||
<View style={styles.hero}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={album.cover != null}
|
||||
style={styles.cover}
|
||||
/>
|
||||
<Text style={[styles.title, { color: palette.foreground }]}>
|
||||
{album.title}
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playAlbumShuffled(album.id, songIds)}
|
||||
style={[styles.iconAction, { backgroundColor: colors.muted }]}
|
||||
onPress={() => push(`/artist/${album.artist.id}`)}
|
||||
style={styles.artistPressable}
|
||||
>
|
||||
<Ionicons name="shuffle" size={24} color={colors.foreground} />
|
||||
<Text style={[styles.artist, { color: palette.accentText }]}>
|
||||
{album.artist.name}
|
||||
</Text>
|
||||
</Pressable>
|
||||
{metadata ? (
|
||||
<Text style={{ color: palette.secondaryForeground }}>
|
||||
{metadata}
|
||||
</Text>
|
||||
) : null}
|
||||
<View style={styles.actions}>
|
||||
<Pressable
|
||||
onPress={() => void toggleAlbumFavorite(album.id)}
|
||||
hitSlop={8}
|
||||
style={[
|
||||
styles.iconAction,
|
||||
{ backgroundColor: palette.surface },
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name={favorited ? "star" : "star-outline"}
|
||||
size={24}
|
||||
color={favorited ? palette.accent : palette.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={() => void playAlbum(album.id, songIds)}
|
||||
style={styles.playButton}
|
||||
tint={{
|
||||
background: palette.accent,
|
||||
foreground: palette.accentForeground,
|
||||
}}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={() => void playAlbumShuffled(album.id, songIds)}
|
||||
style={[
|
||||
styles.iconAction,
|
||||
{ backgroundColor: palette.surface },
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name="shuffle"
|
||||
size={24}
|
||||
color={palette.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
<CollectionDivider color={palette.divider} />
|
||||
</View>
|
||||
}
|
||||
renderItem={({ item: track, index }) => (
|
||||
<MediaContextMenu
|
||||
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>
|
||||
)}
|
||||
renderItem={renderItem}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
type AlbumListItem =
|
||||
| { type: "disc"; key: string; label: string }
|
||||
| { type: "track"; track: BrowseAlbumTrack; number: number }
|
||||
|
||||
/**
|
||||
* Tracks arrive sorted by disc then track number. Disc headers are only
|
||||
* inserted when the album spans more than one disc.
|
||||
*/
|
||||
function albumListItems(tracks: BrowseAlbumTrack[]): AlbumListItem[] {
|
||||
const multiDisc = new Set(tracks.map((track) => track.diskNumber)).size > 1
|
||||
const items: AlbumListItem[] = []
|
||||
let currentDisc: number | null | undefined
|
||||
let positionInDisc = 0
|
||||
|
||||
for (const track of tracks) {
|
||||
if (track.diskNumber !== currentDisc) {
|
||||
currentDisc = track.diskNumber
|
||||
positionInDisc = 0
|
||||
if (multiDisc) {
|
||||
items.push({
|
||||
type: "disc",
|
||||
key: `disc-${currentDisc ?? "unknown"}`,
|
||||
label: currentDisc == null ? "Other" : `Disc ${currentDisc}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
positionInDisc += 1
|
||||
items.push({
|
||||
type: "track",
|
||||
track,
|
||||
number: track.track || positionInDisc,
|
||||
})
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
function albumListItemKey(item: AlbumListItem) {
|
||||
return item.type === "disc" ? item.key : item.track.id
|
||||
}
|
||||
|
||||
const AlbumTrackRow = memo(function AlbumTrackRow({
|
||||
track,
|
||||
number,
|
||||
album,
|
||||
songIds,
|
||||
palette,
|
||||
favorited,
|
||||
onPlay,
|
||||
onAction,
|
||||
}: {
|
||||
track: BrowseAlbumTrack
|
||||
number: number
|
||||
album: BrowseAlbumDetail
|
||||
songIds: Id<"songs">[]
|
||||
palette: CoverPalette
|
||||
favorited: boolean
|
||||
onPlay: (songId: Id<"songs">, songIds: Id<"songs">[]) => Promise<void>
|
||||
onAction: (
|
||||
track: BrowseAlbumTrack,
|
||||
album: BrowseAlbumDetail,
|
||||
action: MediaAction
|
||||
) => Promise<void>
|
||||
}) {
|
||||
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}
|
||||
onPress={() => void onPlay(track.id as Id<"songs">, songIds)}
|
||||
>
|
||||
<Text
|
||||
style={[styles.trackNumber, { color: palette.secondaryForeground }]}
|
||||
>
|
||||
{number}
|
||||
</Text>
|
||||
<View
|
||||
style={[styles.trackContent, { borderBottomColor: palette.divider }]}
|
||||
>
|
||||
<View style={styles.trackMeta}>
|
||||
<Text
|
||||
style={[styles.trackTitle, { color: palette.foreground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{track.title}
|
||||
</Text>
|
||||
{track.artists ? (
|
||||
<Text
|
||||
style={{ color: palette.secondaryForeground }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{track.artists.join(", ")}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text style={{ color: palette.secondaryForeground }}>
|
||||
{formatDuration(track.durationSeconds)}
|
||||
</Text>
|
||||
</View>
|
||||
</Pressable>
|
||||
</MediaContextMenu>
|
||||
)
|
||||
})
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
empty: { flex: 1, alignItems: "center", justifyContent: "center" },
|
||||
hero: {
|
||||
@@ -248,7 +382,8 @@ const styles = StyleSheet.create({
|
||||
borderRadius: radius.lg,
|
||||
},
|
||||
title: { fontSize: 24, fontWeight: "800", textAlign: "center" },
|
||||
artist: { fontSize: 16, fontWeight: "600" },
|
||||
artistPressable: { alignSelf: "stretch" },
|
||||
artist: { fontSize: 16, fontWeight: "600", textAlign: "center" },
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
@@ -267,13 +402,22 @@ const styles = StyleSheet.create({
|
||||
trackRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.sm,
|
||||
paddingLeft: collectionInset,
|
||||
},
|
||||
trackNumber: { width: 24, fontSize: 16, textAlign: "center" },
|
||||
trackContent: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
alignSelf: "stretch",
|
||||
gap: spacing.md,
|
||||
minHeight: 60,
|
||||
paddingHorizontal: spacing.lg,
|
||||
minHeight: 52,
|
||||
paddingVertical: 12,
|
||||
marginRight: collectionInset,
|
||||
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
trackNumber: { width: 24, textAlign: "center" },
|
||||
trackMeta: { flex: 1, minWidth: 0 },
|
||||
trackTitle: { fontSize: 16, fontWeight: "500" },
|
||||
})
|
||||
@@ -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,25 +1,12 @@
|
||||
import { useMutation } from "convex/react"
|
||||
import { useEffect } from "react"
|
||||
import { memo, useCallback, useEffect, useMemo } 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 { Stack, useLocalSearchParams, useRouter } from "expo-router"
|
||||
Stack,
|
||||
useIsFocused,
|
||||
useLocalSearchParams,
|
||||
useRouter,
|
||||
} from "expo-router"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
import {
|
||||
FlatList,
|
||||
Platform,
|
||||
@@ -27,11 +14,18 @@ import {
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type ListRenderItemInfo,
|
||||
} from "react-native"
|
||||
import ReanimatedSwipeable from "react-native-gesture-handler/ReanimatedSwipeable"
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
|
||||
import { CollectionDivider } from "@/components/collection-list"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import {
|
||||
SwipeToRemoveRow,
|
||||
useSwipeRowGroup,
|
||||
type SwipeRowGroup,
|
||||
} from "@/components/ios-swipe-to-remove-row"
|
||||
|
||||
import {
|
||||
MediaActionMenu,
|
||||
@@ -39,7 +33,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"
|
||||
@@ -47,23 +41,32 @@ import {
|
||||
useCachedPaginatedQuery,
|
||||
useCachedQuery,
|
||||
} from "@/hooks/use-cached-query"
|
||||
import { useCoverBackgroundColor } from "@/hooks/use-cover-background-color"
|
||||
import { useCoverPalette } from "@/hooks/use-cover-palette"
|
||||
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 type { CoverPalette } from "@/lib/cover-palette"
|
||||
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,22 +93,13 @@ 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")
|
||||
config && playlistId
|
||||
? playlistCoverUrl(config.serverUrl, playlist?.id ?? playlistId)
|
||||
: ""
|
||||
const backgroundColor = useCoverBackgroundColor(
|
||||
const { palette, settled } = useCoverPalette(
|
||||
coverUri,
|
||||
playlist?.cover != null,
|
||||
colors.background
|
||||
playlist ? playlist.cover != null : playlist === null ? false : undefined
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -115,7 +109,8 @@ export default function PlaylistScreen() {
|
||||
if (
|
||||
playlist === undefined ||
|
||||
(status === "LoadingFirstPage" && !isCached) ||
|
||||
!config
|
||||
!config ||
|
||||
!settled
|
||||
) {
|
||||
return (
|
||||
<>
|
||||
@@ -148,21 +143,99 @@ 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}
|
||||
palette={palette}
|
||||
onEndReached={() => {
|
||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function maybeLoadMore() {
|
||||
if (status === "CanLoadMore") loadMore(PAGE_SIZE)
|
||||
}
|
||||
function PlaylistContent({
|
||||
playlist,
|
||||
songs,
|
||||
allSongIds,
|
||||
coverUri,
|
||||
palette,
|
||||
onEndReached,
|
||||
}: {
|
||||
playlist: BrowsePlaylistDetail
|
||||
songs: BrowseSong[]
|
||||
allSongIds: Id<"songs">[] | undefined
|
||||
coverUri: string
|
||||
palette: CoverPalette
|
||||
onEndReached: () => void
|
||||
}) {
|
||||
const router = useRouter()
|
||||
const isFocused = useIsFocused()
|
||||
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 swipeGroup = useSwipeRowGroup()
|
||||
|
||||
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 false
|
||||
try {
|
||||
await removeSongs({ playlistId, songIds: [songId] })
|
||||
showSuccess("Removed from playlist")
|
||||
return true
|
||||
} catch (error) {
|
||||
showError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Failed to remove from playlist"
|
||||
)
|
||||
return false
|
||||
}
|
||||
},
|
||||
[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 +243,222 @@ 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,
|
||||
headerTintColor: palette.foreground,
|
||||
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={palette.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
),
|
||||
}
|
||||
}, [
|
||||
canEdit,
|
||||
deletePlaylist,
|
||||
handlePlaylistDetailAction,
|
||||
palette.foreground,
|
||||
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}
|
||||
palette={palette}
|
||||
swipeGroup={swipeGroup}
|
||||
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
|
||||
),
|
||||
[
|
||||
canEdit,
|
||||
handlePlaySong,
|
||||
handleRemoveSong,
|
||||
handleSongMenuAction,
|
||||
isSongFavorite,
|
||||
palette,
|
||||
swipeGroup,
|
||||
]
|
||||
)
|
||||
|
||||
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>
|
||||
),
|
||||
}}
|
||||
{isFocused ? (
|
||||
<StatusBar style={palette.isDark ? "light" : "dark"} />
|
||||
) : null}
|
||||
<Stack.Screen options={screenOptions} />
|
||||
<FlatList
|
||||
{...longListProps}
|
||||
data={songs}
|
||||
keyExtractor={songKey}
|
||||
renderItem={renderItem}
|
||||
style={{ flex: 1, backgroundColor: palette.background }}
|
||||
indicatorStyle={palette.isDark ? "white" : "black"}
|
||||
contentContainerStyle={styles.listContent}
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
onEndReached={onEndReached}
|
||||
onEndReachedThreshold={0.5}
|
||||
onScrollBeginDrag={swipeGroup.closeOpenRow}
|
||||
ListHeaderComponent={
|
||||
<PlaylistHero
|
||||
coverUri={coverUri}
|
||||
hasCover={playlist.cover != null}
|
||||
title={playlist.title}
|
||||
ownerName={playlist.owner.name}
|
||||
palette={palette}
|
||||
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,
|
||||
palette,
|
||||
swipeGroup,
|
||||
onPlay,
|
||||
onAction,
|
||||
onRemove,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
favorited: boolean
|
||||
removable: boolean
|
||||
palette: CoverPalette
|
||||
swipeGroup: SwipeRowGroup
|
||||
onPlay: (song: BrowseSong) => void
|
||||
onAction: (song: BrowseSong, action: MediaAction) => void
|
||||
onRemove: (songId: Id<"songs">) => Promise<boolean>
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
const handleRemove = useCallback(() => onRemove(song.id), [onRemove, song.id])
|
||||
const row = (
|
||||
<SongListRow
|
||||
song={song}
|
||||
favorited={favorited}
|
||||
playlistLabel={PLAYLIST_LABEL}
|
||||
palette={palette}
|
||||
inset
|
||||
onPlay={onPlay}
|
||||
onAction={onAction}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!removable) {
|
||||
return row
|
||||
}
|
||||
|
||||
if (Platform.OS === "ios") {
|
||||
return (
|
||||
<SwipeToRemoveRow
|
||||
group={swipeGroup}
|
||||
backgroundColor={palette.background}
|
||||
actionAccessibilityLabel={`Remove ${song.title} from playlist`}
|
||||
onRemove={handleRemove}
|
||||
>
|
||||
{row}
|
||||
</SwipeToRemoveRow>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ReanimatedSwipeable
|
||||
friction={2}
|
||||
rightThreshold={56}
|
||||
overshootRight={false}
|
||||
enableTrackpadTwoFingerGesture
|
||||
containerStyle={{ backgroundColor: colors.destructive }}
|
||||
childrenContainerStyle={{ backgroundColor: palette.background }}
|
||||
renderRightActions={(_progress, _translation, swipeable) => (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Remove ${song.title} from playlist`}
|
||||
onPress={() => {
|
||||
swipeable.close()
|
||||
void handleRemove()
|
||||
}}
|
||||
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,
|
||||
palette,
|
||||
isSubscribed,
|
||||
showSubscribe = false,
|
||||
onSubscribeToggle,
|
||||
@@ -492,7 +469,7 @@ function PlaylistHero({
|
||||
hasCover: boolean
|
||||
title: string
|
||||
ownerName: string
|
||||
colors: ReturnType<typeof useThemeColors>
|
||||
palette: CoverPalette
|
||||
isSubscribed?: boolean
|
||||
showSubscribe?: boolean
|
||||
onSubscribeToggle?: () => void
|
||||
@@ -500,56 +477,68 @@ function PlaylistHero({
|
||||
onShuffle: () => void
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.hero}>
|
||||
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
|
||||
<Text style={[styles.title, { color: colors.foreground }]}>{title}</Text>
|
||||
<Text style={{ color: colors.mutedForeground }}>{ownerName}</Text>
|
||||
<View style={styles.actions}>
|
||||
{showSubscribe ? (
|
||||
<View>
|
||||
<View style={styles.hero}>
|
||||
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.cover} />
|
||||
<Text style={[styles.title, { color: palette.foreground }]}>
|
||||
{title}
|
||||
</Text>
|
||||
<Text style={{ color: palette.secondaryForeground }}>{ownerName}</Text>
|
||||
<View style={styles.actions}>
|
||||
{showSubscribe ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={isSubscribed ? "Subscribed" : "Subscribe"}
|
||||
accessibilityState={{ selected: isSubscribed }}
|
||||
hitSlop={8}
|
||||
onPress={onSubscribeToggle}
|
||||
style={[
|
||||
styles.iconAction,
|
||||
{
|
||||
backgroundColor: isSubscribed
|
||||
? palette.surface
|
||||
: palette.accent,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name={isSubscribed ? "checkmark" : "add"}
|
||||
size={24}
|
||||
color={
|
||||
isSubscribed ? palette.foreground : palette.accentForeground
|
||||
}
|
||||
/>
|
||||
</Pressable>
|
||||
) : null}
|
||||
<Button
|
||||
title="Play"
|
||||
icon="play"
|
||||
onPress={onPlay}
|
||||
style={styles.playButton}
|
||||
tint={{
|
||||
background: palette.accent,
|
||||
foreground: palette.accentForeground,
|
||||
}}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={isSubscribed ? "Subscribed" : "Subscribe"}
|
||||
accessibilityState={{ selected: isSubscribed }}
|
||||
accessibilityLabel="Shuffle"
|
||||
hitSlop={8}
|
||||
onPress={onSubscribeToggle}
|
||||
style={[
|
||||
styles.iconAction,
|
||||
{
|
||||
backgroundColor: isSubscribed ? colors.muted : colors.primary,
|
||||
},
|
||||
]}
|
||||
onPress={onShuffle}
|
||||
style={[styles.iconAction, { backgroundColor: palette.surface }]}
|
||||
>
|
||||
<Ionicons
|
||||
name={isSubscribed ? "checkmark" : "add"}
|
||||
size={24}
|
||||
color={
|
||||
isSubscribed ? colors.foreground : colors.primaryForeground
|
||||
}
|
||||
/>
|
||||
<Ionicons name="shuffle" size={24} color={palette.foreground} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
<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>
|
||||
<CollectionDivider color={palette.divider} />
|
||||
</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 +561,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,101 @@
|
||||
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 { CollectionDivider } from "@/components/collection-list"
|
||||
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"
|
||||
inset
|
||||
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 +104,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 +114,100 @@ 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>
|
||||
<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>
|
||||
<CollectionDivider />
|
||||
</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}
|
||||
|
||||
@@ -476,77 +476,82 @@ function UsersSection({
|
||||
title="People"
|
||||
subtitle="Manage who can access this server."
|
||||
>
|
||||
{users.map((user, index) => (
|
||||
<View key={user._id}>
|
||||
{index > 0 ? (
|
||||
<View
|
||||
style={[styles.divider, { backgroundColor: colors.border }]}
|
||||
/>
|
||||
) : null}
|
||||
<View style={styles.userRow}>
|
||||
<ProfileAvatar user={user} size={44} />
|
||||
<View style={styles.userCopy}>
|
||||
<View style={styles.userNameRow}>
|
||||
<View style={styles.userList}>
|
||||
{users.map((user, index) => (
|
||||
<View
|
||||
key={user._id}
|
||||
style={[
|
||||
styles.userBlock,
|
||||
index > 0
|
||||
? [styles.userBlockSpaced, { borderTopColor: colors.border }]
|
||||
: null,
|
||||
]}
|
||||
>
|
||||
<View style={styles.userRow}>
|
||||
<ProfileAvatar user={user} size={44} />
|
||||
<View style={styles.userCopy}>
|
||||
<View style={styles.userNameRow}>
|
||||
<Text
|
||||
style={[styles.userName, { color: colors.foreground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{user.name}
|
||||
</Text>
|
||||
{user.isAdmin ? (
|
||||
<View
|
||||
style={[styles.badge, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.badgeText,
|
||||
{ color: colors.mutedForeground },
|
||||
]}
|
||||
>
|
||||
Admin
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
<Text
|
||||
style={[styles.userName, { color: colors.foreground }]}
|
||||
style={{ color: colors.mutedForeground }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{user.name}
|
||||
{user.email}
|
||||
</Text>
|
||||
{user.isAdmin ? (
|
||||
<View
|
||||
style={[styles.badge, { backgroundColor: colors.muted }]}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.badgeText,
|
||||
{ color: colors.mutedForeground },
|
||||
]}
|
||||
>
|
||||
Admin
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
<Text
|
||||
style={{ color: colors.mutedForeground }}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{user.email}
|
||||
</Text>
|
||||
</View>
|
||||
{user._id !== currentUserId ? (
|
||||
<View style={styles.userActions}>
|
||||
<Button
|
||||
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
|
||||
variant="secondary"
|
||||
onPress={() =>
|
||||
void setAdmin({
|
||||
userId: user._id,
|
||||
isAdmin: !user.isAdmin,
|
||||
}).then(
|
||||
() => showSuccess("Updated permissions"),
|
||||
(error: Error) => showError(error.message)
|
||||
)
|
||||
}
|
||||
style={styles.userActionButton}
|
||||
/>
|
||||
<Button
|
||||
title="Delete"
|
||||
variant="destructive"
|
||||
onPress={() =>
|
||||
void deleteUserMutation({ userId: user._id }).then(
|
||||
() => showSuccess("User deleted"),
|
||||
(error: Error) => showError(error.message)
|
||||
)
|
||||
}
|
||||
style={styles.userActionButton}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{user._id !== currentUserId ? (
|
||||
<View style={styles.userActions}>
|
||||
<Button
|
||||
title={user.isAdmin ? "Remove Admin" : "Make Admin"}
|
||||
variant="secondary"
|
||||
onPress={() =>
|
||||
void setAdmin({
|
||||
userId: user._id,
|
||||
isAdmin: !user.isAdmin,
|
||||
}).then(
|
||||
() => showSuccess("Updated permissions"),
|
||||
(error: Error) => showError(error.message)
|
||||
)
|
||||
}
|
||||
style={styles.userActionButton}
|
||||
/>
|
||||
<Button
|
||||
title="Delete"
|
||||
variant="destructive"
|
||||
onPress={() =>
|
||||
void deleteUserMutation({ userId: user._id }).then(
|
||||
() => showSuccess("User deleted"),
|
||||
(error: Error) => showError(error.message)
|
||||
)
|
||||
}
|
||||
style={styles.userActionButton}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
))}
|
||||
))}
|
||||
</View>
|
||||
</SettingsCard>
|
||||
</>
|
||||
)
|
||||
@@ -833,6 +838,16 @@ const styles = StyleSheet.create({
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
},
|
||||
userList: {
|
||||
gap: spacing.lg,
|
||||
},
|
||||
userBlock: {
|
||||
gap: spacing.md,
|
||||
},
|
||||
userBlockSpaced: {
|
||||
paddingTop: spacing.lg,
|
||||
borderTopWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
userRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
@@ -855,7 +870,6 @@ const styles = StyleSheet.create({
|
||||
userActions: {
|
||||
flexDirection: "row",
|
||||
gap: spacing.sm,
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
userActionButton: {
|
||||
flex: 1,
|
||||
|
||||
@@ -16,17 +16,18 @@ export default function LibraryLayout() {
|
||||
screenOptions={({ route }) => ({
|
||||
...baseOptions,
|
||||
title: tabStackScreenTitles[route.name] ?? "Library",
|
||||
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
|
||||
headerRight:
|
||||
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
|
||||
unstable_headerRightItems:
|
||||
route.name === "settings"
|
||||
? undefined
|
||||
: () => [
|
||||
route.name === "index"
|
||||
? () => [
|
||||
{
|
||||
type: "custom",
|
||||
element: <ProfileHeaderButton />,
|
||||
hidesSharedBackground: true,
|
||||
},
|
||||
],
|
||||
]
|
||||
: undefined,
|
||||
})}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -16,17 +16,18 @@ export default function SearchLayout() {
|
||||
screenOptions={({ route }) => ({
|
||||
...baseOptions,
|
||||
title: tabStackScreenTitles[route.name] ?? "Search",
|
||||
headerRight: route.name === "settings" ? undefined : () => <ProfileHeaderButton />,
|
||||
headerRight:
|
||||
route.name === "index" ? () => <ProfileHeaderButton /> : undefined,
|
||||
unstable_headerRightItems:
|
||||
route.name === "settings"
|
||||
? undefined
|
||||
: () => [
|
||||
route.name === "index"
|
||||
? () => [
|
||||
{
|
||||
type: "custom",
|
||||
element: <ProfileHeaderButton />,
|
||||
hidesSharedBackground: true,
|
||||
},
|
||||
],
|
||||
]
|
||||
: undefined,
|
||||
})}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -87,7 +87,10 @@ export default function AppLayout() {
|
||||
name="player"
|
||||
options={{
|
||||
headerShown: false,
|
||||
presentation: Platform.OS === "ios" ? "modal" : "fullScreenModal",
|
||||
presentation:
|
||||
Platform.OS === "ios"
|
||||
? "transparentModal"
|
||||
: "fullScreenModal",
|
||||
animation: "slide_from_bottom",
|
||||
gestureEnabled: true,
|
||||
gestureDirection: "vertical",
|
||||
|
||||
+606
-234
@@ -1,39 +1,77 @@
|
||||
import { Ionicons } from "@expo/vector-icons"
|
||||
import Slider from "@react-native-community/slider"
|
||||
import { BlurView } from "expo-blur"
|
||||
import { useRouter } from "expo-router"
|
||||
import * as Haptics from "expo-haptics"
|
||||
import { useEffect, useRef } from "react"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler"
|
||||
import {
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native"
|
||||
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context"
|
||||
import { StatusBar } from "expo-status-bar"
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeOut,
|
||||
interpolate,
|
||||
LayoutAnimationConfig,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withSpring,
|
||||
withTiming,
|
||||
} from "react-native-reanimated"
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context"
|
||||
import { scheduleOnRN } from "react-native-worklets"
|
||||
|
||||
import { MediaActionMenu, type MediaAction } from "@/components/media-actions-sheet"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { api } from "@otunes/convex/_generated/api"
|
||||
import { playbackFormat } from "@otunes/convex/playback-stream"
|
||||
|
||||
import { AudioFormatBadge } from "@/components/audio-format-badge"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import { MarqueeText } from "@/components/marquee-text"
|
||||
import {
|
||||
MediaActionMenu,
|
||||
type MediaAction,
|
||||
} from "@/components/media-actions-sheet"
|
||||
import {
|
||||
NowPlayingQueue,
|
||||
QUEUE_HORIZONTAL_INSET,
|
||||
} from "@/components/now-playing-queue"
|
||||
import { PlayerSlider } from "@/components/player-slider"
|
||||
import { PlayerSymbol } from "@/components/player-symbol"
|
||||
import { useFavorites } from "@/contexts/favorites"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import { useCachedQuery } from "@/hooks/use-cached-query"
|
||||
import { useCoverPalette } from "@/hooks/use-cover-palette"
|
||||
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
|
||||
import { formatDuration, formatRemainingDuration } from "@/lib/format"
|
||||
import { useAppNavigation } from "@/lib/app-navigation"
|
||||
import {
|
||||
nowPlayingColors,
|
||||
type NowPlayingColors,
|
||||
} from "@/lib/now-playing-colors"
|
||||
import { albumCoverUrl } from "@/lib/urls"
|
||||
import { appleMusic, radius, spacing, usePlayerTheme } from "@/lib/theme"
|
||||
import { radius, spacing } from "@/lib/theme"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
|
||||
const HORIZONTAL_INSET = QUEUE_HORIZONTAL_INSET
|
||||
const META_HEIGHT = 64
|
||||
const PAUSED_ARTWORK_SCALE = 0.77
|
||||
const ARTWORK_SPRING = { duration: 550, dampingRatio: 0.72 }
|
||||
const BACKGROUND_FADE = { duration: 450 }
|
||||
const MODE_FADE_IN = FadeIn.duration(220)
|
||||
const MODE_FADE_OUT = FadeOut.duration(140)
|
||||
const DISMISS_DISTANCE = 140
|
||||
const DISMISS_VELOCITY = 900
|
||||
const DISMISS_CORNER_RADIUS = 48
|
||||
|
||||
export default function PlayerScreen() {
|
||||
const router = useRouter()
|
||||
const hadSongRef = useRef(false)
|
||||
const { push } = useAppNavigation()
|
||||
const insets = useSafeAreaInsets()
|
||||
const player = usePlayerTheme()
|
||||
const { width: windowWidth, height: windowHeight } = useWindowDimensions()
|
||||
const { config } = useServerConfig()
|
||||
const { isSongFavorite, toggleSongFavorite } = useFavorites()
|
||||
const { handleSongAction } = useMediaMenuActions()
|
||||
const {
|
||||
currentSong,
|
||||
isPlaying,
|
||||
@@ -46,11 +84,93 @@ export default function PlayerScreen() {
|
||||
setIsPlaying,
|
||||
setVolume,
|
||||
seekTo,
|
||||
toggleShuffle,
|
||||
cycleRepeat,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
} = usePlayback()
|
||||
const [showQueue, setShowQueue] = useState(false)
|
||||
const [stageHeight, setStageHeight] = useState(0)
|
||||
const [scrubTime, setScrubTime] = useState<number | null>(null)
|
||||
const user = useCachedQuery(api.auth.currentUser)
|
||||
const playbackInfo = useCachedQuery(
|
||||
api.library.getSongPlaybackInfo,
|
||||
currentSong ? { id: currentSong.id } : "skip"
|
||||
)
|
||||
const format =
|
||||
user && playbackInfo
|
||||
? playbackFormat(
|
||||
playbackInfo.files,
|
||||
user.playbackQuality,
|
||||
user.preferAtmos ?? false
|
||||
)
|
||||
: null
|
||||
|
||||
const coverUri =
|
||||
currentSong && config
|
||||
? albumCoverUrl(config.serverUrl, currentSong.album.id)
|
||||
: ""
|
||||
const { palette } = useCoverPalette(
|
||||
coverUri,
|
||||
currentSong ? currentSong.album.cover != null : undefined
|
||||
)
|
||||
const colors = nowPlayingColors(palette)
|
||||
|
||||
const background = useSharedValue(colors.background)
|
||||
useEffect(() => {
|
||||
background.value = withTiming(colors.background, BACKGROUND_FADE)
|
||||
}, [background, colors.background])
|
||||
const backgroundStyle = useAnimatedStyle(() => ({
|
||||
backgroundColor: background.value,
|
||||
}))
|
||||
|
||||
const artworkScale = useSharedValue(isPlaying ? 1 : PAUSED_ARTWORK_SCALE)
|
||||
useEffect(() => {
|
||||
artworkScale.value = withSpring(
|
||||
isPlaying ? 1 : PAUSED_ARTWORK_SCALE,
|
||||
ARTWORK_SPRING
|
||||
)
|
||||
}, [artworkScale, isPlaying])
|
||||
const artworkStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ scale: artworkScale.value }],
|
||||
shadowOpacity: interpolate(
|
||||
artworkScale.value,
|
||||
[PAUSED_ARTWORK_SCALE, 1],
|
||||
[0.18, 0.4]
|
||||
),
|
||||
}))
|
||||
|
||||
const dismissY = useSharedValue(0)
|
||||
const dismissStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ translateY: dismissY.value }],
|
||||
borderRadius: dismissY.value > 0 ? DISMISS_CORNER_RADIUS : 0,
|
||||
}))
|
||||
|
||||
// The player covers the status bar, so it can't use the native sheet's
|
||||
// swipe to dismiss.
|
||||
function dismissGesture() {
|
||||
return Gesture.Pan()
|
||||
.activeOffsetY(12)
|
||||
.failOffsetY(-12)
|
||||
.failOffsetX([-20, 20])
|
||||
.onUpdate((event) => {
|
||||
dismissY.value = Math.max(0, event.translationY)
|
||||
})
|
||||
.onEnd((event) => {
|
||||
if (
|
||||
event.translationY > DISMISS_DISTANCE ||
|
||||
event.velocityY > DISMISS_VELOCITY
|
||||
) {
|
||||
dismissY.value = withTiming(
|
||||
windowHeight,
|
||||
{ duration: 220 },
|
||||
(finished) => {
|
||||
if (finished) scheduleOnRN(router.back)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
dismissY.value = withSpring(0, { duration: 350, dampingRatio: 0.85 })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const hasQueue = queueSongIds.length > 0
|
||||
|
||||
@@ -70,313 +190,565 @@ export default function PlayerScreen() {
|
||||
}
|
||||
|
||||
const hasCover = currentSong.album.cover != null
|
||||
const coverUri = albumCoverUrl(config.serverUrl, currentSong.album.id)
|
||||
const favorited = isSongFavorite(currentSong.id)
|
||||
const bottomInset = Math.max(insets.bottom, spacing.md) + spacing.lg
|
||||
const { colors } = player
|
||||
|
||||
async function handleAction(action: MediaAction) {
|
||||
if (!currentSong) return
|
||||
await handleSongAction(currentSong, action)
|
||||
}
|
||||
const bottomInset = Math.max(insets.bottom, spacing.md)
|
||||
const artworkSize = Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
windowWidth - HORIZONTAL_INSET * 2,
|
||||
stageHeight > 0 ? stageHeight - META_HEIGHT - spacing.xl : Infinity
|
||||
)
|
||||
)
|
||||
const displayedTime = scrubTime ?? currentTime
|
||||
const timeColor =
|
||||
scrubTime === null ? colors.secondaryForeground : colors.foreground
|
||||
|
||||
function togglePlayback() {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)
|
||||
setIsPlaying(!isPlaying)
|
||||
}
|
||||
|
||||
function toggleQueue() {
|
||||
void Haptics.selectionAsync()
|
||||
setShowQueue((value) => !value)
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={[styles.root, { backgroundColor: colors.background }]}>
|
||||
<StatusBar style={player.statusBar} />
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={hasCover}
|
||||
style={[styles.backgroundImage, { opacity: player.backgroundImageOpacity }]}
|
||||
contentFit="cover"
|
||||
blurRadius={60}
|
||||
placeholderVariant="solid"
|
||||
/>
|
||||
{Platform.OS === "ios" ? (
|
||||
<>
|
||||
<BlurView intensity={90} tint={player.blurTint} style={StyleSheet.absoluteFill} />
|
||||
<View style={[styles.scrim, { backgroundColor: player.scrim }]} />
|
||||
</>
|
||||
) : (
|
||||
<View style={[StyleSheet.absoluteFill, { backgroundColor: player.androidScrim }]} />
|
||||
)}
|
||||
<Animated.View style={[styles.root, backgroundStyle, dismissStyle]}>
|
||||
<StatusBar style={colors.isDark ? "light" : "dark"} />
|
||||
|
||||
<SafeAreaView style={styles.safe} edges={["top"]}>
|
||||
<Pressable
|
||||
onPress={() => router.back()}
|
||||
hitSlop={12}
|
||||
style={styles.handleRow}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close player"
|
||||
>
|
||||
<View style={[styles.handle, { backgroundColor: player.handle }]} />
|
||||
</Pressable>
|
||||
<View style={[styles.safe, { paddingTop: insets.top }]}>
|
||||
<GestureDetector gesture={dismissGesture()}>
|
||||
<Pressable
|
||||
onPress={() => router.back()}
|
||||
hitSlop={12}
|
||||
style={styles.handleRow}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close player"
|
||||
>
|
||||
<View
|
||||
style={[styles.handle, { backgroundColor: colors.sliderTrack }]}
|
||||
/>
|
||||
</Pressable>
|
||||
</GestureDetector>
|
||||
|
||||
<View style={styles.upper}>
|
||||
<View style={styles.artworkWrap}>
|
||||
<CoverImage uri={coverUri} hasCover={hasCover} style={styles.artwork} />
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={[styles.controls, { paddingBottom: bottomInset }]}>
|
||||
<View style={styles.metaRow}>
|
||||
<View style={styles.metaText}>
|
||||
<Text style={[styles.songTitle, { color: colors.foreground }]} numberOfLines={2}>
|
||||
{currentSong.title}
|
||||
</Text>
|
||||
<Text style={[styles.artistName, { color: colors.mutedForeground }]} numberOfLines={1}>
|
||||
{currentSong.artist.name}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.metaActions}>
|
||||
<Pressable
|
||||
onPress={() => void toggleSongFavorite(currentSong.id)}
|
||||
hitSlop={10}
|
||||
style={[styles.circleButton, { backgroundColor: player.buttonSurface }]}
|
||||
>
|
||||
<Ionicons
|
||||
name={favorited ? "star" : "star-outline"}
|
||||
size={20}
|
||||
color={favorited ? appleMusic.pink : colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<MediaActionMenu
|
||||
favorited={favorited}
|
||||
navigation={{
|
||||
artist: { id: currentSong.artist.id },
|
||||
album: { id: currentSong.album.id },
|
||||
}}
|
||||
includeActions={[
|
||||
"play-next",
|
||||
"play-last",
|
||||
"shuffle",
|
||||
"favorite",
|
||||
"go-artist",
|
||||
"go-album",
|
||||
]}
|
||||
onAction={handleAction}
|
||||
>
|
||||
<Pressable
|
||||
hitSlop={10}
|
||||
style={[styles.circleButton, { backgroundColor: player.buttonSurface }]}
|
||||
<GestureDetector gesture={dismissGesture().enabled(!showQueue)}>
|
||||
<View
|
||||
style={styles.stage}
|
||||
onLayout={(event) =>
|
||||
setStageHeight(event.nativeEvent.layout.height)
|
||||
}
|
||||
>
|
||||
<LayoutAnimationConfig skipEntering>
|
||||
{showQueue ? (
|
||||
stageHeight > 0 ? (
|
||||
<Animated.View
|
||||
key="queue"
|
||||
entering={MODE_FADE_IN}
|
||||
exiting={MODE_FADE_OUT}
|
||||
style={styles.fill}
|
||||
>
|
||||
<NowPlayingQueue
|
||||
colors={colors}
|
||||
viewportHeight={stageHeight}
|
||||
currentHeader={
|
||||
<View style={styles.queueHeader}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={hasCover}
|
||||
style={styles.queueArtwork}
|
||||
/>
|
||||
<SongMeta
|
||||
song={currentSong}
|
||||
colors={colors}
|
||||
compact
|
||||
/>
|
||||
</View>
|
||||
}
|
||||
/>
|
||||
</Animated.View>
|
||||
) : null
|
||||
) : (
|
||||
<Animated.View
|
||||
key="artwork"
|
||||
entering={MODE_FADE_IN}
|
||||
exiting={MODE_FADE_OUT}
|
||||
style={[styles.fill, styles.artworkMode]}
|
||||
>
|
||||
<Ionicons name="ellipsis-horizontal" size={20} color={colors.foreground} />
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
</View>
|
||||
<View style={styles.artworkArea}>
|
||||
<Animated.View style={[styles.artworkShadow, artworkStyle]}>
|
||||
<CoverImage
|
||||
uri={coverUri}
|
||||
hasCover={hasCover}
|
||||
style={{
|
||||
width: artworkSize,
|
||||
height: artworkSize,
|
||||
borderRadius: radius.md,
|
||||
}}
|
||||
/>
|
||||
</Animated.View>
|
||||
</View>
|
||||
<View style={styles.meta}>
|
||||
<SongMeta song={currentSong} colors={colors} />
|
||||
</View>
|
||||
</Animated.View>
|
||||
)}
|
||||
</LayoutAnimationConfig>
|
||||
</View>
|
||||
</GestureDetector>
|
||||
|
||||
<View style={styles.progressSection}>
|
||||
<Slider
|
||||
style={styles.slider}
|
||||
minimumValue={0}
|
||||
maximumValue={duration > 0 ? duration : 1}
|
||||
value={Math.min(currentTime, duration || 0)}
|
||||
onSlidingComplete={(value) => void seekTo(value)}
|
||||
minimumTrackTintColor={colors.foreground}
|
||||
maximumTrackTintColor={player.trackInactive}
|
||||
thumbTintColor={colors.foreground}
|
||||
<GestureDetector gesture={dismissGesture()}>
|
||||
<View style={[styles.controls, { paddingBottom: bottomInset }]}>
|
||||
<PlayerSlider
|
||||
accessibilityLabel="Playback position"
|
||||
value={displayedTime}
|
||||
maximumValue={duration}
|
||||
fillColor={colors.sliderFill}
|
||||
activeFillColor={colors.foreground}
|
||||
trackColor={colors.sliderTrack}
|
||||
onValueChange={setScrubTime}
|
||||
onSlidingComplete={(value) => {
|
||||
void seekTo(value)
|
||||
setScrubTime(null)
|
||||
}}
|
||||
/>
|
||||
<View style={styles.timeRow}>
|
||||
<Text style={[styles.time, { color: colors.mutedForeground }]}>
|
||||
{formatDuration(currentTime)}
|
||||
<Text style={[styles.time, { color: timeColor }]}>
|
||||
{formatDuration(displayedTime)}
|
||||
</Text>
|
||||
<Text style={[styles.time, { color: colors.mutedForeground }]}>
|
||||
{formatRemainingDuration(currentTime, duration)}
|
||||
{format ? (
|
||||
<View style={styles.format} pointerEvents="none">
|
||||
<AudioFormatBadge
|
||||
format={format}
|
||||
color={colors.secondaryForeground}
|
||||
backgroundColor={colors.background}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<Text style={[styles.time, { color: timeColor }]}>
|
||||
{formatRemainingDuration(displayedTime, duration).replace(
|
||||
"-",
|
||||
"\u2212"
|
||||
)}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={styles.transport}>
|
||||
<Pressable onPress={() => void skipPrevious()} hitSlop={12}>
|
||||
<Ionicons name="play-back" size={36} color={colors.foreground} />
|
||||
</Pressable>
|
||||
<Pressable onPress={togglePlayback} style={styles.playButton} hitSlop={12}>
|
||||
<Ionicons
|
||||
name={isPlaying ? "pause" : "play"}
|
||||
size={52}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<Pressable onPress={() => void skipNext()} hitSlop={12}>
|
||||
<Ionicons name="play-forward" size={36} color={colors.foreground} />
|
||||
</Pressable>
|
||||
</View>
|
||||
<View style={styles.transport}>
|
||||
<TransportButton
|
||||
colors={colors}
|
||||
accessibilityLabel="Previous"
|
||||
onPress={() => void skipPrevious()}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="backward.fill"
|
||||
fallback="play-back"
|
||||
size={34}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</TransportButton>
|
||||
<TransportButton
|
||||
colors={colors}
|
||||
accessibilityLabel={isPlaying ? "Pause" : "Play"}
|
||||
onPress={togglePlayback}
|
||||
large
|
||||
>
|
||||
<PlayerSymbol
|
||||
name={isPlaying ? "pause.fill" : "play.fill"}
|
||||
fallback={isPlaying ? "pause" : "play"}
|
||||
size={44}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</TransportButton>
|
||||
<TransportButton
|
||||
colors={colors}
|
||||
accessibilityLabel="Next"
|
||||
onPress={() => void skipNext()}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="forward.fill"
|
||||
fallback="play-forward"
|
||||
size={34}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</TransportButton>
|
||||
</View>
|
||||
|
||||
<View style={styles.volumeSection}>
|
||||
<Ionicons name="volume-low" size={18} color={colors.mutedForeground} />
|
||||
<Slider
|
||||
style={styles.volumeSlider}
|
||||
minimumValue={0}
|
||||
maximumValue={1}
|
||||
<PlayerSlider
|
||||
accessibilityLabel="Volume"
|
||||
value={volume}
|
||||
maximumValue={1}
|
||||
fillColor={colors.sliderFill}
|
||||
activeFillColor={colors.foreground}
|
||||
trackColor={colors.sliderTrack}
|
||||
onValueChange={setVolume}
|
||||
minimumTrackTintColor={colors.foreground}
|
||||
maximumTrackTintColor={player.trackInactive}
|
||||
thumbTintColor={colors.foreground}
|
||||
leading={
|
||||
<PlayerSymbol
|
||||
name="speaker.fill"
|
||||
fallback="volume-low"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
trailing={
|
||||
<PlayerSymbol
|
||||
name="speaker.wave.3.fill"
|
||||
fallback="volume-high"
|
||||
size={14}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<Ionicons name="volume-high" size={18} color={colors.mutedForeground} />
|
||||
</View>
|
||||
|
||||
<View style={styles.footer}>
|
||||
<Pressable onPress={() => void toggleShuffle()} hitSlop={12} style={styles.footerButton}>
|
||||
<Ionicons
|
||||
name="shuffle"
|
||||
size={22}
|
||||
color={shuffleEnabled ? appleMusic.pink : colors.mutedForeground}
|
||||
/>
|
||||
</Pressable>
|
||||
<Pressable onPress={() => void cycleRepeat()} hitSlop={12} style={styles.footerButton}>
|
||||
<Ionicons
|
||||
name={repeatEnabled === "once" ? "repeat-outline" : "repeat"}
|
||||
size={22}
|
||||
color={repeatEnabled !== "none" ? appleMusic.pink : colors.mutedForeground}
|
||||
/>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
onPress={() => push("/queue")}
|
||||
hitSlop={12}
|
||||
style={styles.footerButton}
|
||||
disabled={queueSongIds.length === 0}
|
||||
>
|
||||
<Ionicons name="list" size={22} color={colors.mutedForeground} />
|
||||
</Pressable>
|
||||
<View style={styles.footer}>
|
||||
<Pressable
|
||||
disabled
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Lyrics"
|
||||
accessibilityState={{ disabled: true }}
|
||||
style={[styles.queueButton, styles.unavailable]}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="quote.bubble"
|
||||
fallback={{ material: "lyrics" }}
|
||||
size={27}
|
||||
weight="semibold"
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
disabled
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={Platform.OS === "ios" ? "AirPlay" : "Cast"}
|
||||
accessibilityState={{ disabled: true }}
|
||||
style={[styles.queueButton, styles.unavailable]}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="airplay.audio"
|
||||
fallback={{ material: "cast" }}
|
||||
size={27}
|
||||
weight="semibold"
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
onPress={toggleQueue}
|
||||
hitSlop={8}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={showQueue ? "Hide queue" : "Show queue"}
|
||||
accessibilityState={{ selected: showQueue }}
|
||||
style={[
|
||||
styles.queueButton,
|
||||
showQueue && { backgroundColor: colors.selected },
|
||||
]}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="list.bullet"
|
||||
fallback="list"
|
||||
size={25}
|
||||
weight="semibold"
|
||||
color={
|
||||
showQueue ? colors.selectedForeground : colors.foreground
|
||||
}
|
||||
/>
|
||||
{!showQueue && (shuffleEnabled || repeatEnabled !== "none") ? (
|
||||
<View
|
||||
style={[styles.badge, { backgroundColor: colors.control }]}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name={
|
||||
shuffleEnabled
|
||||
? "shuffle"
|
||||
: repeatEnabled === "once"
|
||||
? "repeat.1"
|
||||
: "repeat"
|
||||
}
|
||||
fallback={shuffleEnabled ? "shuffle" : "repeat"}
|
||||
size={14}
|
||||
weight="bold"
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
</GestureDetector>
|
||||
</View>
|
||||
</Animated.View>
|
||||
)
|
||||
}
|
||||
|
||||
/** Title and artist with the favorite and more buttons. */
|
||||
function SongMeta({
|
||||
song,
|
||||
colors,
|
||||
compact = false,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
colors: NowPlayingColors
|
||||
compact?: boolean
|
||||
}) {
|
||||
const { isSongFavorite, toggleSongFavorite } = useFavorites()
|
||||
const { handleSongAction } = useMediaMenuActions()
|
||||
const favorited = isSongFavorite(song.id)
|
||||
|
||||
async function handleAction(action: MediaAction) {
|
||||
await handleSongAction(song, action)
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.metaRow}>
|
||||
<View style={styles.metaText}>
|
||||
<MarqueeText
|
||||
text={song.title}
|
||||
style={[
|
||||
compact ? styles.compactTitle : styles.title,
|
||||
{ color: colors.foreground },
|
||||
]}
|
||||
/>
|
||||
<MarqueeText
|
||||
text={song.artist.name}
|
||||
style={[
|
||||
compact ? styles.compactArtist : styles.artist,
|
||||
{ color: colors.secondaryForeground },
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
<Pressable
|
||||
onPress={() => void toggleSongFavorite(song.id)}
|
||||
hitSlop={10}
|
||||
style={styles.metaButton}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={favorited ? "Unfavorite" : "Favorite"}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name={favorited ? "star.fill" : "star"}
|
||||
fallback={favorited ? "star" : "star-outline"}
|
||||
size={22}
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
<MediaActionMenu
|
||||
favorited={favorited}
|
||||
navigation={{
|
||||
artist: { id: song.artist.id },
|
||||
album: { id: song.album.id },
|
||||
}}
|
||||
includeActions={[
|
||||
"play-next",
|
||||
"play-last",
|
||||
"shuffle",
|
||||
"favorite",
|
||||
"go-artist",
|
||||
"go-album",
|
||||
]}
|
||||
onAction={handleAction}
|
||||
style={styles.menu}
|
||||
>
|
||||
<Pressable
|
||||
hitSlop={10}
|
||||
style={styles.metaButton}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="More"
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="ellipsis"
|
||||
fallback="ellipsis-horizontal"
|
||||
size={20}
|
||||
weight="semibold"
|
||||
color={colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
</MediaActionMenu>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function TransportButton({
|
||||
colors,
|
||||
large = false,
|
||||
accessibilityLabel,
|
||||
onPress,
|
||||
children,
|
||||
}: {
|
||||
colors: NowPlayingColors
|
||||
large?: boolean
|
||||
accessibilityLabel: string
|
||||
onPress: () => void
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<Pressable
|
||||
onPress={onPress}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
style={({ pressed }) => [
|
||||
large ? styles.playButton : styles.skipButton,
|
||||
pressed && {
|
||||
backgroundColor: colors.controlPressed,
|
||||
transform: [{ scale: 0.9 }],
|
||||
},
|
||||
]}
|
||||
>
|
||||
{children}
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
root: {
|
||||
flex: 1,
|
||||
},
|
||||
backgroundImage: {
|
||||
...StyleSheet.absoluteFill,
|
||||
},
|
||||
scrim: {
|
||||
...StyleSheet.absoluteFill,
|
||||
overflow: "hidden",
|
||||
},
|
||||
safe: {
|
||||
flex: 1,
|
||||
paddingHorizontal: spacing.xl,
|
||||
},
|
||||
fill: {
|
||||
flex: 1,
|
||||
},
|
||||
handleRow: {
|
||||
alignItems: "center",
|
||||
paddingTop: spacing.sm,
|
||||
paddingBottom: spacing.md,
|
||||
paddingBottom: spacing.sm,
|
||||
},
|
||||
handle: {
|
||||
width: 36,
|
||||
height: 5,
|
||||
borderRadius: radius.full,
|
||||
},
|
||||
upper: {
|
||||
stage: {
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
justifyContent: "center",
|
||||
},
|
||||
artworkWrap: {
|
||||
artworkMode: {
|
||||
paddingHorizontal: HORIZONTAL_INSET,
|
||||
},
|
||||
artworkArea: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
paddingVertical: spacing.sm,
|
||||
},
|
||||
artwork: {
|
||||
width: "100%",
|
||||
maxWidth: 320,
|
||||
aspectRatio: 1,
|
||||
borderRadius: 12,
|
||||
artworkShadow: {
|
||||
borderRadius: radius.md,
|
||||
shadowColor: "#000",
|
||||
shadowOpacity: 0.45,
|
||||
shadowRadius: 24,
|
||||
shadowOffset: { width: 0, height: 12 },
|
||||
shadowOffset: { width: 0, height: 14 },
|
||||
},
|
||||
controls: {
|
||||
flexShrink: 0,
|
||||
meta: {
|
||||
height: META_HEIGHT,
|
||||
justifyContent: "center",
|
||||
},
|
||||
queueHeader: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 14,
|
||||
},
|
||||
queueArtwork: {
|
||||
width: 64,
|
||||
height: 64,
|
||||
borderRadius: 8,
|
||||
},
|
||||
metaRow: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
metaText: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
songTitle: {
|
||||
fontSize: 22,
|
||||
fontWeight: "700",
|
||||
lineHeight: 28,
|
||||
title: {
|
||||
fontSize: 20,
|
||||
fontWeight: "600",
|
||||
},
|
||||
artistName: {
|
||||
fontSize: 18,
|
||||
marginTop: spacing.xs,
|
||||
artist: {
|
||||
fontSize: 20,
|
||||
marginTop: 1,
|
||||
},
|
||||
metaActions: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
paddingTop: 4,
|
||||
compactTitle: {
|
||||
fontSize: 17,
|
||||
fontWeight: "600",
|
||||
},
|
||||
circleButton: {
|
||||
width: 34,
|
||||
height: 34,
|
||||
borderRadius: 17,
|
||||
compactArtist: {
|
||||
fontSize: 15,
|
||||
marginTop: 1,
|
||||
},
|
||||
menu: {
|
||||
alignSelf: "center",
|
||||
},
|
||||
metaButton: {
|
||||
width: 30,
|
||||
height: 30,
|
||||
borderRadius: 15,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
progressSection: {
|
||||
marginBottom: spacing.lg,
|
||||
},
|
||||
slider: {
|
||||
width: "100%",
|
||||
height: 28,
|
||||
controls: {
|
||||
flexShrink: 0,
|
||||
paddingHorizontal: HORIZONTAL_INSET,
|
||||
paddingTop: spacing.md,
|
||||
},
|
||||
timeRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
marginTop: -4,
|
||||
},
|
||||
format: {
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
right: 0,
|
||||
alignItems: "center",
|
||||
},
|
||||
time: {
|
||||
fontSize: 13,
|
||||
fontSize: 12,
|
||||
fontWeight: "600",
|
||||
fontVariant: ["tabular-nums"],
|
||||
},
|
||||
transport: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 48,
|
||||
marginBottom: spacing.lg,
|
||||
gap: 28,
|
||||
marginVertical: spacing.xl,
|
||||
},
|
||||
skipButton: {
|
||||
width: 72,
|
||||
height: 72,
|
||||
borderRadius: 36,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
playButton: {
|
||||
width: 72,
|
||||
width: 84,
|
||||
height: 84,
|
||||
borderRadius: 42,
|
||||
alignItems: "center",
|
||||
},
|
||||
volumeSection: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.sm,
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
volumeSlider: {
|
||||
flex: 1,
|
||||
height: 28,
|
||||
justifyContent: "center",
|
||||
},
|
||||
footer: {
|
||||
flexDirection: "row",
|
||||
justifyContent: "space-between",
|
||||
paddingHorizontal: spacing.xxl,
|
||||
paddingTop: spacing.sm,
|
||||
paddingTop: spacing.md,
|
||||
paddingHorizontal: 40,
|
||||
},
|
||||
footerButton: {
|
||||
minWidth: 44,
|
||||
minHeight: 44,
|
||||
unavailable: {
|
||||
opacity: 0.35,
|
||||
},
|
||||
queueButton: {
|
||||
width: 38,
|
||||
height: 38,
|
||||
borderRadius: 19,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
badge: {
|
||||
position: "absolute",
|
||||
top: -10,
|
||||
right: -11,
|
||||
width: 21,
|
||||
height: 21,
|
||||
borderRadius: 10.5,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { StyleSheet, Text, View } from "react-native"
|
||||
import Svg, { G, Path } from "react-native-svg"
|
||||
|
||||
import type { PlaybackFormat } from "@otunes/convex/playback-stream"
|
||||
|
||||
const LABEL_SIZE = 13
|
||||
const MARK_HEIGHT = 11
|
||||
|
||||
function DolbyMark({ color }: { color: string }) {
|
||||
return (
|
||||
<Svg
|
||||
width={(MARK_HEIGHT * 23) / 16}
|
||||
height={MARK_HEIGHT}
|
||||
viewBox="0 0 23 16"
|
||||
>
|
||||
<Path d="M0 0H2.5A8 8 0 0 1 2.5 16H0Z" fill={color} />
|
||||
<Path d="M23 0H20.5A8 8 0 0 0 20.5 16H23Z" fill={color} />
|
||||
</Svg>
|
||||
)
|
||||
}
|
||||
|
||||
const LOSSLESS_PEAKS = [110, 215, 320]
|
||||
const LOSSLESS_THIN_WIDTH = 24
|
||||
const LOSSLESS_STROKES: [peak: number, d: string][] = [
|
||||
[110, "M-70 320C-62 245 -38 166 0 166"],
|
||||
[215, "M-70 320C-62 245 -38 166 0 166"],
|
||||
[320, "M-30 185C-22 173 -11 166 0 166"],
|
||||
[110, "M166 413C176 413 186 406 194 395"],
|
||||
[215, "M166 413C200 413 226 340 240 275"],
|
||||
[320, "M166 413C200 413 226 340 240 275"],
|
||||
]
|
||||
const LOSSLESS_FALL =
|
||||
"M0 178L4 179L8 181L12 184L16 189L20 196L23 204L27 213L30 223L34 233L39 243L43 254L48 266L53 278L58 289L62 301L66 313L71 325L75 336L79 347L83 357L86 364L89 370L93 377L97 382L101 387L105 392L109 397L113 401L117 405L121 408L126 412L130 415L134 417L139 419L143 421L148 423L152 424L157 424L161 425L166 425L166 401L163 401L161 400L159 400L157 399L154 397L152 396L151 394L149 392L147 389L145 386L143 383L142 380L140 376L138 371L137 367L135 362L134 357L132 351L130 345L127 339L124 330L120 319L116 308L111 297L107 285L102 272L98 260L93 248L88 235L82 223L76 212L69 201L61 192L53 183L45 175L37 168L28 163L19 158L10 155L0 154Z"
|
||||
const LOSSLESS_FALL_GAP =
|
||||
"M0 178L4 180L6 184L8 190L9 197L11 203L14 210L17 219L21 228L24 238L29 248L33 259L38 270L43 282L47 293L52 305L56 317L60 328L64 340L68 351L73 361L76 368L79 375L83 381L87 387L91 393L95 398L100 403L104 408L109 412L113 416L118 419L124 422L130 424L135 425L141 426L147 426L152 426L157 425L161 425L166 425L166 401L163 401L161 399L159 398L158 395L157 393L156 390L155 387L155 384L154 381L153 379L152 376L150 373L149 369L148 366L146 361L145 357L143 352L142 347L140 341L137 335L134 326L130 315L126 304L122 293L117 281L113 268L108 256L103 243L98 231L92 219L86 207L79 196L71 186L62 177L53 168L44 161L32 157L21 155L10 154L0 154Z"
|
||||
|
||||
/**
|
||||
* Three overlapping waves. Each thick downstroke is outlined in the
|
||||
* background color so it reads as passing over the strokes behind it.
|
||||
*/
|
||||
function LosslessMark({
|
||||
color,
|
||||
backgroundColor,
|
||||
}: {
|
||||
color: string
|
||||
backgroundColor: string
|
||||
}) {
|
||||
return (
|
||||
<Svg
|
||||
width={(MARK_HEIGHT * 544) / 271}
|
||||
height={MARK_HEIGHT}
|
||||
viewBox="28 154 544 271"
|
||||
>
|
||||
{LOSSLESS_STROKES.map(([peak, d], index) => (
|
||||
<Path
|
||||
key={index}
|
||||
d={d}
|
||||
x={peak}
|
||||
stroke={color}
|
||||
strokeWidth={LOSSLESS_THIN_WIDTH}
|
||||
strokeLinecap="round"
|
||||
fill="none"
|
||||
/>
|
||||
))}
|
||||
{LOSSLESS_PEAKS.map((peak) => (
|
||||
<G key={peak} x={peak}>
|
||||
<Path d={LOSSLESS_FALL_GAP} fill={backgroundColor} />
|
||||
<Path d={LOSSLESS_FALL} fill={color} />
|
||||
</G>
|
||||
))}
|
||||
</Svg>
|
||||
)
|
||||
}
|
||||
|
||||
/** The Dolby Atmos or Lossless label shown under the progress bar. */
|
||||
export function AudioFormatBadge({
|
||||
format,
|
||||
color,
|
||||
backgroundColor,
|
||||
}: {
|
||||
format: PlaybackFormat
|
||||
color: string
|
||||
backgroundColor: string
|
||||
}) {
|
||||
const label = format === "atmos" ? "Dolby Atmos" : "Lossless"
|
||||
return (
|
||||
<View style={styles.badge} accessibilityLabel={label}>
|
||||
{format === "atmos" ? (
|
||||
<DolbyMark color={color} />
|
||||
) : (
|
||||
<LosslessMark color={color} backgroundColor={backgroundColor} />
|
||||
)}
|
||||
<Text style={[styles.label, { color }]}>{label}</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
badge: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 3,
|
||||
},
|
||||
label: {
|
||||
fontSize: LABEL_SIZE,
|
||||
fontWeight: "500",
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
import { memo } from "react"
|
||||
import { StyleSheet, Text, View } from "react-native"
|
||||
|
||||
import { useThemeColors } from "@/lib/theme"
|
||||
|
||||
/** Horizontal inset for rows and dividers in album and playlist track lists. */
|
||||
export const collectionInset = 20
|
||||
|
||||
/** Separates a collection's header from its track list. */
|
||||
export function CollectionDivider({ color }: { color?: string }) {
|
||||
const colors = useThemeColors()
|
||||
return (
|
||||
<View
|
||||
style={[styles.divider, { backgroundColor: color ?? colors.border }]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const DiscHeader = memo(function DiscHeader({
|
||||
label,
|
||||
color,
|
||||
}: {
|
||||
label: string
|
||||
color?: string
|
||||
}) {
|
||||
const colors = useThemeColors()
|
||||
return (
|
||||
<Text style={[styles.discHeader, { color: color ?? colors.foreground }]}>
|
||||
{label}
|
||||
</Text>
|
||||
)
|
||||
})
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
divider: {
|
||||
height: StyleSheet.hairlineWidth,
|
||||
marginHorizontal: collectionInset,
|
||||
},
|
||||
discHeader: {
|
||||
fontSize: 17,
|
||||
fontWeight: "700",
|
||||
paddingHorizontal: collectionInset,
|
||||
paddingTop: 24,
|
||||
paddingBottom: 8,
|
||||
},
|
||||
})
|
||||
@@ -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}
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
import * as Haptics from "expo-haptics"
|
||||
import { SymbolView } from "expo-symbols"
|
||||
import { useCallback, useMemo, useState, type ReactNode } from "react"
|
||||
import {
|
||||
PlatformColor,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
type LayoutChangeEvent,
|
||||
} from "react-native"
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler"
|
||||
import Animated, {
|
||||
cancelAnimation,
|
||||
Extrapolation,
|
||||
interpolate,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withSpring,
|
||||
withTiming,
|
||||
} from "react-native-reanimated"
|
||||
import { scheduleOnRN } from "react-native-worklets"
|
||||
|
||||
const ACTION_WIDTH = 82
|
||||
const CARD_ROUNDING_REVEAL = 40
|
||||
const PILL_MIN_MARGIN = 10
|
||||
const PILL_COMMITTED_MARGIN = 6
|
||||
const PILL_WIDTH_INPUT = [24, ACTION_WIDTH, 220]
|
||||
const PILL_WIDTH_OUTPUT = [0, 62, 200]
|
||||
const PILL_HEIGHT_INPUT = [0, 24, 62, 140, 200]
|
||||
const PILL_HEIGHT_RATIO = [0, 0.3, 0.77, 0.82, 0.86]
|
||||
const ICON_FULL_SIZE_REVEAL = 64
|
||||
const FULL_SWIPE_RATIO = 0.55
|
||||
const FLING_VELOCITY = 400
|
||||
const SETTLE_SPRING = { duration: 450, dampingRatio: 1 }
|
||||
const LABEL_SPRING = { duration: 300, dampingRatio: 0.85 }
|
||||
const SLIDE_OUT = { duration: 200 }
|
||||
const COLLAPSE = { duration: 250 }
|
||||
|
||||
/**
|
||||
* Keeps at most one row open, like a `UITableView`: opening a row closes the
|
||||
* previous one, and `closeOpenRow` closes whichever is open (call it when the
|
||||
* list starts scrolling).
|
||||
*/
|
||||
export type SwipeRowGroup = {
|
||||
setOpen: (close: () => void) => void
|
||||
clear: (close: () => void) => void
|
||||
closeOpenRow: () => void
|
||||
}
|
||||
|
||||
export function useSwipeRowGroup(): SwipeRowGroup {
|
||||
const [group] = useState<SwipeRowGroup>(() => {
|
||||
let openRowClose: (() => void) | null = null
|
||||
return {
|
||||
setOpen(close) {
|
||||
if (openRowClose && openRowClose !== close) openRowClose()
|
||||
openRowClose = close
|
||||
},
|
||||
clear(close) {
|
||||
if (openRowClose === close) openRowClose = null
|
||||
},
|
||||
closeOpenRow() {
|
||||
openRowClose?.()
|
||||
openRowClose = null
|
||||
},
|
||||
}
|
||||
})
|
||||
return group
|
||||
}
|
||||
|
||||
type SwipeToRemoveRowProps = {
|
||||
group: SwipeRowGroup
|
||||
backgroundColor: string
|
||||
actionAccessibilityLabel: string
|
||||
/** Resolves `false` if the removal failed, which restores the row. */
|
||||
onRemove: () => Promise<boolean>
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* The iOS 26 trailing swipe-to-delete row: the row lifts into a rounded card
|
||||
* and a red pill grows in the revealed space. Release past half the pill to
|
||||
* leave it open, or drag past the full-swipe point (haptic, the pill fills the
|
||||
* space) to remove on release.
|
||||
*/
|
||||
export function SwipeToRemoveRow(props: SwipeToRemoveRowProps) {
|
||||
const [generation, setGeneration] = useState(0)
|
||||
const restore = useCallback(() => setGeneration((value) => value + 1), [])
|
||||
|
||||
return <SwipeRowBody key={generation} {...props} onRestore={restore} />
|
||||
}
|
||||
|
||||
function SwipeRowBody({
|
||||
group,
|
||||
backgroundColor,
|
||||
actionAccessibilityLabel,
|
||||
onRemove,
|
||||
onRestore,
|
||||
children,
|
||||
}: SwipeToRemoveRowProps & { onRestore: () => void }) {
|
||||
const width = useSharedValue(0)
|
||||
const height = useSharedValue(0)
|
||||
const translateX = useSharedValue(0)
|
||||
const startX = useSharedValue(0)
|
||||
const committed = useSharedValue(false)
|
||||
const commitProgress = useSharedValue(0)
|
||||
const collapse = useSharedValue(0)
|
||||
const removing = useSharedValue(false)
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
|
||||
const close = useCallback(() => {
|
||||
if (removing.value) return
|
||||
translateX.value = withSpring(0, SETTLE_SPRING)
|
||||
setIsOpen(false)
|
||||
}, [removing, translateX])
|
||||
|
||||
const handleSwipeStart = useCallback(() => group.setOpen(close), [close, group])
|
||||
|
||||
const handleSettle = useCallback(
|
||||
(open: boolean) => {
|
||||
setIsOpen(open)
|
||||
if (!open) group.clear(close)
|
||||
},
|
||||
[close, group]
|
||||
)
|
||||
|
||||
const handleRemove = useCallback(async () => {
|
||||
group.clear(close)
|
||||
if (!(await onRemove())) onRestore()
|
||||
}, [close, group, onRemove, onRestore])
|
||||
|
||||
const animateRemoval = useCallback(() => {
|
||||
"worklet"
|
||||
removing.value = true
|
||||
commitProgress.value = withSpring(1, LABEL_SPRING)
|
||||
translateX.value = withTiming(-width.value, SLIDE_OUT, (slid) => {
|
||||
if (!slid) return
|
||||
collapse.value = withTiming(1, COLLAPSE, (collapsed) => {
|
||||
if (collapsed) scheduleOnRN(handleRemove)
|
||||
})
|
||||
})
|
||||
}, [collapse, commitProgress, handleRemove, removing, translateX, width])
|
||||
|
||||
const pan = useMemo(() => {
|
||||
const gesture = Gesture.Pan()
|
||||
.failOffsetY([-10, 10])
|
||||
.onStart(() => {
|
||||
if (removing.value) return
|
||||
cancelAnimation(translateX)
|
||||
startX.value = translateX.value
|
||||
scheduleOnRN(handleSwipeStart)
|
||||
})
|
||||
.onUpdate((event) => {
|
||||
if (removing.value) return
|
||||
const rowWidth = width.value
|
||||
const x = Math.max(
|
||||
-rowWidth,
|
||||
Math.min(0, startX.value + event.translationX)
|
||||
)
|
||||
translateX.value = x
|
||||
|
||||
const shouldCommit = -x > rowWidth * FULL_SWIPE_RATIO
|
||||
if (shouldCommit !== committed.value) {
|
||||
committed.value = shouldCommit
|
||||
commitProgress.value = withSpring(shouldCommit ? 1 : 0, LABEL_SPRING)
|
||||
scheduleOnRN(impact)
|
||||
}
|
||||
})
|
||||
.onEnd((event) => {
|
||||
if (removing.value) return
|
||||
if (committed.value) {
|
||||
animateRemoval()
|
||||
return
|
||||
}
|
||||
|
||||
const velocity = event.velocityX
|
||||
const open =
|
||||
velocity < -FLING_VELOCITY ||
|
||||
(velocity <= FLING_VELOCITY && translateX.value < -ACTION_WIDTH / 2)
|
||||
translateX.value = withSpring(open ? -ACTION_WIDTH : 0, {
|
||||
...SETTLE_SPRING,
|
||||
velocity,
|
||||
})
|
||||
scheduleOnRN(handleSettle, open)
|
||||
})
|
||||
|
||||
return isOpen
|
||||
? gesture.activeOffsetX([-10, 10])
|
||||
: gesture.activeOffsetX(-10).failOffsetX(10)
|
||||
}, [
|
||||
animateRemoval,
|
||||
commitProgress,
|
||||
committed,
|
||||
handleSettle,
|
||||
handleSwipeStart,
|
||||
isOpen,
|
||||
removing,
|
||||
startX,
|
||||
translateX,
|
||||
width,
|
||||
])
|
||||
|
||||
const handleLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
if (removing.value) return
|
||||
width.value = event.nativeEvent.layout.width
|
||||
height.value = event.nativeEvent.layout.height
|
||||
},
|
||||
[height, removing, width]
|
||||
)
|
||||
|
||||
const containerStyle = useAnimatedStyle(() =>
|
||||
collapse.value > 0 ? { height: height.value * (1 - collapse.value) } : {}
|
||||
)
|
||||
|
||||
const contentStyle = useAnimatedStyle(() => ({
|
||||
borderRadius: interpolate(
|
||||
-translateX.value,
|
||||
[0, CARD_ROUNDING_REVEAL],
|
||||
[0, height.value / 2],
|
||||
Extrapolation.CLAMP
|
||||
),
|
||||
transform: [{ translateX: translateX.value }],
|
||||
}))
|
||||
|
||||
const cardFillStyle = useAnimatedStyle(() => ({
|
||||
opacity: interpolate(
|
||||
-translateX.value,
|
||||
[0, CARD_ROUNDING_REVEAL],
|
||||
[0, 1],
|
||||
Extrapolation.CLAMP
|
||||
),
|
||||
}))
|
||||
|
||||
const actionStyle = useAnimatedStyle(() => ({
|
||||
width: -translateX.value,
|
||||
}))
|
||||
|
||||
// The pill grows out of a dot centered in the revealed space; past the
|
||||
// full-swipe point it stretches to fill that space.
|
||||
const pillStyle = useAnimatedStyle(() => {
|
||||
const revealed = -translateX.value
|
||||
const rowHeight = height.value
|
||||
const resting = Math.min(
|
||||
revealed - PILL_MIN_MARGIN * 2,
|
||||
interpolate(
|
||||
revealed,
|
||||
PILL_WIDTH_INPUT,
|
||||
PILL_WIDTH_OUTPUT,
|
||||
Extrapolation.EXTEND
|
||||
)
|
||||
)
|
||||
const pillWidth = Math.max(
|
||||
0,
|
||||
resting +
|
||||
(revealed - PILL_COMMITTED_MARGIN * 2 - resting) *
|
||||
commitProgress.value
|
||||
)
|
||||
const restingHeight = interpolate(
|
||||
pillWidth,
|
||||
PILL_HEIGHT_INPUT,
|
||||
PILL_HEIGHT_RATIO.map((ratio) => ratio * rowHeight),
|
||||
Extrapolation.CLAMP
|
||||
)
|
||||
const pillHeight =
|
||||
restingHeight +
|
||||
(rowHeight - PILL_COMMITTED_MARGIN * 2 - restingHeight) *
|
||||
commitProgress.value
|
||||
return {
|
||||
width: pillWidth,
|
||||
height: pillHeight,
|
||||
borderRadius: pillHeight / 2,
|
||||
opacity: 1 - collapse.value,
|
||||
}
|
||||
})
|
||||
|
||||
const iconStyle = useAnimatedStyle(() => ({
|
||||
transform: [
|
||||
{
|
||||
scale: interpolate(
|
||||
-translateX.value,
|
||||
[PILL_WIDTH_INPUT[0], ICON_FULL_SIZE_REVEAL],
|
||||
[0, 1],
|
||||
Extrapolation.CLAMP
|
||||
),
|
||||
},
|
||||
],
|
||||
}))
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
onLayout={handleLayout}
|
||||
style={[styles.container, containerStyle]}
|
||||
>
|
||||
<Animated.View style={[styles.action, actionStyle]}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={actionAccessibilityLabel}
|
||||
onPress={() => animateRemoval()}
|
||||
style={styles.actionButton}
|
||||
>
|
||||
<Animated.View style={[styles.pill, pillStyle]}>
|
||||
<Animated.View style={iconStyle}>
|
||||
<SymbolView
|
||||
name="minus.circle.fill"
|
||||
size={20}
|
||||
tintColor="white"
|
||||
/>
|
||||
</Animated.View>
|
||||
</Animated.View>
|
||||
</Pressable>
|
||||
</Animated.View>
|
||||
<GestureDetector gesture={pan}>
|
||||
<Animated.View style={[styles.card, { backgroundColor }, contentStyle]}>
|
||||
<Animated.View
|
||||
pointerEvents="none"
|
||||
style={[styles.cardFill, cardFillStyle]}
|
||||
/>
|
||||
{children}
|
||||
{isOpen ? (
|
||||
<Pressable
|
||||
accessible={false}
|
||||
onPress={close}
|
||||
style={StyleSheet.absoluteFill}
|
||||
/>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
</GestureDetector>
|
||||
</Animated.View>
|
||||
)
|
||||
}
|
||||
|
||||
function impact() {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: { overflow: "hidden" },
|
||||
card: { overflow: "hidden" },
|
||||
cardFill: {
|
||||
...StyleSheet.absoluteFill,
|
||||
backgroundColor: PlatformColor("tertiarySystemFill"),
|
||||
},
|
||||
action: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
},
|
||||
actionButton: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
pill: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
backgroundColor: PlatformColor("systemRed"),
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useEffect, useState } from "react"
|
||||
import {
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type StyleProp,
|
||||
type TextStyle,
|
||||
} from "react-native"
|
||||
import Animated, {
|
||||
cancelAnimation,
|
||||
Easing,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withDelay,
|
||||
withRepeat,
|
||||
withSequence,
|
||||
withTiming,
|
||||
} from "react-native-reanimated"
|
||||
|
||||
const GAP = 48
|
||||
const PAUSE_MS = 2500
|
||||
const POINTS_PER_SECOND = 30
|
||||
// Wide enough that the measured text is never wrapped or truncated.
|
||||
const MEASURE_WIDTH = 10_000
|
||||
|
||||
/**
|
||||
* One line of text that scrolls when it doesn't fit, pausing at the start of
|
||||
* each loop like the Now Playing title in Apple Music.
|
||||
*/
|
||||
export function MarqueeText({
|
||||
text,
|
||||
style,
|
||||
}: {
|
||||
text: string
|
||||
style: StyleProp<TextStyle>
|
||||
}) {
|
||||
const [containerWidth, setContainerWidth] = useState(0)
|
||||
const [textWidth, setTextWidth] = useState(0)
|
||||
const offset = useSharedValue(0)
|
||||
const overflows = containerWidth > 0 && textWidth > containerWidth + 1
|
||||
|
||||
useEffect(() => {
|
||||
cancelAnimation(offset)
|
||||
offset.value = 0
|
||||
if (!overflows) return
|
||||
const distance = textWidth + GAP
|
||||
offset.value = withRepeat(
|
||||
withSequence(
|
||||
withDelay(
|
||||
PAUSE_MS,
|
||||
withTiming(-distance, {
|
||||
duration: (distance / POINTS_PER_SECOND) * 1000,
|
||||
easing: Easing.linear,
|
||||
})
|
||||
),
|
||||
withTiming(0, { duration: 0 })
|
||||
),
|
||||
-1
|
||||
)
|
||||
return () => cancelAnimation(offset)
|
||||
}, [offset, overflows, text, textWidth])
|
||||
|
||||
const trackStyle = useAnimatedStyle(() => ({
|
||||
transform: [{ translateX: offset.value }],
|
||||
}))
|
||||
|
||||
return (
|
||||
<View
|
||||
style={styles.container}
|
||||
onLayout={(event) => setContainerWidth(event.nativeEvent.layout.width)}
|
||||
accessible
|
||||
accessibilityLabel={text}
|
||||
>
|
||||
<Animated.View style={[styles.track, trackStyle]}>
|
||||
<Text
|
||||
style={style}
|
||||
numberOfLines={1}
|
||||
onLayout={(event) => setTextWidth(event.nativeEvent.layout.width)}
|
||||
>
|
||||
{text}
|
||||
</Text>
|
||||
{overflows ? (
|
||||
<Text style={[style, { marginLeft: GAP }]} numberOfLines={1}>
|
||||
{text}
|
||||
</Text>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
overflow: "hidden",
|
||||
},
|
||||
track: {
|
||||
flexDirection: "row",
|
||||
width: MEASURE_WIDTH,
|
||||
},
|
||||
})
|
||||
@@ -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 />
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,795 @@
|
||||
import * as Haptics from "expo-haptics"
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react"
|
||||
import {
|
||||
FlatList,
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type CellRendererProps,
|
||||
} from "react-native"
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler"
|
||||
import Animated, {
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withDelay,
|
||||
withTiming,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated"
|
||||
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"
|
||||
import { scheduleOnRN } from "react-native-worklets"
|
||||
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import {
|
||||
SwipeToRemoveRow,
|
||||
useSwipeRowGroup,
|
||||
type SwipeRowGroup,
|
||||
} from "@/components/ios-swipe-to-remove-row"
|
||||
import { PlayerSymbol } from "@/components/player-symbol"
|
||||
import { usePlayback } from "@/contexts/playback"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import type { Id } from "@otunes/convex/_generated/dataModel"
|
||||
import type { NowPlayingColors } from "@/lib/now-playing-colors"
|
||||
import { useSong } from "@/lib/song-cache"
|
||||
import { albumCoverUrl } from "@/lib/urls"
|
||||
|
||||
export const QUEUE_HORIZONTAL_INSET = 26
|
||||
|
||||
const ROW_HEIGHT = 64
|
||||
const HISTORY_HEADER_HEIGHT = 48
|
||||
const CURRENT_HEIGHT = 92
|
||||
const CONTROLS_HEIGHT = 108
|
||||
const TOGGLES_ONLY_HEIGHT = 64
|
||||
const BOTTOM_FADE_HEIGHT = 36
|
||||
const DRAG_SETTLE = { duration: 180 }
|
||||
const DRAG_HIGHLIGHT_Z_INDEX = 5
|
||||
const TAP_HIGHLIGHT_DELAY_MS = 80
|
||||
|
||||
type QueueListItem =
|
||||
| { type: "history-header"; key: string }
|
||||
| { type: "history"; key: string; songId: Id<"songs">; historyIndex: number }
|
||||
| { type: "current"; key: string }
|
||||
| { type: "controls"; key: string; showTitle: boolean }
|
||||
| { type: "upcoming"; key: string; songId: Id<"songs">; queueIndex: number }
|
||||
| { type: "empty"; key: string; height: number }
|
||||
|
||||
function itemHeight(item: QueueListItem) {
|
||||
switch (item.type) {
|
||||
case "history-header":
|
||||
return HISTORY_HEADER_HEIGHT
|
||||
case "current":
|
||||
return CURRENT_HEIGHT
|
||||
case "controls":
|
||||
return item.showTitle ? CONTROLS_HEIGHT : TOGGLES_ONLY_HEIGHT
|
||||
case "empty":
|
||||
return item.height
|
||||
default:
|
||||
return ROW_HEIGHT
|
||||
}
|
||||
}
|
||||
|
||||
type DragState = {
|
||||
from: SharedValue<number>
|
||||
to: SharedValue<number>
|
||||
y: SharedValue<number>
|
||||
/** Set once a drag is released so it settles and drops only once. */
|
||||
dropping: SharedValue<boolean>
|
||||
}
|
||||
|
||||
/**
|
||||
* The queue shown in place of the artwork: history above (scrolled out of view
|
||||
* at first), then the current song, the shuffle and repeat toggles, and the
|
||||
* upcoming songs, which can be dragged to reorder or swiped away.
|
||||
*/
|
||||
export function NowPlayingQueue({
|
||||
colors,
|
||||
viewportHeight,
|
||||
currentHeader,
|
||||
}: {
|
||||
colors: NowPlayingColors
|
||||
viewportHeight: number
|
||||
currentHeader: ReactNode
|
||||
}) {
|
||||
const {
|
||||
queueSongIds,
|
||||
queueHistorySongIds,
|
||||
shuffleEnabled,
|
||||
repeatEnabled,
|
||||
toggleShuffle,
|
||||
cycleRepeat,
|
||||
clearHistory,
|
||||
reorderQueue,
|
||||
skipToQueueIndex,
|
||||
skipToHistoryIndex,
|
||||
} = usePlayback()
|
||||
const swipeGroup = useSwipeRowGroup()
|
||||
const [scrollEnabled, setScrollEnabled] = useState(true)
|
||||
const dragFrom = useSharedValue(-1)
|
||||
const dragTo = useSharedValue(-1)
|
||||
const dragY = useSharedValue(0)
|
||||
const dragDropping = useSharedValue(false)
|
||||
const drag = useMemo<DragState>(
|
||||
() => ({ from: dragFrom, to: dragTo, y: dragY, dropping: dragDropping }),
|
||||
[dragDropping, dragFrom, dragTo, dragY]
|
||||
)
|
||||
const listRef = useRef<FlatList<QueueListItem>>(null)
|
||||
const queueRef = useRef(queueSongIds)
|
||||
queueRef.current = queueSongIds
|
||||
const resetDragOnCommit = useRef(false)
|
||||
|
||||
const items = useMemo(() => {
|
||||
const list: QueueListItem[] = []
|
||||
if (queueHistorySongIds.length > 0) {
|
||||
list.push({ type: "history-header", key: "history-header" })
|
||||
queueHistorySongIds.forEach((songId, historyIndex) =>
|
||||
list.push({
|
||||
type: "history",
|
||||
key: `history:${historyIndex}:${songId}`,
|
||||
songId,
|
||||
historyIndex,
|
||||
})
|
||||
)
|
||||
}
|
||||
list.push({ type: "current", key: "current" })
|
||||
const hasUpcoming = queueSongIds.length > 1
|
||||
list.push({ type: "controls", key: "controls", showTitle: hasUpcoming })
|
||||
const occurrences = new Map<string, number>()
|
||||
queueSongIds.forEach((songId, queueIndex) => {
|
||||
const occurrence = occurrences.get(songId) ?? 0
|
||||
occurrences.set(songId, occurrence + 1)
|
||||
if (queueIndex === 0) return
|
||||
list.push({
|
||||
type: "upcoming",
|
||||
key: `${songId}:${occurrence}`,
|
||||
songId,
|
||||
queueIndex,
|
||||
})
|
||||
})
|
||||
if (!hasUpcoming) {
|
||||
// Fills the rest of the page so the message sits in its middle.
|
||||
list.push({
|
||||
type: "empty",
|
||||
key: "empty",
|
||||
height: Math.max(
|
||||
ROW_HEIGHT * 2,
|
||||
viewportHeight - CURRENT_HEIGHT - TOGGLES_ONLY_HEIGHT
|
||||
),
|
||||
})
|
||||
}
|
||||
return list
|
||||
}, [queueHistorySongIds, queueSongIds, viewportHeight])
|
||||
|
||||
const offsets = useMemo(() => {
|
||||
const result: number[] = []
|
||||
let offset = 0
|
||||
for (const item of items) {
|
||||
result.push(offset)
|
||||
offset += itemHeight(item)
|
||||
}
|
||||
return result
|
||||
}, [items])
|
||||
|
||||
const currentIndex = items.findIndex((item) => item.type === "current")
|
||||
const controlsIndex = currentIndex + 1
|
||||
const belowCurrentHeight = items
|
||||
.slice(currentIndex)
|
||||
.reduce((sum, item) => sum + itemHeight(item), 0)
|
||||
// Lets the current song scroll to the top even when little is queued.
|
||||
const footerHeight = Math.max(
|
||||
BOTTOM_FADE_HEIGHT,
|
||||
viewportHeight - belowCurrentHeight
|
||||
)
|
||||
|
||||
// Keep the current song at the top as playback moves through the queue.
|
||||
const currentSongId = queueSongIds[0]
|
||||
const currentOffset = offsets[currentIndex] ?? 0
|
||||
const scrolledSongId = useRef(currentSongId)
|
||||
useEffect(() => {
|
||||
if (scrolledSongId.current === currentSongId) return
|
||||
scrolledSongId.current = currentSongId
|
||||
listRef.current?.scrollToOffset({ offset: currentOffset, animated: true })
|
||||
}, [currentOffset, currentSongId])
|
||||
|
||||
const getItemLayout = useCallback(
|
||||
(data: ArrayLike<QueueListItem> | null | undefined, index: number) => ({
|
||||
length: data ? itemHeight(data[index]) : ROW_HEIGHT,
|
||||
offset: offsets[index] ?? 0,
|
||||
index,
|
||||
}),
|
||||
[offsets]
|
||||
)
|
||||
|
||||
const resetDrag = useCallback(() => {
|
||||
drag.from.value = -1
|
||||
drag.to.value = -1
|
||||
drag.y.value = 0
|
||||
drag.dropping.value = false
|
||||
}, [drag])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!resetDragOnCommit.current) return
|
||||
resetDragOnCommit.current = false
|
||||
resetDrag()
|
||||
}, [queueSongIds, resetDrag])
|
||||
|
||||
const handleDragStart = useCallback(() => {
|
||||
setScrollEnabled(false)
|
||||
swipeGroup.closeOpenRow()
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium)
|
||||
}, [swipeGroup])
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(songId: Id<"songs">, from: number, to: number) => {
|
||||
setScrollEnabled(true)
|
||||
const queue = queueRef.current
|
||||
if (
|
||||
from === to ||
|
||||
queue[from] !== songId ||
|
||||
to < 1 ||
|
||||
to >= queue.length
|
||||
) {
|
||||
resetDrag()
|
||||
return
|
||||
}
|
||||
const next = [...queue]
|
||||
const [moved] = next.splice(from, 1)
|
||||
next.splice(to, 0, moved)
|
||||
resetDragOnCommit.current = true
|
||||
void reorderQueue(next)
|
||||
},
|
||||
[reorderQueue, resetDrag]
|
||||
)
|
||||
|
||||
const handleRemove = useCallback(
|
||||
async (queueIndex: number) => {
|
||||
const queue = queueRef.current
|
||||
if (queueIndex < 1 || queueIndex >= queue.length) return false
|
||||
await reorderQueue(queue.filter((_, index) => index !== queueIndex))
|
||||
return true
|
||||
},
|
||||
[reorderQueue]
|
||||
)
|
||||
|
||||
const CellRenderer = useMemo(
|
||||
() =>
|
||||
function QueueCell({
|
||||
item,
|
||||
style,
|
||||
children,
|
||||
onLayout,
|
||||
}: CellRendererProps<QueueListItem>) {
|
||||
const queueIndex = item.type === "upcoming" ? item.queueIndex : -1
|
||||
const lift = useAnimatedStyle(() => ({
|
||||
zIndex:
|
||||
queueIndex > 0 && drag.from.value === queueIndex
|
||||
? DRAG_HIGHLIGHT_Z_INDEX
|
||||
: 0,
|
||||
}))
|
||||
return (
|
||||
<Animated.View style={[style, lift]} onLayout={onLayout}>
|
||||
{children}
|
||||
</Animated.View>
|
||||
)
|
||||
},
|
||||
[drag]
|
||||
)
|
||||
|
||||
const renderItem = ({ item }: { item: QueueListItem }) => {
|
||||
switch (item.type) {
|
||||
case "history-header":
|
||||
return (
|
||||
<View style={styles.historyHeader}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
|
||||
History
|
||||
</Text>
|
||||
<Pressable onPress={() => void clearHistory()} hitSlop={10}>
|
||||
<Text
|
||||
style={[styles.clear, { color: colors.secondaryForeground }]}
|
||||
>
|
||||
Clear
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
)
|
||||
case "history":
|
||||
return (
|
||||
<HistoryRow
|
||||
songId={item.songId}
|
||||
historyIndex={item.historyIndex}
|
||||
colors={colors}
|
||||
onPress={skipToHistoryIndex}
|
||||
/>
|
||||
)
|
||||
case "current":
|
||||
return <View style={styles.current}>{currentHeader}</View>
|
||||
case "controls":
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
styles.controls,
|
||||
{
|
||||
height: item.showTitle ? CONTROLS_HEIGHT : TOGGLES_ONLY_HEIGHT,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<View style={styles.toggles}>
|
||||
<QueueToggle
|
||||
colors={colors}
|
||||
selected={shuffleEnabled}
|
||||
label="Shuffle"
|
||||
symbol="shuffle"
|
||||
fallback="shuffle"
|
||||
onPress={toggleShuffle}
|
||||
/>
|
||||
<QueueToggle
|
||||
colors={colors}
|
||||
selected={repeatEnabled !== "none"}
|
||||
label={repeatEnabled === "once" ? "Repeat one" : "Repeat"}
|
||||
symbol={repeatEnabled === "once" ? "repeat.1" : "repeat"}
|
||||
fallback="repeat"
|
||||
onPress={cycleRepeat}
|
||||
/>
|
||||
</View>
|
||||
{item.showTitle ? (
|
||||
<Text style={[styles.sectionTitle, { color: colors.foreground }]}>
|
||||
Continue Playing
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
case "upcoming":
|
||||
return (
|
||||
<UpcomingRow
|
||||
songId={item.songId}
|
||||
queueIndex={item.queueIndex}
|
||||
lastIndex={queueSongIds.length - 1}
|
||||
colors={colors}
|
||||
drag={drag}
|
||||
swipeGroup={swipeGroup}
|
||||
onPress={skipToQueueIndex}
|
||||
onRemove={handleRemove}
|
||||
onDragStart={handleDragStart}
|
||||
onDrop={handleDrop}
|
||||
/>
|
||||
)
|
||||
case "empty":
|
||||
return (
|
||||
<View style={[styles.empty, { height: item.height }]}>
|
||||
<Text
|
||||
style={[styles.emptyText, { color: colors.secondaryForeground }]}
|
||||
>
|
||||
Nothing else is queued.
|
||||
</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.root}>
|
||||
<FlatList
|
||||
ref={listRef}
|
||||
data={items}
|
||||
keyExtractor={(item) => item.key}
|
||||
renderItem={renderItem}
|
||||
getItemLayout={getItemLayout}
|
||||
CellRendererComponent={CellRenderer}
|
||||
initialScrollIndex={currentIndex}
|
||||
stickyHeaderIndices={[controlsIndex]}
|
||||
scrollEnabled={scrollEnabled}
|
||||
onScrollBeginDrag={swipeGroup.closeOpenRow}
|
||||
showsVerticalScrollIndicator={false}
|
||||
initialNumToRender={16}
|
||||
maxToRenderPerBatch={10}
|
||||
windowSize={9}
|
||||
ListFooterComponent={<View style={{ height: footerHeight }} />}
|
||||
/>
|
||||
<Svg
|
||||
pointerEvents="none"
|
||||
style={styles.bottomFade}
|
||||
width="100%"
|
||||
height={BOTTOM_FADE_HEIGHT}
|
||||
>
|
||||
<Defs>
|
||||
<LinearGradient id="queue-fade" x1="0" y1="0" x2="0" y2="1">
|
||||
<Stop offset="0" stopColor={colors.background} stopOpacity={0} />
|
||||
<Stop offset="1" stopColor={colors.background} stopOpacity={1} />
|
||||
</LinearGradient>
|
||||
</Defs>
|
||||
<Rect width="100%" height="100%" fill="url(#queue-fade)" />
|
||||
</Svg>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function QueueToggle({
|
||||
colors,
|
||||
selected,
|
||||
label,
|
||||
symbol,
|
||||
fallback,
|
||||
onPress,
|
||||
}: {
|
||||
colors: NowPlayingColors
|
||||
selected: boolean
|
||||
label: string
|
||||
symbol: "shuffle" | "repeat" | "repeat.1"
|
||||
fallback: "shuffle" | "repeat"
|
||||
onPress: () => Promise<void>
|
||||
}) {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="switch"
|
||||
accessibilityLabel={label}
|
||||
accessibilityState={{ checked: selected }}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync()
|
||||
void onPress()
|
||||
}}
|
||||
style={({ pressed }) => [
|
||||
styles.toggle,
|
||||
{
|
||||
backgroundColor: selected ? colors.selected : colors.control,
|
||||
opacity: pressed ? 0.7 : 1,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<PlayerSymbol
|
||||
name={symbol}
|
||||
fallback={fallback}
|
||||
size={24}
|
||||
weight="semibold"
|
||||
color={selected ? colors.selectedForeground : colors.foreground}
|
||||
/>
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
|
||||
function QueueSongContent({
|
||||
songId,
|
||||
colors,
|
||||
trailing,
|
||||
}: {
|
||||
songId: Id<"songs">
|
||||
colors: NowPlayingColors
|
||||
trailing?: ReactNode
|
||||
}) {
|
||||
const { config } = useServerConfig()
|
||||
const song = useSong(songId)
|
||||
|
||||
return (
|
||||
<View style={styles.row}>
|
||||
<CoverImage
|
||||
uri={
|
||||
song && config ? albumCoverUrl(config.serverUrl, song.album.id) : ""
|
||||
}
|
||||
hasCover={song ? song.album.cover != null : false}
|
||||
style={styles.rowArtwork}
|
||||
/>
|
||||
<View style={styles.rowMeta}>
|
||||
<Text
|
||||
style={[styles.rowTitle, { color: colors.foreground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{song?.title ?? " "}
|
||||
</Text>
|
||||
<Text
|
||||
style={[styles.rowSubtitle, { color: colors.secondaryForeground }]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{song?.artist.name ?? " "}
|
||||
</Text>
|
||||
</View>
|
||||
{trailing}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A row tap that takes part in gesture arbitration, so swiping the row or
|
||||
* dragging its handle cancels it. A `Pressable` would still fire, since the row
|
||||
* moves with the finger.
|
||||
*/
|
||||
function RowTap({
|
||||
colors,
|
||||
onPress,
|
||||
children,
|
||||
}: {
|
||||
colors: NowPlayingColors
|
||||
onPress: () => void
|
||||
children: ReactNode
|
||||
}) {
|
||||
const pressed = useSharedValue(0)
|
||||
const tap = useMemo(
|
||||
() =>
|
||||
Gesture.Tap()
|
||||
.maxDistance(10)
|
||||
.onBegin(() => {
|
||||
pressed.value = withDelay(
|
||||
TAP_HIGHLIGHT_DELAY_MS,
|
||||
withTiming(1, { duration: 0 })
|
||||
)
|
||||
})
|
||||
.onEnd((_event, success) => {
|
||||
if (success) scheduleOnRN(onPress)
|
||||
})
|
||||
.onFinalize(() => {
|
||||
pressed.value = withTiming(0, { duration: 150 })
|
||||
}),
|
||||
[onPress, pressed]
|
||||
)
|
||||
const highlightStyle = useAnimatedStyle(() => ({ opacity: pressed.value }))
|
||||
|
||||
return (
|
||||
<GestureDetector gesture={tap}>
|
||||
<View accessible accessibilityRole="button" onAccessibilityTap={onPress}>
|
||||
{children}
|
||||
<Animated.View
|
||||
pointerEvents="none"
|
||||
style={[
|
||||
StyleSheet.absoluteFill,
|
||||
{ backgroundColor: colors.highlight },
|
||||
highlightStyle,
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
</GestureDetector>
|
||||
)
|
||||
}
|
||||
|
||||
const HistoryRow = memo(function HistoryRow({
|
||||
songId,
|
||||
historyIndex,
|
||||
colors,
|
||||
onPress,
|
||||
}: {
|
||||
songId: Id<"songs">
|
||||
historyIndex: number
|
||||
colors: NowPlayingColors
|
||||
onPress: (historyIndex: number) => Promise<void>
|
||||
}) {
|
||||
const handlePress = useCallback(
|
||||
() => void onPress(historyIndex),
|
||||
[historyIndex, onPress]
|
||||
)
|
||||
return (
|
||||
<RowTap colors={colors} onPress={handlePress}>
|
||||
<QueueSongContent songId={songId} colors={colors} />
|
||||
</RowTap>
|
||||
)
|
||||
})
|
||||
|
||||
const UpcomingRow = memo(function UpcomingRow({
|
||||
songId,
|
||||
queueIndex,
|
||||
lastIndex,
|
||||
colors,
|
||||
drag,
|
||||
swipeGroup,
|
||||
onPress,
|
||||
onRemove,
|
||||
onDragStart,
|
||||
onDrop,
|
||||
}: {
|
||||
songId: Id<"songs">
|
||||
queueIndex: number
|
||||
lastIndex: number
|
||||
colors: NowPlayingColors
|
||||
drag: DragState
|
||||
swipeGroup: SwipeRowGroup
|
||||
onPress: (queueIndex: number) => Promise<void>
|
||||
onRemove: (queueIndex: number) => Promise<boolean>
|
||||
onDragStart: () => void
|
||||
onDrop: (songId: Id<"songs">, from: number, to: number) => void
|
||||
}) {
|
||||
const handlePan = useMemo(() => {
|
||||
const tick = () => void Haptics.selectionAsync()
|
||||
return Gesture.Pan()
|
||||
.minDistance(0)
|
||||
.shouldCancelWhenOutside(false)
|
||||
.onStart(() => {
|
||||
if (drag.dropping.value) return
|
||||
drag.from.value = queueIndex
|
||||
drag.to.value = queueIndex
|
||||
drag.y.value = 0
|
||||
scheduleOnRN(onDragStart)
|
||||
})
|
||||
.onUpdate((event) => {
|
||||
if (drag.from.value !== queueIndex || drag.dropping.value) return
|
||||
drag.y.value = event.translationY
|
||||
const to = Math.min(
|
||||
lastIndex,
|
||||
Math.max(1, Math.round(queueIndex + event.translationY / ROW_HEIGHT))
|
||||
)
|
||||
if (to !== drag.to.value) {
|
||||
drag.to.value = to
|
||||
scheduleOnRN(tick)
|
||||
}
|
||||
})
|
||||
.onFinalize(() => {
|
||||
if (drag.from.value !== queueIndex || drag.dropping.value) return
|
||||
drag.dropping.value = true
|
||||
const to = drag.to.value
|
||||
drag.y.value = withTiming(
|
||||
(to - queueIndex) * ROW_HEIGHT,
|
||||
DRAG_SETTLE,
|
||||
() => scheduleOnRN(onDrop, songId, queueIndex, to)
|
||||
)
|
||||
})
|
||||
}, [drag, lastIndex, onDragStart, onDrop, queueIndex, songId])
|
||||
|
||||
const shiftStyle = useAnimatedStyle(() => {
|
||||
const from = drag.from.value
|
||||
if (from < 0) return { transform: [{ translateY: 0 }] }
|
||||
if (from === queueIndex) {
|
||||
return { transform: [{ translateY: drag.y.value }] }
|
||||
}
|
||||
const to = drag.to.value
|
||||
let shift = 0
|
||||
if (from < to && queueIndex > from && queueIndex <= to) shift = -ROW_HEIGHT
|
||||
if (from > to && queueIndex < from && queueIndex >= to) shift = ROW_HEIGHT
|
||||
return { transform: [{ translateY: withTiming(shift, DRAG_SETTLE) }] }
|
||||
})
|
||||
|
||||
const liftStyle = useAnimatedStyle(() => ({
|
||||
opacity: withTiming(drag.from.value === queueIndex ? 1 : 0, DRAG_SETTLE),
|
||||
}))
|
||||
|
||||
const handleRemove = useCallback(
|
||||
() => onRemove(queueIndex),
|
||||
[onRemove, queueIndex]
|
||||
)
|
||||
|
||||
const handlePress = useCallback(
|
||||
() => void onPress(queueIndex),
|
||||
[onPress, queueIndex]
|
||||
)
|
||||
|
||||
const content = (
|
||||
<RowTap colors={colors} onPress={handlePress}>
|
||||
<QueueSongContent
|
||||
songId={songId}
|
||||
colors={colors}
|
||||
trailing={
|
||||
<GestureDetector gesture={handlePan}>
|
||||
<View
|
||||
style={styles.handle}
|
||||
accessibilityLabel="Reorder"
|
||||
accessibilityHint="Drag to move this song in the queue"
|
||||
>
|
||||
<PlayerSymbol
|
||||
name="line.3.horizontal"
|
||||
fallback="reorder-three"
|
||||
size={20}
|
||||
color={colors.secondaryForeground}
|
||||
/>
|
||||
</View>
|
||||
</GestureDetector>
|
||||
}
|
||||
/>
|
||||
<Animated.View
|
||||
pointerEvents="none"
|
||||
style={[
|
||||
StyleSheet.absoluteFill,
|
||||
{ backgroundColor: colors.highlight },
|
||||
liftStyle,
|
||||
]}
|
||||
/>
|
||||
</RowTap>
|
||||
)
|
||||
|
||||
return (
|
||||
<Animated.View style={shiftStyle}>
|
||||
{Platform.OS === "ios" ? (
|
||||
<SwipeToRemoveRow
|
||||
group={swipeGroup}
|
||||
backgroundColor={colors.background}
|
||||
actionAccessibilityLabel="Remove from queue"
|
||||
onRemove={handleRemove}
|
||||
>
|
||||
{content}
|
||||
</SwipeToRemoveRow>
|
||||
) : (
|
||||
<View style={{ backgroundColor: colors.background }}>{content}</View>
|
||||
)}
|
||||
</Animated.View>
|
||||
)
|
||||
})
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
root: {
|
||||
flex: 1,
|
||||
},
|
||||
historyHeader: {
|
||||
height: HISTORY_HEADER_HEIGHT,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
paddingHorizontal: QUEUE_HORIZONTAL_INSET,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: 17,
|
||||
fontWeight: "700",
|
||||
},
|
||||
clear: {
|
||||
fontSize: 17,
|
||||
},
|
||||
current: {
|
||||
height: CURRENT_HEIGHT,
|
||||
justifyContent: "center",
|
||||
paddingHorizontal: QUEUE_HORIZONTAL_INSET,
|
||||
},
|
||||
controls: {
|
||||
justifyContent: "center",
|
||||
gap: 18,
|
||||
paddingHorizontal: QUEUE_HORIZONTAL_INSET,
|
||||
},
|
||||
toggles: {
|
||||
flexDirection: "row",
|
||||
gap: 12,
|
||||
},
|
||||
toggle: {
|
||||
flex: 1,
|
||||
height: 36,
|
||||
borderRadius: 18,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
row: {
|
||||
height: ROW_HEIGHT,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 14,
|
||||
paddingLeft: QUEUE_HORIZONTAL_INSET,
|
||||
paddingRight: QUEUE_HORIZONTAL_INSET - 10,
|
||||
},
|
||||
rowArtwork: {
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: 6,
|
||||
},
|
||||
rowMeta: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
rowTitle: {
|
||||
fontSize: 16,
|
||||
},
|
||||
rowSubtitle: {
|
||||
fontSize: 14,
|
||||
marginTop: 2,
|
||||
},
|
||||
handle: {
|
||||
width: 44,
|
||||
height: ROW_HEIGHT,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
empty: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
paddingHorizontal: QUEUE_HORIZONTAL_INSET,
|
||||
},
|
||||
emptyText: {
|
||||
fontSize: 20,
|
||||
fontWeight: "600",
|
||||
textAlign: "center",
|
||||
},
|
||||
bottomFade: {
|
||||
position: "absolute",
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,185 @@
|
||||
import { useEffect, useMemo, useRef, type ReactNode } from "react"
|
||||
import { StyleSheet, View } from "react-native"
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler"
|
||||
import Animated, {
|
||||
interpolate,
|
||||
interpolateColor,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withSpring,
|
||||
withTiming,
|
||||
} from "react-native-reanimated"
|
||||
import { scheduleOnRN } from "react-native-worklets"
|
||||
|
||||
const IDLE_HEIGHT = 7
|
||||
const ACTIVE_HEIGHT = 13
|
||||
const TOUCH_HEIGHT = 36
|
||||
const ACTIVE_STRETCH = 1.03
|
||||
// Playback position lags a seek; hold the committed value until it catches up.
|
||||
const COMMIT_HOLD_MS = 800
|
||||
|
||||
/**
|
||||
* A thumbless bar that thickens while touched. Drags move the value relative to
|
||||
* where the finger started rather than jumping to the touch point.
|
||||
*/
|
||||
export function PlayerSlider({
|
||||
value,
|
||||
maximumValue,
|
||||
fillColor,
|
||||
activeFillColor,
|
||||
trackColor,
|
||||
onValueChange,
|
||||
onSlidingStart,
|
||||
onSlidingComplete,
|
||||
leading,
|
||||
trailing,
|
||||
accessibilityLabel,
|
||||
}: {
|
||||
value: number
|
||||
maximumValue: number
|
||||
fillColor: string
|
||||
activeFillColor: string
|
||||
trackColor: string
|
||||
onValueChange?: (value: number) => void
|
||||
onSlidingStart?: () => void
|
||||
onSlidingComplete?: (value: number) => void
|
||||
leading?: ReactNode
|
||||
trailing?: ReactNode
|
||||
accessibilityLabel: string
|
||||
}) {
|
||||
const max = maximumValue > 0 ? maximumValue : 1
|
||||
const fraction = useSharedValue(clamp(value / max))
|
||||
const startFraction = useSharedValue(0)
|
||||
const width = useSharedValue(0)
|
||||
const active = useSharedValue(0)
|
||||
const dragging = useSharedValue(false)
|
||||
const holdUntil = useRef(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (dragging.value || Date.now() < holdUntil.current) return
|
||||
fraction.value = clamp(value / max)
|
||||
}, [dragging, fraction, max, value])
|
||||
|
||||
const callbacks = useRef({
|
||||
onValueChange,
|
||||
onSlidingStart,
|
||||
onSlidingComplete,
|
||||
max,
|
||||
})
|
||||
callbacks.current = { onValueChange, onSlidingStart, onSlidingComplete, max }
|
||||
|
||||
const gesture = useMemo(() => {
|
||||
const start = () => callbacks.current.onSlidingStart?.()
|
||||
const change = (next: number) =>
|
||||
callbacks.current.onValueChange?.(next * callbacks.current.max)
|
||||
const complete = (next: number) => {
|
||||
holdUntil.current = Date.now() + COMMIT_HOLD_MS
|
||||
callbacks.current.onSlidingComplete?.(next * callbacks.current.max)
|
||||
}
|
||||
|
||||
return Gesture.Pan()
|
||||
.activeOffsetX([-2, 2])
|
||||
.failOffsetY([-24, 24])
|
||||
.shouldCancelWhenOutside(false)
|
||||
.onBegin(() => {
|
||||
active.value = withSpring(1, { duration: 250, dampingRatio: 0.8 })
|
||||
})
|
||||
.onStart(() => {
|
||||
dragging.value = true
|
||||
startFraction.value = fraction.value
|
||||
scheduleOnRN(start)
|
||||
})
|
||||
.onUpdate((event) => {
|
||||
if (width.value <= 0) return
|
||||
const next = Math.min(
|
||||
1,
|
||||
Math.max(0, startFraction.value + event.translationX / width.value)
|
||||
)
|
||||
fraction.value = next
|
||||
scheduleOnRN(change, next)
|
||||
})
|
||||
.onEnd(() => {
|
||||
scheduleOnRN(complete, fraction.value)
|
||||
})
|
||||
.onFinalize(() => {
|
||||
dragging.value = false
|
||||
active.value = withTiming(0, { duration: 250 })
|
||||
})
|
||||
}, [active, dragging, fraction, startFraction, width])
|
||||
|
||||
const trackStyle = useAnimatedStyle(() => {
|
||||
const height = interpolate(
|
||||
active.value,
|
||||
[0, 1],
|
||||
[IDLE_HEIGHT, ACTIVE_HEIGHT]
|
||||
)
|
||||
return {
|
||||
height,
|
||||
borderRadius: height / 2,
|
||||
transform: [
|
||||
{ scaleX: interpolate(active.value, [0, 1], [1, ACTIVE_STRETCH]) },
|
||||
],
|
||||
}
|
||||
})
|
||||
|
||||
const fillStyle = useAnimatedStyle(() => ({
|
||||
width: `${fraction.value * 100}%`,
|
||||
backgroundColor: interpolateColor(
|
||||
active.value,
|
||||
[0, 1],
|
||||
[fillColor, activeFillColor]
|
||||
),
|
||||
}))
|
||||
|
||||
return (
|
||||
<View style={styles.row}>
|
||||
{leading}
|
||||
<GestureDetector gesture={gesture}>
|
||||
<View
|
||||
style={styles.touchArea}
|
||||
onLayout={(event) => {
|
||||
width.value = event.nativeEvent.layout.width
|
||||
}}
|
||||
accessible
|
||||
accessibilityRole="adjustable"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
accessibilityValue={{
|
||||
min: 0,
|
||||
max: Math.round(max),
|
||||
now: Math.round(value),
|
||||
}}
|
||||
>
|
||||
<Animated.View
|
||||
style={[styles.track, { backgroundColor: trackColor }, trackStyle]}
|
||||
>
|
||||
<Animated.View style={[styles.fill, fillStyle]} />
|
||||
</Animated.View>
|
||||
</View>
|
||||
</GestureDetector>
|
||||
{trailing}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function clamp(fraction: number) {
|
||||
return Number.isFinite(fraction) ? Math.min(1, Math.max(0, fraction)) : 0
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
row: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 10,
|
||||
},
|
||||
touchArea: {
|
||||
flex: 1,
|
||||
height: TOUCH_HEIGHT,
|
||||
justifyContent: "center",
|
||||
},
|
||||
track: {
|
||||
overflow: "hidden",
|
||||
},
|
||||
fill: {
|
||||
height: "100%",
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Ionicons, MaterialIcons } from "@expo/vector-icons"
|
||||
import { SymbolView, type SFSymbol } from "expo-symbols"
|
||||
import { Platform } from "react-native"
|
||||
|
||||
type Fallback =
|
||||
| keyof typeof Ionicons.glyphMap
|
||||
| { material: keyof typeof MaterialIcons.glyphMap }
|
||||
|
||||
/** An SF Symbol on iOS, or the closest Ionicon or Material icon elsewhere. */
|
||||
export function PlayerSymbol({
|
||||
name,
|
||||
fallback,
|
||||
size,
|
||||
color,
|
||||
weight = "regular",
|
||||
}: {
|
||||
name: SFSymbol
|
||||
fallback: Fallback
|
||||
size: number
|
||||
color: string
|
||||
weight?: "regular" | "medium" | "semibold" | "bold"
|
||||
}) {
|
||||
if (Platform.OS === "ios") {
|
||||
return (
|
||||
<SymbolView name={name} size={size} tintColor={color} weight={weight} />
|
||||
)
|
||||
}
|
||||
if (typeof fallback === "object") {
|
||||
return <MaterialIcons name={fallback.material} size={size} color={color} />
|
||||
}
|
||||
return <Ionicons name={fallback} size={size} color={color} />
|
||||
}
|
||||
@@ -1,26 +1,27 @@
|
||||
import { collectionInset } from "@/components/collection-list"
|
||||
import { CoverImage } from "@/components/cover-image"
|
||||
import { useServerConfig } from "@/contexts/server-config"
|
||||
import type { BrowseSong } from "@otunes/convex/types"
|
||||
import type { CoverPalette } from "@/lib/cover-palette"
|
||||
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,
|
||||
trailing,
|
||||
palette,
|
||||
inset = false,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
onPress?: () => void
|
||||
@@ -28,14 +29,41 @@ export function SongRow({
|
||||
onAction: MediaMenuConfig["onAction"]
|
||||
}
|
||||
trailing?: React.ReactNode
|
||||
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
|
||||
/** Album/playlist layout: the divider starts at the title, not the artwork. */
|
||||
inset?: boolean
|
||||
}) {
|
||||
const { config } = useServerConfig()
|
||||
const colors = useThemeColors()
|
||||
if (!config) return null
|
||||
|
||||
const foreground = palette?.foreground ?? colors.foreground
|
||||
const secondaryForeground =
|
||||
palette?.secondaryForeground ?? colors.mutedForeground
|
||||
const divider = palette?.divider ?? colors.border
|
||||
|
||||
const content = (
|
||||
<>
|
||||
<View style={styles.rowMeta}>
|
||||
<Text style={[styles.rowTitle, { color: foreground }]} numberOfLines={1}>
|
||||
{song.title}
|
||||
</Text>
|
||||
<Text style={[styles.rowSubtitle, { color: secondaryForeground }]} numberOfLines={1}>
|
||||
{song.artist.name} · {song.album.title}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={[styles.duration, { color: secondaryForeground }]}>
|
||||
{formatDuration(song.durationSeconds)}
|
||||
</Text>
|
||||
{trailing}
|
||||
</>
|
||||
)
|
||||
|
||||
const row = (
|
||||
<Pressable
|
||||
style={[styles.row, { borderBottomColor: colors.border }]}
|
||||
style={
|
||||
inset ? styles.insetRow : [styles.row, { borderBottomColor: divider }]
|
||||
}
|
||||
onPress={onPress}
|
||||
>
|
||||
<CoverImage
|
||||
@@ -43,18 +71,13 @@ export function SongRow({
|
||||
hasCover={song.album.cover != null}
|
||||
style={styles.rowArtwork}
|
||||
/>
|
||||
<View style={styles.rowMeta}>
|
||||
<Text style={[styles.rowTitle, { color: colors.foreground }]} numberOfLines={1}>
|
||||
{song.title}
|
||||
</Text>
|
||||
<Text style={[styles.rowSubtitle, { color: colors.mutedForeground }]} numberOfLines={1}>
|
||||
{song.artist.name} · {song.album.title}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={[styles.duration, { color: colors.mutedForeground }]}>
|
||||
{formatDuration(song.durationSeconds)}
|
||||
</Text>
|
||||
{trailing}
|
||||
{inset ? (
|
||||
<View style={[styles.insetContent, { borderBottomColor: divider }]}>
|
||||
{content}
|
||||
</View>
|
||||
) : (
|
||||
content
|
||||
)}
|
||||
</Pressable>
|
||||
)
|
||||
|
||||
@@ -67,7 +90,55 @@ 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,
|
||||
palette,
|
||||
inset,
|
||||
onPlay,
|
||||
onAction,
|
||||
}: {
|
||||
song: BrowseSong
|
||||
favorited: boolean
|
||||
playlistLabel?: string
|
||||
palette?: Pick<CoverPalette, "foreground" | "secondaryForeground" | "divider">
|
||||
inset?: boolean
|
||||
onPlay: (song: BrowseSong) => void
|
||||
onAction: (song: BrowseSong, action: MediaAction) => void
|
||||
}) {
|
||||
const handlePress = useCallback(() => onPlay(song), [onPlay, song])
|
||||
|
||||
return (
|
||||
<SongRow
|
||||
song={song}
|
||||
palette={palette}
|
||||
inset={inset}
|
||||
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
|
||||
@@ -82,6 +153,24 @@ const styles = StyleSheet.create({
|
||||
paddingHorizontal: spacing.lg,
|
||||
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
insetRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: spacing.md,
|
||||
paddingLeft: collectionInset,
|
||||
},
|
||||
insetContent: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
alignSelf: "stretch",
|
||||
gap: spacing.md,
|
||||
minHeight: 64,
|
||||
paddingVertical: 10,
|
||||
marginRight: collectionInset,
|
||||
borderBottomWidth: StyleSheet.hairlineWidth,
|
||||
},
|
||||
rowArtwork: {
|
||||
width: 44,
|
||||
height: 44,
|
||||
|
||||
@@ -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}>
|
||||
|
||||
@@ -20,6 +20,8 @@ type ButtonProps = Omit<PressableProps, "style"> & {
|
||||
loading?: boolean
|
||||
icon?: React.ComponentProps<typeof Ionicons>["name"]
|
||||
style?: StyleProp<ViewStyle>
|
||||
/** Overrides the variant's colors, e.g. on screens tinted by cover art. */
|
||||
tint?: { background: string; foreground: string }
|
||||
}
|
||||
|
||||
export function Button({
|
||||
@@ -29,13 +31,15 @@ export function Button({
|
||||
disabled,
|
||||
icon,
|
||||
style,
|
||||
tint,
|
||||
...props
|
||||
}: ButtonProps) {
|
||||
const colors = useThemeColors()
|
||||
const isDisabled = disabled || loading
|
||||
|
||||
const backgroundColor =
|
||||
variant === "primary"
|
||||
const backgroundColor = tint
|
||||
? tint.background
|
||||
: variant === "primary"
|
||||
? colors.primary
|
||||
: variant === "secondary"
|
||||
? colors.muted
|
||||
@@ -43,8 +47,9 @@ export function Button({
|
||||
? colors.destructive
|
||||
: "transparent"
|
||||
|
||||
const textColor =
|
||||
variant === "primary"
|
||||
const textColor = tint
|
||||
? tint.foreground
|
||||
: variant === "primary"
|
||||
? colors.primaryForeground
|
||||
: variant === "destructive"
|
||||
? "#fff"
|
||||
|
||||
+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(
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
updatePlaylistLockScreenMetadata,
|
||||
} from "@/lib/audio-playlist-lock-screen"
|
||||
import {
|
||||
nativePlaylistEdits,
|
||||
nativePlaylistNeedsRebuild,
|
||||
nativePlaylistSongIds,
|
||||
repeatToPlaylistLoop,
|
||||
@@ -113,8 +114,10 @@ type PlaybackContextValue = {
|
||||
toggleShuffle: () => Promise<void>
|
||||
cycleRepeat: () => Promise<void>
|
||||
clearQueue: () => Promise<void>
|
||||
clearHistory: () => Promise<void>
|
||||
reorderQueue: (songIds: Id<"songs">[]) => Promise<void>
|
||||
skipToQueueIndex: (index: number) => Promise<void>
|
||||
skipToHistoryIndex: (index: number) => Promise<void>
|
||||
skipNext: () => Promise<void>
|
||||
skipPrevious: () => Promise<void>
|
||||
}
|
||||
@@ -137,8 +140,10 @@ type PlaybackActionsValue = Pick<
|
||||
| "toggleShuffle"
|
||||
| "cycleRepeat"
|
||||
| "clearQueue"
|
||||
| "clearHistory"
|
||||
| "reorderQueue"
|
||||
| "skipToQueueIndex"
|
||||
| "skipToHistoryIndex"
|
||||
| "skipNext"
|
||||
| "skipPrevious"
|
||||
>
|
||||
@@ -243,6 +248,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const prevIsPlayingRef = useRef(false)
|
||||
const currentTimeRef = useRef(0)
|
||||
const pendingSeekRef = useRef<number | null>(null)
|
||||
const seekInFlightRef = useRef(false)
|
||||
const loadRequestIdRef = useRef(0)
|
||||
const playRequestRef = useRef(0)
|
||||
const volumeRef = useRef(DEFAULT_VOLUME)
|
||||
@@ -340,8 +346,6 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
return
|
||||
}
|
||||
|
||||
currentTimeRef.current = status.currentTime
|
||||
setCurrentTime(status.currentTime)
|
||||
if (status.duration > 0) {
|
||||
setDuration(status.duration)
|
||||
}
|
||||
@@ -349,9 +353,19 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
if (pendingSeekRef.current !== null && pendingSeekRef.current > 0) {
|
||||
const seekSeconds = pendingSeekRef.current
|
||||
pendingSeekRef.current = null
|
||||
void playlistRef.current?.seekTo(seekSeconds)
|
||||
const playlist = playlistRef.current
|
||||
if (playlist) {
|
||||
// Statuses report the old position until the seek lands.
|
||||
seekInFlightRef.current = true
|
||||
void playlist.seekTo(seekSeconds).finally(() => {
|
||||
seekInFlightRef.current = false
|
||||
})
|
||||
}
|
||||
currentTimeRef.current = seekSeconds
|
||||
setCurrentTime(seekSeconds)
|
||||
} else if (!seekInFlightRef.current) {
|
||||
currentTimeRef.current = status.currentTime
|
||||
setCurrentTime(status.currentTime)
|
||||
}
|
||||
|
||||
if (status.playing) {
|
||||
@@ -399,13 +413,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
const handleTrackChanged = useCallback(
|
||||
(data: { currentIndex: number; previousIndex: number }) => {
|
||||
if (ignoreTrackChangeRef.current) return
|
||||
if (data.currentIndex === data.previousIndex) return
|
||||
// The window is history then queue, so the current track sits at
|
||||
// `history.length`. Android's `previousIndex` goes stale when tracks
|
||||
// are inserted or removed before it.
|
||||
const steps =
|
||||
data.currentIndex - storeRef.current.getState().history.length
|
||||
if (steps === 0) return
|
||||
|
||||
autoPlayNextRef.current = true
|
||||
isPlayingRef.current = true
|
||||
setIsPlayingState(true)
|
||||
|
||||
const steps = data.currentIndex - data.previousIndex
|
||||
storeRef.current.update((state) => {
|
||||
if (steps === 1) return playbackQueue.skipNext(state)
|
||||
if (steps > 1) return playbackQueue.skipToQueueIndex(state, steps)
|
||||
@@ -682,33 +700,89 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
return
|
||||
}
|
||||
|
||||
const songs = await loadPlaybackSongs(convex, cacheScope, windowSongIds)
|
||||
if (!isCurrentLoad()) return
|
||||
const buildSources = async (songIds: Id<"songs">[]) => {
|
||||
const songs = await loadPlaybackSongs(convex, cacheScope, songIds)
|
||||
const sources = new Map<Id<"songs">, AudioSource>()
|
||||
for (const song of songs) {
|
||||
if (!song) return null
|
||||
const plan = playbackStreamPlan(
|
||||
song.files,
|
||||
user.playbackQuality,
|
||||
user.preferAtmos ?? false
|
||||
)
|
||||
sources.set(
|
||||
song.id,
|
||||
songAudioSource(
|
||||
config.serverUrl,
|
||||
song.id,
|
||||
plan.playbackQuality,
|
||||
plan.preferAtmos,
|
||||
plan.useHls,
|
||||
{ cookieHeader, songTitle: song.title }
|
||||
)
|
||||
)
|
||||
}
|
||||
return sources
|
||||
}
|
||||
|
||||
const sources: AudioSource[] = []
|
||||
for (let i = 0; i < windowSongIds.length; i++) {
|
||||
const song = songs[i]
|
||||
if (!song) {
|
||||
// Queue and history edits around the playing track are applied in place
|
||||
// so playback isn't interrupted.
|
||||
const loadedPlaylist = playlistRef.current
|
||||
const edits =
|
||||
loadedPlaylist && loadedLoadKeyRef.current === loadKey
|
||||
? nativePlaylistEdits(
|
||||
loadedSongIdsRef.current,
|
||||
loadedPlaylist.currentIndex,
|
||||
windowSongIds,
|
||||
currentIndex
|
||||
)
|
||||
: null
|
||||
if (loadedPlaylist && edits) {
|
||||
const addedSongIds = edits.flatMap((edit) =>
|
||||
edit.type === "remove" ? [] : [edit.songId]
|
||||
)
|
||||
const sources = await buildSources([...new Set(addedSongIds)])
|
||||
if (!isCurrentLoad()) return
|
||||
if (!sources) {
|
||||
handlePlaybackLoadFailure()
|
||||
return
|
||||
}
|
||||
const plan = playbackStreamPlan(
|
||||
song.files,
|
||||
user.playbackQuality,
|
||||
user.preferAtmos ?? false
|
||||
)
|
||||
sources.push(
|
||||
songAudioSource(
|
||||
config.serverUrl,
|
||||
song.id,
|
||||
plan.playbackQuality,
|
||||
plan.preferAtmos,
|
||||
plan.useHls,
|
||||
{ cookieHeader, songTitle: song.title }
|
||||
)
|
||||
)
|
||||
ignoreTrackChangeRef.current = true
|
||||
for (const edit of edits) {
|
||||
if (edit.type === "remove") {
|
||||
loadedPlaylist.remove(edit.index)
|
||||
} else if (edit.type === "insert") {
|
||||
loadedPlaylist.insert(sources.get(edit.songId)!, edit.index)
|
||||
} else {
|
||||
loadedPlaylist.add(sources.get(edit.songId)!)
|
||||
}
|
||||
}
|
||||
loadedSongIdsRef.current = windowSongIds
|
||||
loadedPlaylist.loop = repeatToPlaylistLoop(repeatEnabled)
|
||||
scheduleTrackChangeHandling()
|
||||
if (shouldPlay && !loadedPlaylist.playing) {
|
||||
isPlayingRef.current = true
|
||||
setIsPlayingState(true)
|
||||
loadedPlaylist.play()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const sourcesById = await buildSources(windowSongIds)
|
||||
if (!isCurrentLoad()) return
|
||||
if (!sourcesById) {
|
||||
handlePlaybackLoadFailure()
|
||||
return
|
||||
}
|
||||
const sources = windowSongIds.map((songId) => sourcesById.get(songId)!)
|
||||
|
||||
// Keep the position when only the stream settings changed.
|
||||
const resumeSeconds =
|
||||
loadedPlaylist &&
|
||||
loadedSongIdsRef.current[loadedPlaylist.currentIndex] === currentSongId
|
||||
? currentTimeRef.current
|
||||
: null
|
||||
|
||||
ignoreTrackChangeRef.current = true
|
||||
destroyPlaylist()
|
||||
if (!isCurrentLoad()) {
|
||||
@@ -716,17 +790,22 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
return
|
||||
}
|
||||
|
||||
const playlist = ensurePlaylist(sources)
|
||||
if (resumeSeconds !== null && resumeSeconds > 0) {
|
||||
pendingSeekRef.current = resumeSeconds
|
||||
}
|
||||
// Start at the current track and put history in front of it, so an
|
||||
// earlier song is never loaded first.
|
||||
const playlist = ensurePlaylist(sources.slice(currentIndex))
|
||||
for (let index = 0; index < currentIndex; index++) {
|
||||
playlist.insert(sources[index], index)
|
||||
}
|
||||
loadedSongIdsRef.current = windowSongIds
|
||||
loadedLoadKeyRef.current = loadKey
|
||||
playlist.volume = volumeRef.current
|
||||
playlist.loop = repeatToPlaylistLoop(repeatEnabled)
|
||||
if (currentIndex > 0) {
|
||||
playlist.skipTo(currentIndex)
|
||||
}
|
||||
activatePlaylistLockScreen(
|
||||
playlist,
|
||||
metadata ?? { title: songs[currentIndex]?.title }
|
||||
metadata ?? { title: currentSong?.title }
|
||||
)
|
||||
scheduleTrackChangeHandling()
|
||||
|
||||
@@ -991,6 +1070,10 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
setIsPlaying(false)
|
||||
}, [store, setIsPlaying])
|
||||
|
||||
const clearHistory = useCallback(async () => {
|
||||
store.update(playbackQueue.clearHistory)
|
||||
}, [store])
|
||||
|
||||
const reorderQueue = useCallback(
|
||||
async (songIds: Id<"songs">[]) => {
|
||||
store.update((state) => playbackQueue.reorderQueue(state, songIds))
|
||||
@@ -1007,6 +1090,15 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
[store]
|
||||
)
|
||||
|
||||
const skipToHistoryIndex = useCallback(
|
||||
async (index: number) => {
|
||||
if (index < 0 || index >= store.getState().history.length) return
|
||||
autoPlayNextRef.current = true
|
||||
store.update((state) => playbackQueue.skipToHistoryIndex(state, index))
|
||||
},
|
||||
[store]
|
||||
)
|
||||
|
||||
const skipNext = useCallback(async () => {
|
||||
const before = store.getState()
|
||||
if (before.repeatEnabled === "none" && before.queue.length <= 1) {
|
||||
@@ -1057,14 +1149,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
toggleShuffle,
|
||||
cycleRepeat,
|
||||
clearQueue,
|
||||
clearHistory,
|
||||
reorderQueue,
|
||||
skipToQueueIndex,
|
||||
skipToHistoryIndex,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
}),
|
||||
[
|
||||
addToQueueNext,
|
||||
addToQueueLast,
|
||||
clearHistory,
|
||||
clearQueue,
|
||||
cycleRepeat,
|
||||
playAlbum,
|
||||
@@ -1081,6 +1176,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) {
|
||||
setIsPlaying,
|
||||
skipNext,
|
||||
skipPrevious,
|
||||
skipToHistoryIndex,
|
||||
skipToQueueIndex,
|
||||
toggleShuffle,
|
||||
]
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import { useEffect, useState } from "react"
|
||||
import { getColors, type ImageColorsResult } from "react-native-image-colors"
|
||||
|
||||
import { withCoverImageSize } from "@/lib/urls"
|
||||
|
||||
function prominentColor(result: ImageColorsResult): string {
|
||||
switch (result.platform) {
|
||||
case "ios":
|
||||
return result.primary || result.background
|
||||
case "android":
|
||||
return result.vibrant || result.dominant || result.average
|
||||
case "web":
|
||||
return result.vibrant || result.dominant
|
||||
}
|
||||
}
|
||||
|
||||
export function useCoverBackgroundColor(
|
||||
uri: string,
|
||||
hasCover: boolean,
|
||||
fallback: string,
|
||||
) {
|
||||
const [backgroundColor, setBackgroundColor] = useState(fallback)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
if (!hasCover) {
|
||||
setBackgroundColor(fallback)
|
||||
return
|
||||
}
|
||||
|
||||
setBackgroundColor(fallback)
|
||||
const colorSourceUri = withCoverImageSize(uri, 64)
|
||||
void getColors(colorSourceUri, {
|
||||
fallback,
|
||||
cache: true,
|
||||
key: colorSourceUri,
|
||||
quality: "low",
|
||||
pixelSpacing: 8,
|
||||
})
|
||||
.then((result) => {
|
||||
if (!cancelled) {
|
||||
setBackgroundColor(prominentColor(result))
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) {
|
||||
setBackgroundColor(fallback)
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [fallback, hasCover, uri])
|
||||
|
||||
return backgroundColor
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { getColors, type ImageColorsResult } from "react-native-image-colors"
|
||||
|
||||
import {
|
||||
deriveCoverPalette,
|
||||
themeCoverPalette,
|
||||
type CoverPalette,
|
||||
type CoverSwatches,
|
||||
} from "@/lib/cover-palette"
|
||||
import { readCache, writeCache } from "@/lib/persistent-cache"
|
||||
import { useIsDark, useThemeColors } from "@/lib/theme"
|
||||
import { withCoverImageSize } from "@/lib/urls"
|
||||
|
||||
// How long a screen holds its skeleton for the first extraction of a cover,
|
||||
// so rows render once with final colors instead of flashing from the theme.
|
||||
export const COVER_PALETTE_WAIT_MS = 400
|
||||
|
||||
// image-colors substitutes this for swatches it couldn't find.
|
||||
const MISSING = "#010203"
|
||||
|
||||
const swatchesByKey = new Map<string, CoverSwatches | null>()
|
||||
const pending = new Map<string, Promise<CoverSwatches | null>>()
|
||||
|
||||
function cacheKey(colorSourceUri: string) {
|
||||
return `palette:${colorSourceUri}`
|
||||
}
|
||||
|
||||
function present(colors: (string | undefined)[]) {
|
||||
return colors.filter(
|
||||
(color): color is string => !!color && color.toLowerCase() !== MISSING
|
||||
)
|
||||
}
|
||||
|
||||
function toSwatches(result: ImageColorsResult): CoverSwatches | null {
|
||||
if (result.platform === "ios") {
|
||||
const text = present([result.primary, result.secondary, result.detail])
|
||||
return result.background.toLowerCase() === MISSING
|
||||
? null
|
||||
: { background: result.background, text, accent: text }
|
||||
}
|
||||
|
||||
const background = present([result.dominant, result.muted])[0]
|
||||
if (!background) return null
|
||||
return {
|
||||
background,
|
||||
text: present([
|
||||
result.lightVibrant,
|
||||
result.lightMuted,
|
||||
result.darkVibrant,
|
||||
result.darkMuted,
|
||||
result.vibrant,
|
||||
result.muted,
|
||||
]),
|
||||
accent: present([
|
||||
result.vibrant,
|
||||
result.lightVibrant,
|
||||
result.darkVibrant,
|
||||
result.muted,
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
function sameSwatches(
|
||||
a: CoverSwatches | null | undefined,
|
||||
b: CoverSwatches | null | undefined
|
||||
) {
|
||||
return a === b || JSON.stringify(a) === JSON.stringify(b)
|
||||
}
|
||||
|
||||
function cachedSwatches(key: string): CoverSwatches | null | undefined {
|
||||
if (swatchesByKey.has(key)) return swatchesByKey.get(key)
|
||||
return readCache<CoverSwatches>(cacheKey(key))
|
||||
}
|
||||
|
||||
function extractSwatches(key: string) {
|
||||
const inFlight = pending.get(key)
|
||||
if (inFlight) return inFlight
|
||||
|
||||
const request = getColors(key, {
|
||||
fallback: MISSING,
|
||||
cache: true,
|
||||
key,
|
||||
quality: "low",
|
||||
pixelSpacing: 4,
|
||||
})
|
||||
.then(toSwatches)
|
||||
.catch(() => null)
|
||||
.then((swatches) => {
|
||||
swatchesByKey.set(key, swatches)
|
||||
if (swatches) writeCache(cacheKey(key), swatches)
|
||||
pending.delete(key)
|
||||
return swatches
|
||||
})
|
||||
pending.set(key, request)
|
||||
return request
|
||||
}
|
||||
|
||||
/**
|
||||
* Colors for a screen tinted by `uri`'s cover art. Extraction runs once per
|
||||
* cover and is cached on device. Pass `hasCover` as `undefined` while it isn't
|
||||
* known yet so extraction can start early.
|
||||
*
|
||||
* `settled` turns true once the palette is final or after
|
||||
* `COVER_PALETTE_WAIT_MS`, whichever comes first.
|
||||
*/
|
||||
export function useCoverPalette(
|
||||
uri: string,
|
||||
hasCover: boolean | undefined
|
||||
): { palette: CoverPalette; settled: boolean } {
|
||||
const theme = useThemeColors()
|
||||
const isDark = useIsDark()
|
||||
const key = uri ? withCoverImageSize(uri, 64) : ""
|
||||
const [resolved, setResolved] = useState(() => ({
|
||||
key,
|
||||
swatches: key ? cachedSwatches(key) : null,
|
||||
}))
|
||||
const [waitedKey, setWaitedKey] = useState<string | null>(null)
|
||||
|
||||
const swatches =
|
||||
resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null
|
||||
|
||||
useEffect(() => {
|
||||
if (!key || hasCover === false) return
|
||||
let cancelled = false
|
||||
const known = cachedSwatches(key)
|
||||
const show = (next: CoverSwatches | null) =>
|
||||
setResolved((prev) =>
|
||||
prev.key === key && sameSwatches(prev.swatches, next)
|
||||
? prev
|
||||
: { key, swatches: next }
|
||||
)
|
||||
if (known !== undefined && swatchesByKey.has(key)) {
|
||||
show(known)
|
||||
return
|
||||
}
|
||||
|
||||
// Persisted swatches render immediately; refresh them in the background in
|
||||
// case the cover changed.
|
||||
const timer =
|
||||
known === undefined
|
||||
? setTimeout(() => !cancelled && setWaitedKey(key), COVER_PALETTE_WAIT_MS)
|
||||
: null
|
||||
void extractSwatches(key).then((next) => {
|
||||
if (!cancelled) show(next ?? known ?? null)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
if (timer) clearTimeout(timer)
|
||||
}
|
||||
}, [hasCover, key])
|
||||
|
||||
const palette = useMemo(() => {
|
||||
const fromArt =
|
||||
hasCover !== false && swatches ? deriveCoverPalette(swatches, isDark) : null
|
||||
return fromArt ?? themeCoverPalette(theme, isDark)
|
||||
}, [hasCover, isDark, swatches, theme])
|
||||
|
||||
return {
|
||||
palette,
|
||||
settled:
|
||||
!key || hasCover === false || swatches !== undefined || waitedKey === key,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
import type { ThemeColors } from "@/lib/theme"
|
||||
|
||||
/**
|
||||
* Colors for a screen tinted by its cover art, modeled on Apple Music's
|
||||
* artwork colors (`bgColor`, `textColor1`, `textColor2`).
|
||||
*/
|
||||
export type CoverPalette = {
|
||||
background: string
|
||||
foreground: string
|
||||
secondaryForeground: string
|
||||
accent: string
|
||||
accentForeground: string
|
||||
/** `accent` adjusted to be legible as body text. */
|
||||
accentText: string
|
||||
surface: string
|
||||
divider: string
|
||||
isDark: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw colors sampled from the art. `background` is the color the art bleeds
|
||||
* into; `text` is ordered by preference and `accent` holds candidates for the
|
||||
* Play button.
|
||||
*/
|
||||
export type CoverSwatches = {
|
||||
background: string
|
||||
text: string[]
|
||||
accent: string[]
|
||||
}
|
||||
|
||||
// Best effort: `legibleBackground` only guarantees that white or black reaches
|
||||
// 7:1, so on some backgrounds primary text settles for pure white or black.
|
||||
const PRIMARY_MIN_CONTRAST = 10
|
||||
const SECONDARY_MIN_CONTRAST = 4.5
|
||||
const SECONDARY_TO_PRIMARY_CONTRAST = 0.62
|
||||
const ACCENT_MIN_CONTRAST = 3
|
||||
const ACCENT_MIN_CHROMA = 0.05
|
||||
const ACCENT_MAX_LIGHTNESS_SHIFT = 0.25
|
||||
// Backgrounds between these luminances can't reach 7:1 with white or black.
|
||||
const DARK_BACKGROUND_MAX_LUMINANCE = 0.095
|
||||
const LIGHT_BACKGROUND_MIN_LUMINANCE = 0.31
|
||||
|
||||
type Rgb = [number, number, number]
|
||||
type Oklch = { l: number; c: number; h: number }
|
||||
|
||||
export function themeCoverPalette(theme: ThemeColors, isDark: boolean): CoverPalette {
|
||||
return {
|
||||
background: theme.background,
|
||||
foreground: theme.foreground,
|
||||
secondaryForeground: theme.mutedForeground,
|
||||
accent: theme.primary,
|
||||
accentForeground: theme.primaryForeground,
|
||||
accentText: theme.primary,
|
||||
surface: theme.muted,
|
||||
divider: theme.border,
|
||||
isDark,
|
||||
}
|
||||
}
|
||||
|
||||
export function deriveCoverPalette(
|
||||
swatches: CoverSwatches,
|
||||
schemeIsDark: boolean
|
||||
): CoverPalette | null {
|
||||
const source = parseHex(swatches.background)
|
||||
if (!source) return null
|
||||
|
||||
const background = legibleBackground(source, schemeIsDark)
|
||||
const lightText = prefersLightText(background)
|
||||
const parsedText = swatches.text
|
||||
.map(parseHex)
|
||||
.filter((color): color is Rgb => color !== null)
|
||||
const backgroundLuminance = luminance(background)
|
||||
const sameSideText = parsedText.filter((color) =>
|
||||
lightText
|
||||
? luminance(color) > backgroundLuminance
|
||||
: luminance(color) < backgroundLuminance
|
||||
)
|
||||
const textCandidates = sameSideText.length > 0 ? sameSideText : parsedText
|
||||
const fallbackText: Rgb = lightText ? [255, 255, 255] : [0, 0, 0]
|
||||
|
||||
const foreground = withMinContrast(
|
||||
textCandidates[0] ?? fallbackText,
|
||||
background,
|
||||
PRIMARY_MIN_CONTRAST
|
||||
)
|
||||
const primaryContrast = contrastRatio(foreground, background)
|
||||
const secondaryTarget = Math.max(
|
||||
SECONDARY_MIN_CONTRAST,
|
||||
primaryContrast * SECONDARY_TO_PRIMARY_CONTRAST
|
||||
)
|
||||
const secondaryForeground = softenTo(
|
||||
withMinContrast(
|
||||
textCandidates[1] ?? foreground,
|
||||
background,
|
||||
SECONDARY_MIN_CONTRAST
|
||||
),
|
||||
background,
|
||||
secondaryTarget
|
||||
)
|
||||
|
||||
const accent = pickAccent(swatches.accent, background) ?? foreground
|
||||
const accentForeground: Rgb = prefersLightText(accent)
|
||||
? [255, 255, 255]
|
||||
: [0, 0, 0]
|
||||
|
||||
return {
|
||||
background: toHex(background),
|
||||
foreground: toHex(foreground),
|
||||
secondaryForeground: toHex(secondaryForeground),
|
||||
accent: toHex(accent),
|
||||
accentForeground: toHex(accentForeground),
|
||||
accentText: toHex(withMinContrast(accent, background, SECONDARY_MIN_CONTRAST)),
|
||||
surface: toHex(mix(foreground, background, lightText ? 0.16 : 0.1)),
|
||||
divider: toHex(mix(foreground, background, lightText ? 0.2 : 0.14)),
|
||||
isDark: lightText,
|
||||
}
|
||||
}
|
||||
|
||||
function legibleBackground(color: Rgb, schemeIsDark: boolean): Rgb {
|
||||
const lch = toOklch(color)
|
||||
// Keep the art's hue but avoid a glaring page in dark mode or a murky one in
|
||||
// light mode.
|
||||
const clamped = schemeIsDark
|
||||
? withLightness(color, Math.min(lch.l, 0.86))
|
||||
: withLightness(color, Math.max(lch.l, 0.2))
|
||||
const y = luminance(clamped)
|
||||
if (y <= DARK_BACKGROUND_MAX_LUMINANCE || y >= LIGHT_BACKGROUND_MIN_LUMINANCE) {
|
||||
return clamped
|
||||
}
|
||||
|
||||
const pivot = schemeIsDark ? 0.28 : 0.14
|
||||
return y < pivot
|
||||
? withLuminance(clamped, DARK_BACKGROUND_MAX_LUMINANCE)
|
||||
: withLuminance(clamped, LIGHT_BACKGROUND_MIN_LUMINANCE)
|
||||
}
|
||||
|
||||
function pickAccent(candidates: string[], background: Rgb): Rgb | null {
|
||||
let best: Rgb | null = null
|
||||
let bestChroma = ACCENT_MIN_CHROMA
|
||||
for (const hex of candidates) {
|
||||
const color = parseHex(hex)
|
||||
if (!color) continue
|
||||
const adjusted = withMinContrast(color, background, ACCENT_MIN_CONTRAST)
|
||||
const before = toOklch(color)
|
||||
const after = toOklch(adjusted)
|
||||
// A color pushed far from its own lightness (yellow turned olive) no
|
||||
// longer reads as coming from the art.
|
||||
if (Math.abs(after.l - before.l) > ACCENT_MAX_LIGHTNESS_SHIFT) continue
|
||||
if (after.c > bestChroma) {
|
||||
best = adjusted
|
||||
bestChroma = after.c
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
function prefersLightText(background: Rgb) {
|
||||
return contrastRatio([255, 255, 255], background) >= contrastRatio([0, 0, 0], background)
|
||||
}
|
||||
|
||||
/** Moves `color`'s lightness away from `background` until it reaches `min`. */
|
||||
function withMinContrast(color: Rgb, background: Rgb, min: number): Rgb {
|
||||
if (contrastRatio(color, background) >= min) return color
|
||||
|
||||
const lighten = prefersLightText(background)
|
||||
const start = toOklch(color).l
|
||||
const extreme = lighten ? 1 : 0
|
||||
if (contrastRatio(withLightness(color, extreme), background) < min) {
|
||||
return lighten ? [255, 255, 255] : [0, 0, 0]
|
||||
}
|
||||
|
||||
let near = start
|
||||
let far = extreme
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const mid = (near + far) / 2
|
||||
if (contrastRatio(withLightness(color, mid), background) >= min) {
|
||||
far = mid
|
||||
} else {
|
||||
near = mid
|
||||
}
|
||||
}
|
||||
return withLightness(color, far)
|
||||
}
|
||||
|
||||
/** Blends `color` toward `background` until its contrast drops to `max`. */
|
||||
function softenTo(color: Rgb, background: Rgb, max: number): Rgb {
|
||||
if (contrastRatio(color, background) <= max) return color
|
||||
|
||||
let keep = 0
|
||||
let blend = 1
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const mid = (keep + blend) / 2
|
||||
if (contrastRatio(mix(color, background, mid), background) >= max) {
|
||||
blend = mid
|
||||
} else {
|
||||
keep = mid
|
||||
}
|
||||
}
|
||||
return mix(color, background, blend)
|
||||
}
|
||||
|
||||
function withLuminance(color: Rgb, target: number): Rgb {
|
||||
let low = 0
|
||||
let high = 1
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const mid = (low + high) / 2
|
||||
if (luminance(withLightness(color, mid)) < target) {
|
||||
low = mid
|
||||
} else {
|
||||
high = mid
|
||||
}
|
||||
}
|
||||
return withLightness(color, target <= DARK_BACKGROUND_MAX_LUMINANCE ? low : high)
|
||||
}
|
||||
|
||||
/** `amount` of `color` over `base`. */
|
||||
function mix(color: Rgb, base: Rgb, amount: number): Rgb {
|
||||
return [0, 1, 2].map((i) =>
|
||||
Math.round(base[i] + (color[i] - base[i]) * amount)
|
||||
) as Rgb
|
||||
}
|
||||
|
||||
function contrastRatio(a: Rgb, b: Rgb) {
|
||||
const la = luminance(a)
|
||||
const lb = luminance(b)
|
||||
return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)
|
||||
}
|
||||
|
||||
function luminance([r, g, b]: Rgb) {
|
||||
return 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b)
|
||||
}
|
||||
|
||||
function toLinear(channel: number) {
|
||||
const c = channel / 255
|
||||
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
|
||||
}
|
||||
|
||||
function fromLinear(value: number) {
|
||||
const c = value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055
|
||||
return c * 255
|
||||
}
|
||||
|
||||
function toOklch(color: Rgb): Oklch {
|
||||
const [r, g, b] = color.map(toLinear)
|
||||
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
|
||||
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
|
||||
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
|
||||
const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s
|
||||
const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s
|
||||
const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s
|
||||
return { l: L, c: Math.hypot(A, B), h: Math.atan2(B, A) }
|
||||
}
|
||||
|
||||
function oklchToLinear({ l: L, c, h }: Oklch): Rgb {
|
||||
const A = c * Math.cos(h)
|
||||
const B = c * Math.sin(h)
|
||||
const l = (L + 0.3963377774 * A + 0.2158037573 * B) ** 3
|
||||
const m = (L - 0.1055613458 * A - 0.0638541728 * B) ** 3
|
||||
const s = (L - 0.0894841775 * A - 1.291485548 * B) ** 3
|
||||
return [
|
||||
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
|
||||
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
|
||||
-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
|
||||
]
|
||||
}
|
||||
|
||||
/** Sets OKLCH lightness, reducing chroma as needed to stay within sRGB. */
|
||||
function withLightness(color: Rgb, lightness: number): Rgb {
|
||||
const lch = toOklch(color)
|
||||
const l = Math.min(1, Math.max(0, lightness))
|
||||
let c = lch.c
|
||||
let linear = oklchToLinear({ l, c, h: lch.h })
|
||||
for (let i = 0; i < 12 && !inGamut(linear); i++) {
|
||||
c *= 0.8
|
||||
linear = oklchToLinear({ l, c, h: lch.h })
|
||||
}
|
||||
return linear.map((value) =>
|
||||
Math.round(Math.min(255, Math.max(0, fromLinear(value))))
|
||||
) as Rgb
|
||||
}
|
||||
|
||||
function inGamut(linear: Rgb) {
|
||||
return linear.every((value) => value >= -0.0005 && value <= 1.0005)
|
||||
}
|
||||
|
||||
function parseHex(hex: string | undefined): Rgb | null {
|
||||
if (!hex) return null
|
||||
const match = /^#?([0-9a-f]{6})/i.exec(hex.trim())
|
||||
if (!match) return null
|
||||
const value = parseInt(match[1], 16)
|
||||
return [(value >> 16) & 255, (value >> 8) & 255, value & 255]
|
||||
}
|
||||
|
||||
function toHex(color: Rgb) {
|
||||
return `#${color.map((c) => c.toString(16).padStart(2, "0")).join("")}`
|
||||
}
|
||||
@@ -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
|
||||
@@ -22,6 +22,68 @@ export function repeatToPlaylistLoop(repeat: RepeatMode): PlaylistLoopMode {
|
||||
return "none"
|
||||
}
|
||||
|
||||
export type NativePlaylistEdit =
|
||||
| { type: "remove"; index: number }
|
||||
| { type: "insert"; index: number; songId: Id<"songs"> }
|
||||
| { type: "add"; songId: Id<"songs"> }
|
||||
|
||||
/**
|
||||
* Edits that turn the loaded native playlist into `desiredSongIds` without
|
||||
* touching the playing track, applied in order. `null` when the playing track
|
||||
* itself differs, which needs a rebuild.
|
||||
*/
|
||||
export function nativePlaylistEdits(
|
||||
loadedSongIds: Id<"songs">[],
|
||||
loadedCurrentIndex: number,
|
||||
desiredSongIds: Id<"songs">[],
|
||||
desiredCurrentIndex: number
|
||||
): NativePlaylistEdit[] | null {
|
||||
const current = loadedSongIds[loadedCurrentIndex]
|
||||
if (
|
||||
current === undefined ||
|
||||
current !== desiredSongIds[desiredCurrentIndex]
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
const edits: NativePlaylistEdit[] = []
|
||||
const desiredUpcoming = desiredSongIds.slice(desiredCurrentIndex + 1)
|
||||
const keptUpcoming = commonPrefixLength(
|
||||
loadedSongIds.slice(loadedCurrentIndex + 1),
|
||||
desiredUpcoming
|
||||
)
|
||||
for (
|
||||
let index = loadedSongIds.length - 1;
|
||||
index > loadedCurrentIndex + keptUpcoming;
|
||||
index--
|
||||
) {
|
||||
edits.push({ type: "remove", index })
|
||||
}
|
||||
for (const songId of desiredUpcoming.slice(keptUpcoming)) {
|
||||
edits.push({ type: "add", songId })
|
||||
}
|
||||
|
||||
const keptHistory = commonPrefixLength(
|
||||
loadedSongIds.slice(0, loadedCurrentIndex),
|
||||
desiredSongIds.slice(0, desiredCurrentIndex)
|
||||
)
|
||||
for (let index = loadedCurrentIndex - 1; index >= keptHistory; index--) {
|
||||
edits.push({ type: "remove", index })
|
||||
}
|
||||
for (let index = keptHistory; index < desiredCurrentIndex; index++) {
|
||||
edits.push({ type: "insert", index, songId: desiredSongIds[index] })
|
||||
}
|
||||
return edits
|
||||
}
|
||||
|
||||
function commonPrefixLength(a: Id<"songs">[], b: Id<"songs">[]) {
|
||||
let length = 0
|
||||
while (length < a.length && length < b.length && a[length] === b[length]) {
|
||||
length++
|
||||
}
|
||||
return length
|
||||
}
|
||||
|
||||
export function nativePlaylistNeedsRebuild(
|
||||
loadedSongIds: Id<"songs">[],
|
||||
historySongIds: Id<"songs">[],
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { CoverPalette } from "@/lib/cover-palette"
|
||||
|
||||
/** Now Playing colors: the cover palette plus translucent tints of its text color. */
|
||||
export type NowPlayingColors = {
|
||||
background: string
|
||||
foreground: string
|
||||
secondaryForeground: string
|
||||
sliderTrack: string
|
||||
sliderFill: string
|
||||
control: string
|
||||
controlPressed: string
|
||||
selected: string
|
||||
selectedForeground: string
|
||||
highlight: string
|
||||
isDark: boolean
|
||||
}
|
||||
|
||||
export function nowPlayingColors(palette: CoverPalette): NowPlayingColors {
|
||||
const { foreground } = palette
|
||||
return {
|
||||
background: palette.background,
|
||||
foreground,
|
||||
secondaryForeground: palette.secondaryForeground,
|
||||
sliderTrack: withAlpha(foreground, 0.2),
|
||||
sliderFill: withAlpha(foreground, 0.6),
|
||||
control: withAlpha(foreground, 0.14),
|
||||
controlPressed: withAlpha(foreground, 0.1),
|
||||
selected: withAlpha(foreground, 0.8),
|
||||
selectedForeground: palette.background,
|
||||
highlight: withAlpha(foreground, 0.1),
|
||||
isDark: palette.isDark,
|
||||
}
|
||||
}
|
||||
|
||||
function withAlpha(color: string, alpha: number) {
|
||||
const match = /^#([0-9a-f]{6})$/i.exec(color.trim())
|
||||
if (!match) return color
|
||||
const value = parseInt(match[1], 16)
|
||||
return `rgba(${(value >> 16) & 255}, ${(value >> 8) & 255}, ${value & 255}, ${alpha})`
|
||||
}
|
||||
@@ -63,5 +63,5 @@ const asyncStorageBackend: PersistentCacheBackend = {
|
||||
// Android's AsyncStorage database is capped at 6 MB by default, so keep fewer
|
||||
// entries than the web cache.
|
||||
configurePersistentCache(asyncStorageBackend, {
|
||||
maxEntriesByPrefix: { q: 200, song: 3000, files: 500 },
|
||||
maxEntriesByPrefix: { q: 200, song: 3000, files: 500, palette: 500 },
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
@@ -66,24 +66,6 @@ export function useMiniPlayerBackground(): string {
|
||||
return useIsDark() ? appleMusic.miniPlayer : appleMusic.miniPlayerLight
|
||||
}
|
||||
|
||||
export function usePlayerTheme() {
|
||||
const theme = useThemeColors()
|
||||
const isDark = useIsDark()
|
||||
|
||||
return {
|
||||
colors: theme,
|
||||
isDark,
|
||||
blurTint: isDark ? ("dark" as const) : ("light" as const),
|
||||
statusBar: isDark ? ("light" as const) : ("dark" as const),
|
||||
scrim: isDark ? "rgba(0, 0, 0, 0.28)" : "rgba(255, 255, 255, 0.5)",
|
||||
androidScrim: isDark ? "rgba(0, 0, 0, 0.72)" : "rgba(255, 255, 255, 0.9)",
|
||||
backgroundImageOpacity: isDark ? 0.55 : 0.4,
|
||||
trackInactive: isDark ? "rgba(255, 255, 255, 0.25)" : "rgba(0, 0, 0, 0.12)",
|
||||
buttonSurface: isDark ? "rgba(255, 255, 255, 0.14)" : "rgba(0, 0, 0, 0.08)",
|
||||
handle: isDark ? "rgba(255, 255, 255, 0.35)" : "rgba(0, 0, 0, 0.2)",
|
||||
}
|
||||
}
|
||||
|
||||
export const spacing = {
|
||||
xs: 4,
|
||||
sm: 8,
|
||||
|
||||
@@ -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;
|
||||
+6
-1
@@ -18,5 +18,10 @@
|
||||
"prettier": "^3.8.3",
|
||||
"prettier-plugin-tailwindcss": "^0.8.0"
|
||||
},
|
||||
"packageManager": "pnpm@10.1.0"
|
||||
"packageManager": "pnpm@10.1.0",
|
||||
"pnpm": {
|
||||
"patchedDependencies": {
|
||||
"expo-audio@57.0.0": "patches/expo-audio@57.0.0.patch"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,10 @@ export function clearQueue(state: PlaybackQueueState): PlaybackQueueState {
|
||||
return { ...state, queue: [], history: [], progressSeconds: 0 }
|
||||
}
|
||||
|
||||
export function clearHistory(state: PlaybackQueueState): PlaybackQueueState {
|
||||
return state.history.length === 0 ? state : { ...state, history: [] }
|
||||
}
|
||||
|
||||
export function reorderQueue(
|
||||
state: PlaybackQueueState,
|
||||
songIds: Id<"songs">[]
|
||||
@@ -169,6 +173,22 @@ export function skipToQueueIndex(
|
||||
}
|
||||
}
|
||||
|
||||
/** Plays `history[index]`, putting it and every later song back in the queue. */
|
||||
export function skipToHistoryIndex(
|
||||
state: PlaybackQueueState,
|
||||
index: number
|
||||
): PlaybackQueueState {
|
||||
if (index < 0 || index >= state.history.length) {
|
||||
return state
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
queue: [...state.history.slice(index), ...state.queue],
|
||||
history: state.history.slice(0, index),
|
||||
progressSeconds: 0,
|
||||
}
|
||||
}
|
||||
|
||||
export function skipNext(state: PlaybackQueueState): PlaybackQueueState {
|
||||
if (state.queue.length === 0) {
|
||||
return state
|
||||
|
||||
@@ -29,8 +29,7 @@ export function playbackStreamPlan(
|
||||
preferAtmos: boolean
|
||||
): PlaybackStreamPlan {
|
||||
const playbackQuality = quality ?? "medium"
|
||||
const kbps =
|
||||
playbackQuality === "lossless" ? 0 : qualityKbps(playbackQuality)
|
||||
const kbps = playbackQuality === "lossless" ? 0 : qualityKbps(playbackQuality)
|
||||
const effectivePreferAtmos = preferAtmos && "atmos" in files
|
||||
|
||||
let transcodeNeeded = true
|
||||
@@ -50,3 +49,19 @@ export function playbackStreamPlan(
|
||||
useHls: transcodeNeeded,
|
||||
}
|
||||
}
|
||||
|
||||
export type PlaybackFormat = "atmos" | "lossless"
|
||||
|
||||
/** The labeled format a song streams in under the plan, if any. */
|
||||
export function playbackFormat(
|
||||
files: Record<string, unknown>,
|
||||
quality: PlaybackQuality | undefined,
|
||||
preferAtmos: boolean
|
||||
): PlaybackFormat | null {
|
||||
const plan = playbackStreamPlan(files, quality, preferAtmos)
|
||||
if (plan.preferAtmos) return "atmos"
|
||||
if (plan.playbackQuality === "lossless" && "lossless" in files) {
|
||||
return "lossless"
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
diff --git a/ios/AudioPlaylist.swift b/ios/AudioPlaylist.swift
|
||||
index db2c6af75ec8766757fc16c7db2f3ae365c275a0..52682780e06bbd0583eb47032dac560206b23aeb 100644
|
||||
--- a/ios/AudioPlaylist.swift
|
||||
+++ b/ios/AudioPlaylist.swift
|
||||
@@ -149,17 +149,22 @@ public class AudioPlaylist: SharedRef<AVQueuePlayer>, Playable {
|
||||
return
|
||||
}
|
||||
|
||||
- let wasPlaying = isPlaying
|
||||
sources.insert(source, at: index)
|
||||
|
||||
if index <= currentTrackIndex {
|
||||
+ // Earlier tracks aren't queued in the player, so only the index moves.
|
||||
currentTrackIndex += 1
|
||||
+ } else if let item = AudioUtils.createAVPlayerItem(from: source) {
|
||||
+ // Queue the item in place so the playing item is left alone.
|
||||
+ let queued = ref.items()
|
||||
+ let offset = index - currentTrackIndex
|
||||
+ let after = offset - 1 < queued.count ? queued[offset - 1] : queued.last
|
||||
+ ref.insert(item, after: after)
|
||||
+ if currentItem == nil {
|
||||
+ currentItem = ref.currentItem
|
||||
+ }
|
||||
}
|
||||
|
||||
- rebuildPlaylist(startingAt: currentTrackIndex)
|
||||
- if wasPlaying {
|
||||
- play(at: currentRate)
|
||||
- }
|
||||
updateStatus(with: ["trackCount": trackCount])
|
||||
}
|
||||
|
||||
@@ -180,10 +185,13 @@ public class AudioPlaylist: SharedRef<AVQueuePlayer>, Playable {
|
||||
play(at: currentRate)
|
||||
}
|
||||
} else if index < currentTrackIndex {
|
||||
+ // Earlier tracks aren't queued in the player, so only the index moves.
|
||||
currentTrackIndex -= 1
|
||||
- rebuildPlaylist(startingAt: currentTrackIndex)
|
||||
- if wasPlaying {
|
||||
- play(at: currentRate)
|
||||
+ } else {
|
||||
+ let queued = ref.items()
|
||||
+ let offset = index - currentTrackIndex
|
||||
+ if offset < queued.count {
|
||||
+ ref.remove(queued[offset])
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+7
-2
@@ -4,6 +4,11 @@ settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
patchedDependencies:
|
||||
expo-audio@57.0.0:
|
||||
hash: 545bf6f7cc9a4124a97048734d689acacfe7199b46a4a40263c2703b9c21bc10
|
||||
path: patches/expo-audio@57.0.0.patch
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
@@ -46,7 +51,7 @@ importers:
|
||||
version: 57.0.3(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3)(typescript@6.0.3)
|
||||
expo-audio:
|
||||
specifier: ^57.0.0
|
||||
version: 57.0.0(expo-asset@57.0.3(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3)(typescript@6.0.3))(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3)
|
||||
version: 57.0.0(patch_hash=545bf6f7cc9a4124a97048734d689acacfe7199b46a4a40263c2703b9c21bc10)(expo-asset@57.0.3(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3)(typescript@6.0.3))(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3)
|
||||
expo-blur:
|
||||
specifier: ~57.0.0
|
||||
version: 57.0.0(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3)
|
||||
@@ -10776,7 +10781,7 @@ snapshots:
|
||||
- supports-color
|
||||
- typescript
|
||||
|
||||
expo-audio@57.0.0(expo-asset@57.0.3(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3)(typescript@6.0.3))(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3):
|
||||
expo-audio@57.0.0(patch_hash=545bf6f7cc9a4124a97048734d689acacfe7199b46a4a40263c2703b9c21bc10)(expo-asset@57.0.3(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3)(typescript@6.0.3))(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3):
|
||||
dependencies:
|
||||
expo: 57.0.4(@babel/core@7.29.7)(@expo/dom-webview@57.0.0)(@expo/metro-runtime@57.0.3)(expo-router@57.0.4)(react-dom@19.2.4(react@19.2.3))(react-native-worklets@0.10.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3))(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3)(typescript@6.0.3)
|
||||
expo-asset: 57.0.3(expo@57.0.4)(react-native@0.86.0(@babel/core@7.29.7)(@react-native/metro-config@0.86.0(@babel/core@7.29.7))(@types/react@19.2.17)(react@19.2.3))(react@19.2.3)(typescript@6.0.3)
|
||||
|
||||
Reference in new issue
Block a user