feat(mobile): Apple Music-style Now Playing screen (#37)

This commit was merged in pull request #37.
This commit is contained in:
joshuafhiggins committed 2026-10-17 20:10:27 -04:00
1 parent a9f9aa33ec
commit 38add8df53
16 files changed
+2158 -289

No files matched your search

+4 -1
View File
@@ -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
View File
@@ -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",
},
})
+100
View File
@@ -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,
},
})
@@ -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,
},
})
+185
View File
@@ -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%",
},
})
+32
View File
@@ -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} />
}
+127 -31
View File
@@ -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,
]
+62
View File
@@ -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">[],
+40
View File
@@ -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})`
}
-18
View File
@@ -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,
+6 -1
View File
@@ -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"
}
}
}
+20
View File
@@ -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
+17 -2
View File
@@ -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
}
+49
View File
@@ -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])
}
}
+7 -2
View File
@@ -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)