Files
otunes/apps/mobile/app/(app)/player.tsx
T

821 lines
23 KiB
TypeScript

import { useTabletLayout } from "@/hooks/use-tablet-layout"
import {
TabletNowPlaying,
type PlayerPanel,
} from "@/components/tablet-now-playing"
import { atmosEnabled } from "@/lib/playback-capabilities"
import { NavigationBar } from "expo-navigation-bar"
import { MusicEntityView } from "@/components/music-entity-view"
import { Stack, useRouter, useLocalSearchParams } from "expo-router"
import * as Haptics from "expo-haptics"
import { StatusBar } from "expo-status-bar"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import {
Platform,
Pressable,
StyleSheet,
Text,
useWindowDimensions,
View,
} from "react-native"
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 { api } from "@otunes/convex/_generated/api"
import { playbackFormat } from "@otunes/convex/playback-stream"
import { AudioFormatBadge } from "@/components/audio-format-badge"
import { AudioOutputButton } from "@/components/audio-output-button"
import { CoverImage } from "@/components/cover-image"
import { MarqueeText } from "@/components/marquee-text"
import {
MediaActionMenu,
type MediaAction,
} from "@/components/media-context-menu"
import {
NowPlayingQueue,
QUEUE_HORIZONTAL_INSET,
} from "@/components/now-playing-queue"
import { PlayerArtistMenu } from "@/components/player-artist-menu"
import { PlayerProgress } from "@/components/player-progress"
import { PlayerSlider } from "@/components/player-slider"
import { PlayerSymbol } from "@/components/player-symbol"
import { useFavorites } from "@/contexts/favorites"
import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback"
import { useServerConfig } from "@/contexts/server-config"
import { LyricsView } from "@/components/lyrics-view"
import { useCachedQuery } from "@/hooks/use-cached-query"
import { useLyrics } from "@/hooks/use-lyrics"
import { useCoverPalette } from "@/hooks/use-cover-palette"
import { useMediaMenuActions } from "@/hooks/use-media-menu-actions"
import { useSystemVolume } from "@/hooks/use-system-volume"
import {
nowPlayingColors,
type NowPlayingColors,
} from "@/lib/now-playing-colors"
import { albumCoverUrl } from "@/lib/urls"
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 tabletLayout = useTabletLayout()
const router = useRouter()
const hadSongRef = useRef(false)
const insets = useSafeAreaInsets()
const { width: windowWidth, height: windowHeight } = useWindowDimensions()
// Unfolded iPhones retain the phone idiom but have room for the iPad player.
const isTablet =
tabletLayout ||
(Platform.OS === "ios" && Math.min(windowWidth, windowHeight) >= 600)
const { config } = useServerConfig()
const {
currentSong,
isPlaying,
shuffleEnabled,
repeatEnabled,
queueSongIds,
} = usePlaybackQueue()
const { setIsPlaying, skipNext, skipPrevious } = usePlaybackActions()
const params = useLocalSearchParams<{ queue?: string; lyrics?: string }>()
// The queue or lyrics, shown in place of the artwork.
const [panel, setPanel] = useState<PlayerPanel | null>(
params.queue === "1" ? "queue" : params.lyrics === "1" ? "lyrics" : null
)
const showQueue = panel === "queue"
const showLyrics = panel === "lyrics"
const lyrics = useLyrics(currentSong?.id ?? null)
const [isDismissing, setIsDismissing] = useState(false)
const [stageHeight, setStageHeight] = useState(0)
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,
atmosEnabled(user)
)
: null
const coverUri =
currentSong && config
? albumCoverUrl(config.serverUrl, currentSong.album.id)
: ""
const { palette } = useCoverPalette(
coverUri,
currentSong ? currentSong.album.cover != null : undefined
)
const colors = useMemo(() => nowPlayingColors(palette), [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. Each GestureDetector needs its own gesture instance.
const makeDismissGesture = useCallback(
() =>
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
) {
scheduleOnRN(setIsDismissing, true)
dismissY.value = withTiming(
windowHeight,
{ duration: 220 },
(finished) => {
if (finished) scheduleOnRN(router.back)
}
)
} else {
dismissY.value = withSpring(0, {
duration: 350,
dampingRatio: 0.85,
})
}
}),
[dismissY, router, windowHeight]
)
const handleGesture = useMemo(makeDismissGesture, [makeDismissGesture])
const controlsGesture = useMemo(makeDismissGesture, [makeDismissGesture])
const stageGesture = useMemo(
() => makeDismissGesture().enabled(panel === null),
[makeDismissGesture, panel]
)
const hasCover = currentSong ? currentSong.album.cover != null : false
const queueHeader = useMemo(
() =>
currentSong ? (
<View style={styles.queueHeader}>
<CoverImage
uri={coverUri}
hasCover={hasCover}
style={styles.queueArtwork}
/>
<SongMeta song={currentSong} colors={colors} compact />
</View>
) : null,
[colors, coverUri, currentSong, hasCover]
)
const songMeta = useMemo(
() =>
currentSong ? <SongMeta song={currentSong} colors={colors} /> : null,
[colors, currentSong]
)
const hasQueue = queueSongIds.length > 0
useEffect(() => {
if (hasQueue) {
hadSongRef.current = true
return
}
if (hadSongRef.current) {
router.back()
}
}, [hasQueue, router])
if (!currentSong || !config) {
return null
}
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
)
)
function togglePlayback() {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)
setIsPlaying(!isPlaying)
}
function togglePanel(next: PlayerPanel) {
void Haptics.selectionAsync()
setPanel((value) => (value === next ? null : next))
}
if (isTablet) {
return (
<MusicEntityView kind="song" id={currentSong.id} style={{ flex: 1 }}>
<TabletNowPlaying
colors={colors}
backgroundStyle={backgroundStyle}
dismissStyle={dismissStyle}
dismissGestures={{ handle: handleGesture, artwork: controlsGesture }}
panel={panel}
togglePanel={togglePanel}
lyrics={lyrics}
metadata={songMeta}
/>
</MusicEntityView>
)
}
return (
<Animated.View style={[styles.root, backgroundStyle, dismissStyle]}>
<StatusBar style={colors.isDark ? "light" : "dark"} />
{Platform.OS === "android" ? (
<>
<Stack.Screen
options={{
statusBarStyle: colors.isDark ? "light" : "dark",
// The swipe already animates the player offscreen.
animation: isDismissing ? "none" : "slide_from_bottom",
}}
/>
<NavigationBar style={colors.isDark ? "light" : "dark"} />
</>
) : null}
<MusicEntityView
kind="song"
id={currentSong.id}
style={[styles.safe, { paddingTop: insets.top }]}
>
<GestureDetector gesture={handleGesture}>
<Pressable
onPress={() => router.back()}
hitSlop={12}
style={styles.handleRow}
accessibilityRole="button"
accessibilityLabel="Close player"
>
<View
style={[styles.handle, { backgroundColor: colors.sliderTrack }]}
/>
</Pressable>
</GestureDetector>
<GestureDetector gesture={stageGesture}>
<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={queueHeader}
/>
</Animated.View>
) : null
) : showLyrics ? (
<Animated.View
key="lyrics"
entering={MODE_FADE_IN}
exiting={MODE_FADE_OUT}
style={[styles.fill, styles.artworkMode]}
>
{queueHeader}
<LyricsView
key={currentSong.id}
lyrics={lyrics}
colors={colors}
/>
</Animated.View>
) : (
<Animated.View
key="artwork"
entering={MODE_FADE_IN}
exiting={MODE_FADE_OUT}
style={[styles.fill, styles.artworkMode]}
>
<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}</View>
</Animated.View>
)}
</LayoutAnimationConfig>
</View>
</GestureDetector>
<GestureDetector gesture={controlsGesture}>
<View style={[styles.controls, { paddingBottom: bottomInset }]}>
<PlayerProgress
colors={colors}
timeStyle={styles.time}
center={
format ? (
<AudioFormatBadge
format={format}
color={colors.secondaryForeground}
backgroundColor={colors.background}
/>
) : null
}
/>
<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>
<VolumeSlider colors={colors} />
<View style={styles.footer}>
<Pressable
onPress={() => togglePanel("lyrics")}
disabled={!lyrics && !showLyrics}
hitSlop={8}
accessibilityRole="button"
accessibilityLabel={showLyrics ? "Hide lyrics" : "Show lyrics"}
accessibilityState={{
selected: showLyrics,
disabled: !lyrics && !showLyrics,
}}
style={[
styles.queueButton,
!lyrics && !showLyrics && styles.unavailable,
showLyrics && { backgroundColor: colors.selected },
]}
>
<PlayerSymbol
name="quote.bubble"
fallback={{ material: "lyrics" }}
size={27}
weight="semibold"
color={
showLyrics ? colors.selectedForeground : colors.foreground
}
/>
</Pressable>
<AudioOutputButton
color={colors.foreground}
style={styles.queueButton}
/>
<Pressable
onPress={() => togglePanel("queue")}
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>
</GestureDetector>
</MusicEntityView>
</Animated.View>
)
}
/** Phone volume slider. Owns the volume listener so volume changes stay local. */
function VolumeSlider({ colors }: { colors: NowPlayingColors }) {
const { volume, setVolume, available } = useSystemVolume()
if (!available) return null
return (
<PlayerSlider
accessibilityLabel="Volume"
commitHoldMs={0}
animateValueChanges
value={volume}
maximumValue={1}
fillColor={colors.sliderFill}
activeFillColor={colors.foreground}
trackColor={colors.sliderTrack}
onValueChange={setVolume}
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}
/>
}
/>
)
}
/** 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 },
]}
/>
<PlayerArtistMenu song={song} onAction={handleAction}>
<MarqueeText
text={song.artist.name}
style={[
compact ? styles.compactArtist : styles.artist,
{ color: colors.secondaryForeground },
]}
/>
</PlayerArtistMenu>
</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
share={{
type: "song",
songId: song.id,
albumId: song.album.id,
title: song.title,
}}
stationArtistId={song.artist.id}
favorited={favorited}
navigation={{
artist: { id: song.artist.id },
album: { id: song.album.id },
}}
includeActions={[
"share",
"play-next",
"play-last",
"shuffle",
"create-station",
"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,
overflow: "hidden",
},
safe: {
flex: 1,
},
fill: {
flex: 1,
},
handleRow: {
alignItems: "center",
paddingTop: spacing.sm,
paddingBottom: spacing.sm,
},
handle: {
width: 36,
height: 5,
borderRadius: radius.full,
},
stage: {
flex: 1,
minHeight: 0,
},
artworkMode: {
paddingHorizontal: HORIZONTAL_INSET,
},
artworkArea: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
artworkShadow: {
borderRadius: radius.md,
shadowColor: "#000",
shadowRadius: 24,
shadowOffset: { width: 0, height: 14 },
},
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: "center",
gap: spacing.md,
},
metaText: {
flex: 1,
minWidth: 0,
},
title: {
fontSize: 20,
fontWeight: "600",
},
artist: {
fontSize: 20,
marginTop: 1,
},
compactTitle: {
fontSize: 17,
fontWeight: "600",
},
compactArtist: {
fontSize: 15,
marginTop: 1,
},
menu: {
alignSelf: "center",
},
metaButton: {
width: 30,
height: 30,
borderRadius: 15,
alignItems: "center",
justifyContent: "center",
},
controls: {
flexShrink: 0,
paddingHorizontal: HORIZONTAL_INSET,
paddingTop: spacing.md,
},
time: { fontWeight: "600" },
transport: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 28,
marginVertical: spacing.xl,
},
skipButton: {
width: 72,
height: 72,
borderRadius: 36,
alignItems: "center",
justifyContent: "center",
},
playButton: {
width: 84,
height: 84,
borderRadius: 42,
alignItems: "center",
justifyContent: "center",
},
footer: {
flexDirection: "row",
justifyContent: "space-between",
paddingTop: spacing.md,
paddingHorizontal: 40,
},
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",
},
})