Files
otunes/apps/mobile/components/now-playing-queue.tsx
T

877 lines
23 KiB
TypeScript

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 LayoutChangeEvent,
type StyleProp,
type ViewStyle,
} 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 { usePlaybackActions, usePlaybackQueue } 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; tablet?: 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.tablet
? 44
: 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,
tablet = false,
fadeColor,
}: {
colors: NowPlayingColors
viewportHeight: number
currentHeader: ReactNode
tablet?: boolean
fadeColor?: string
}) {
const { queueSongIds, queueHistorySongIds, shuffleEnabled, repeatEnabled } =
usePlaybackQueue()
const {
toggleShuffle,
cycleRepeat,
clearHistory,
reorderQueue,
skipToQueueIndex,
skipToHistoryIndex,
} = usePlaybackActions()
const [viewportWidth, setViewportWidth] = useState(0)
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,
})
)
}
if (!tablet) list.push({ type: "current", key: "current" })
const hasUpcoming = queueSongIds.length > 1
list.push({
type: "controls",
key: "controls",
showTitle: hasUpcoming,
tablet,
})
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, tablet])
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 === (tablet ? "controls" : "current")
)
const controlsIndex = tablet ? currentIndex : 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,
}: {
item: QueueListItem
style: StyleProp<ViewStyle>
children: ReactNode
onLayout?: (event: LayoutChangeEvent) => void
}) {
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 lastIndex = queueSongIds.length - 1
const renderItem = useCallback(
({ 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: itemHeight(item),
backgroundColor: tablet ? "transparent" : colors.background,
},
]}
>
{!tablet ? (
<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>
) : null}
{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={lastIndex}
tablet={tablet}
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>
)
}
},
[
clearHistory,
colors,
currentHeader,
cycleRepeat,
drag,
handleDragStart,
handleDrop,
handleRemove,
lastIndex,
repeatEnabled,
shuffleEnabled,
skipToHistoryIndex,
skipToQueueIndex,
swipeGroup,
tablet,
toggleShuffle,
]
)
return (
<View
style={styles.root}
onLayout={(event) => setViewportWidth(event.nativeEvent.layout.width)}
>
<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
key={viewportWidth}
pointerEvents="none"
style={styles.bottomFade}
width={viewportWidth}
height={BOTTOM_FADE_HEIGHT}
>
<Defs>
<LinearGradient id="queue-fade" x1="0" y1="0" x2="0" y2="1">
<Stop
offset="0"
stopColor={fadeColor ?? colors.background}
stopOpacity={0}
/>
<Stop
offset="1"
stopColor={fadeColor ?? colors.background}
stopOpacity={1}
/>
</LinearGradient>
</Defs>
<Rect
width={viewportWidth}
height={BOTTOM_FADE_HEIGHT}
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,
tablet = false,
colors,
drag,
swipeGroup,
onPress,
onRemove,
onDragStart,
onDrop,
}: {
songId: Id<"songs">
queueIndex: number
lastIndex: number
tablet?: boolean
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>
}
/>
{tablet ? (
<View
pointerEvents="none"
style={{
position: "absolute",
left: 88,
right: 26,
bottom: 0,
height: StyleSheet.hairlineWidth,
backgroundColor: colors.sliderTrack,
}}
/>
) : null}
<Animated.View
pointerEvents="none"
style={[
StyleSheet.absoluteFill,
{ backgroundColor: colors.highlight },
liftStyle,
]}
/>
</RowTap>
)
return (
<Animated.View style={shiftStyle}>
{Platform.OS === "ios" ? (
<SwipeToRemoveRow
group={swipeGroup}
backgroundColor={tablet ? "transparent" : 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,
},
})