From a561fdf3c42cad264cb589a59260b01f0e6a9cbd Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 14:46:26 -0500 Subject: [PATCH] fix(mobile): stop the player re-rendering on every playback tick The playback clock lived in the broad usePlayback() value, so the player, tablet player, queue and intent bridge re-rendered twice a second. seekTo also depended on duration, which changed every playback action's identity on each track change and re-rendered every album row. - Move currentTime and duration into usePlaybackProgress(), read only by the new PlayerProgress slider and time labels. Drop usePlayback(). - Read duration from a ref in seekTo so all actions stay stable. - Memoize dismiss gestures, now playing colors, the queue header and the queue renderItem. Pass a stable onPlay to AlbumTrackRow. - Keep the phone volume listener in its own VolumeSlider so the tablet player no longer registers it twice. Co-Authored-By: Claude Opus 5.5 --- .../app/(app)/(tabs)/home/album/[id].tsx | 12 +- apps/mobile/app/(app)/player.tsx | 257 ++++++++---------- apps/mobile/components/app-intent-bridge.tsx | 4 +- apps/mobile/components/now-playing-queue.tsx | 218 ++++++++------- apps/mobile/components/player-progress.tsx | 83 ++++++ apps/mobile/components/tablet-now-playing.tsx | 77 ++---- apps/mobile/contexts/playback.tsx | 79 +++--- 7 files changed, 381 insertions(+), 349 deletions(-) create mode 100644 apps/mobile/components/player-progress.tsx diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx index a32bf8c..b4734e3 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -111,6 +111,12 @@ export default function AlbumScreen() { const listItems = useMemo(() => albumListItems(album?.tracks ?? []), [album]) + const playTrack = useCallback( + (songId: Id<"songs">, ids: Id<"songs">[]) => + playFromSong(songId, ids, `album:${id}`), + [id, playFromSong] + ) + const renderItem = useCallback( ({ item }: { item: AlbumListItem }) => { if (item.type === "disc") { @@ -125,9 +131,7 @@ export default function AlbumScreen() { songIds={songIds} palette={palette} favorited={isSongFavorite(item.track.id)} - onPlay={(songId, ids) => - playFromSong(songId, ids, `album:${album.id}`) - } + onPlay={playTrack} onAction={handleAlbumTrackAction} /> ) : null @@ -137,7 +141,7 @@ export default function AlbumScreen() { handleAlbumTrackAction, isSongFavorite, palette, - playFromSong, + playTrack, songIds, swipeGroup, ] diff --git a/apps/mobile/app/(app)/player.tsx b/apps/mobile/app/(app)/player.tsx index 74da7bc..d799264 100644 --- a/apps/mobile/app/(app)/player.tsx +++ b/apps/mobile/app/(app)/player.tsx @@ -6,7 +6,7 @@ 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 { useEffect, useRef, useState } from "react" +import { useCallback, useEffect, useMemo, useRef, useState } from "react" import { Gesture, GestureDetector } from "react-native-gesture-handler" import { Platform, @@ -45,16 +45,16 @@ import { 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 { usePlayback } from "@/contexts/playback" +import { usePlaybackActions, usePlaybackQueue } 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 { useSystemVolume } from "@/hooks/use-system-volume" -import { formatDuration, formatRemainingDuration } from "@/lib/format" import { nowPlayingColors, type NowPlayingColors, @@ -90,20 +90,13 @@ export default function PlayerScreen() { isPlaying, shuffleEnabled, repeatEnabled, - currentTime, - duration, queueSongIds, - setIsPlaying, - seekTo, - skipNext, - skipPrevious, - } = usePlayback() - const { volume, setVolume, available: volumeAvailable } = useSystemVolume() + } = usePlaybackQueue() + const { setIsPlaying, skipNext, skipPrevious } = usePlaybackActions() const { queue } = useLocalSearchParams<{ queue?: string }>() const [showQueue, setShowQueue] = useState(queue === "1") const [isDismissing, setIsDismissing] = useState(false) const [stageHeight, setStageHeight] = useState(0) - const [scrubTime, setScrubTime] = useState(null) const user = useCachedQuery(api.auth.currentUser) const playbackInfo = useCachedQuery( api.library.getSongPlaybackInfo, @@ -126,7 +119,7 @@ export default function PlayerScreen() { coverUri, currentSong ? currentSong.album.cover != null : undefined ) - const colors = nowPlayingColors(palette) + const colors = useMemo(() => nowPlayingColors(palette), [palette]) const background = useSharedValue(colors.background) useEffect(() => { @@ -159,33 +152,65 @@ export default function PlayerScreen() { })) // 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 - ) { - 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 }) - } - }) - } + // 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(!showQueue), + [makeDismissGesture, showQueue] + ) + + const hasCover = currentSong ? currentSong.album.cover != null : false + const queueHeader = useMemo( + () => + currentSong ? ( + + + + + ) : null, + [colors, coverUri, currentSong, hasCover] + ) + const songMeta = useMemo( + () => + currentSong ? : null, + [colors, currentSong] + ) const hasQueue = queueSongIds.length > 0 @@ -204,7 +229,6 @@ export default function PlayerScreen() { return null } - const hasCover = currentSong.album.cover != null const bottomInset = Math.max(insets.bottom, spacing.md) const artworkSize = Math.max( 0, @@ -213,9 +237,6 @@ export default function PlayerScreen() { 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) @@ -234,10 +255,10 @@ export default function PlayerScreen() { colors={colors} backgroundStyle={backgroundStyle} dismissStyle={dismissStyle} - dismissGesture={dismissGesture} + dismissGestures={{ handle: handleGesture, artwork: controlsGesture }} showQueue={showQueue} toggleQueue={toggleQueue} - metadata={} + metadata={songMeta} /> ) @@ -264,7 +285,7 @@ export default function PlayerScreen() { id={currentSong.id} style={[styles.safe, { paddingTop: insets.top }]} > - + router.back()} hitSlop={12} @@ -278,7 +299,7 @@ export default function PlayerScreen() { - + @@ -297,20 +318,7 @@ export default function PlayerScreen() { - - - - } + currentHeader={queueHeader} /> ) : null @@ -334,50 +342,28 @@ export default function PlayerScreen() { /> - - - + {songMeta} )} - + - { - void seekTo(value) - setScrubTime(null) - }} - /> - - - {formatDuration(displayedTime)} - - {format ? ( - + - - ) : null} - - {formatRemainingDuration(displayedTime, duration).replace( - "-", - "\u2212" - )} - - + ) : null + } + /> - {volumeAvailable ? ( - - } - trailing={ - - } - /> - ) : null} + + } + trailing={ + + } + /> + ) +} + /** Title and artist with the favorite and more buttons. */ function SongMeta({ song, @@ -739,23 +732,7 @@ const styles = StyleSheet.create({ 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: 12, - fontWeight: "600", - fontVariant: ["tabular-nums"], - }, + time: { fontWeight: "600" }, transport: { flexDirection: "row", alignItems: "center", diff --git a/apps/mobile/components/app-intent-bridge.tsx b/apps/mobile/components/app-intent-bridge.tsx index c73c49d..2210a71 100644 --- a/apps/mobile/components/app-intent-bridge.tsx +++ b/apps/mobile/components/app-intent-bridge.tsx @@ -14,7 +14,7 @@ import { ANONYMOUS_CACHE_SCOPE, useCacheScope, } from "@/contexts/persistent-cache" -import { usePlayback } from "@/contexts/playback" +import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback" import { FAVORITES_PLAYLIST_ID, loadHandledIntentIds, @@ -156,7 +156,7 @@ export function AppIntentBridge() { function ReadyAppIntentBridge() { const convex = useConvex() const cacheScope = useCacheScope() - const playback = usePlayback() + const playback = { ...usePlaybackQueue(), ...usePlaybackActions() } const user = useQuery(api.auth.currentUser) const navigation = useAppNavigation() const favorites = useQuery(api.favorites.getUserFavorites) diff --git a/apps/mobile/components/now-playing-queue.tsx b/apps/mobile/components/now-playing-queue.tsx index 6976d70..7a5dec1 100644 --- a/apps/mobile/components/now-playing-queue.tsx +++ b/apps/mobile/components/now-playing-queue.tsx @@ -38,7 +38,7 @@ import { type SwipeRowGroup, } from "@/components/ios-swipe-to-remove-row" import { PlayerSymbol } from "@/components/player-symbol" -import { usePlayback } from "@/contexts/playback" +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" @@ -110,18 +110,16 @@ export function NowPlayingQueue({ tablet?: boolean fadeColor?: string }) { + const { queueSongIds, queueHistorySongIds, shuffleEnabled, repeatEnabled } = + usePlaybackQueue() const { - queueSongIds, - queueHistorySongIds, - shuffleEnabled, - repeatEnabled, toggleShuffle, cycleRepeat, clearHistory, reorderQueue, skipToQueueIndex, skipToHistoryIndex, - } = usePlayback() + } = usePlaybackActions() const [viewportWidth, setViewportWidth] = useState(0) const swipeGroup = useSwipeRowGroup() const [scrollEnabled, setScrollEnabled] = useState(true) @@ -307,100 +305,126 @@ export function NowPlayingQueue({ [drag] ) - const renderItem = ({ item }: { item: QueueListItem }) => { - switch (item.type) { - case "history-header": - return ( - - - History - - void clearHistory()} hitSlop={10}> - - Clear - - - - ) - case "history": - return ( - - ) - case "current": - return {currentHeader} - case "controls": - return ( - - {!tablet ? ( - - - - - ) : null} - {item.showTitle ? ( + const lastIndex = queueSongIds.length - 1 + const renderItem = useCallback( + ({ item }: { item: QueueListItem }) => { + switch (item.type) { + case "history-header": + return ( + - Continue Playing + History - ) : null} - - ) - case "upcoming": - return ( - - ) - case "empty": - return ( - - void clearHistory()} hitSlop={10}> + + Clear + + + + ) + case "history": + return ( + + ) + case "current": + return {currentHeader} + case "controls": + return ( + - Nothing else is queued. - - - ) - } - } + {!tablet ? ( + + + + + ) : null} + {item.showTitle ? ( + + Continue Playing + + ) : null} + + ) + case "upcoming": + return ( + + ) + case "empty": + return ( + + + Nothing else is queued. + + + ) + } + }, + [ + clearHistory, + colors, + currentHeader, + cycleRepeat, + drag, + handleDragStart, + handleDrop, + handleRemove, + lastIndex, + repeatEnabled, + shuffleEnabled, + skipToHistoryIndex, + skipToQueueIndex, + swipeGroup, + tablet, + toggleShuffle, + ] + ) return ( +}) { + const { currentTime, duration } = usePlaybackProgress() + const { seekTo } = usePlaybackActions() + const [scrubTime, setScrubTime] = useState(null) + const time = scrubTime ?? currentTime + const timeColor = + scrubTime === null ? colors.secondaryForeground : colors.foreground + + return ( + <> + { + void seekTo(value) + setScrubTime(null) + }} + /> + + + {formatDuration(time)} + + {center ? ( + + {center} + + ) : null} + + {formatRemainingDuration(time, duration).replace("-", "−")} + + + + ) +} + +const styles = StyleSheet.create({ + row: { + flexDirection: "row", + alignItems: "center", + justifyContent: "space-between", + marginTop: -4, + }, + center: { + position: "absolute", + left: 0, + right: 0, + alignItems: "center", + }, + time: { fontSize: 12, fontVariant: ["tabular-nums"] }, +}) diff --git a/apps/mobile/components/tablet-now-playing.tsx b/apps/mobile/components/tablet-now-playing.tsx index 64213d3..39ebaae 100644 --- a/apps/mobile/components/tablet-now-playing.tsx +++ b/apps/mobile/components/tablet-now-playing.tsx @@ -1,11 +1,5 @@ import { useEffect, useState, type ComponentProps, type ReactNode } from "react" -import { - Pressable, - StyleSheet, - Text, - View, - useWindowDimensions, -} from "react-native" +import { Pressable, StyleSheet, View, useWindowDimensions } from "react-native" import Animated, { Easing, ReduceMotion, @@ -14,7 +8,7 @@ import Animated, { useSharedValue, withTiming, } from "react-native-reanimated" -import { GestureDetector, Gesture } from "react-native-gesture-handler" +import { GestureDetector, type Gesture } from "react-native-gesture-handler" import { useSafeAreaInsets } from "react-native-safe-area-context" import { useRouter } from "expo-router" import { StatusBar } from "expo-status-bar" @@ -22,12 +16,12 @@ import { StatusBar } from "expo-status-bar" import { AudioOutputButton } from "@/components/audio-output-button" import { CoverImage } from "@/components/cover-image" import { NowPlayingQueue } from "@/components/now-playing-queue" +import { PlayerProgress } from "@/components/player-progress" import { PlayerSlider } from "@/components/player-slider" import { PlayerSymbol } from "@/components/player-symbol" -import { usePlayback } from "@/contexts/playback" +import { usePlaybackActions, usePlaybackQueue } from "@/contexts/playback" import { useServerConfig } from "@/contexts/server-config" import { useSystemVolume } from "@/hooks/use-system-volume" -import { formatDuration, formatRemainingDuration } from "@/lib/format" import type { NowPlayingColors } from "@/lib/now-playing-colors" import { albumCoverUrl } from "@/lib/urls" @@ -42,7 +36,7 @@ export function TabletNowPlaying({ colors, backgroundStyle, dismissStyle, - dismissGesture, + dismissGestures, showQueue, toggleQueue, metadata, @@ -50,7 +44,10 @@ export function TabletNowPlaying({ colors: NowPlayingColors backgroundStyle: ComponentProps["style"] dismissStyle: ComponentProps["style"] - dismissGesture: () => ReturnType + dismissGestures: { + handle: ReturnType + artwork: ReturnType + } showQueue: boolean toggleQueue: () => void metadata: ReactNode @@ -59,22 +56,11 @@ export function TabletNowPlaying({ const insets = useSafeAreaInsets() const { width, height } = useWindowDimensions() const { config } = useServerConfig() - const { - currentSong, - currentTime, - duration, - isPlaying, - setIsPlaying, - seekTo, - skipNext, - skipPrevious, - shuffleEnabled, - repeatEnabled, - toggleShuffle, - cycleRepeat, - } = usePlayback() + const { currentSong, isPlaying, shuffleEnabled, repeatEnabled } = + usePlaybackQueue() + const { setIsPlaying, skipNext, skipPrevious, toggleShuffle, cycleRepeat } = + usePlaybackActions() const { volume, setVolume, available: volumeAvailable } = useSystemVolume() - const [scrubTime, setScrubTime] = useState(null) const [queueHeight, setQueueHeight] = useState(0) const wideLayout = width >= 700 const sideBySide = showQueue && wideLayout @@ -113,7 +99,6 @@ export function TabletNowPlaying({ opacity: interpolate(progress.value, [0, 0.15, 1], [0, 0, 1]), transform: [{ translateX: (1 - progress.value) * 48 }], })) - const time = scrubTime ?? currentTime if (!currentSong || !config) return null const control = ( label: string, @@ -150,7 +135,7 @@ export function TabletNowPlaying({ return ( - + router.back()} accessibilityRole="button" @@ -164,7 +149,7 @@ export function TabletNowPlaying({ - + {metadata} - { - void seekTo(value) - setScrubTime(null) - }} - /> - - - {formatDuration(time)} - - - {formatRemainingDuration(time, duration).replace("-", "−")} - - + {control( "Shuffle", @@ -376,12 +337,6 @@ const styles = StyleSheet.create({ }, controls: { width: "100%", maxWidth: 456, paddingHorizontal: 0 }, meta: { height: 48 }, - times: { - flexDirection: "row", - justifyContent: "space-between", - marginTop: -4, - }, - time: { fontSize: 12, fontVariant: ["tabular-nums"] }, transport: { flexDirection: "row", alignItems: "center", diff --git a/apps/mobile/contexts/playback.tsx b/apps/mobile/contexts/playback.tsx index 96241e8..cc39427 100644 --- a/apps/mobile/contexts/playback.tsx +++ b/apps/mobile/contexts/playback.tsx @@ -137,6 +137,8 @@ type PlaybackContextValue = { type PlaybackActionsValue = Pick< PlaybackContextValue, + | "seekTo" + | "waitForPlaybackReady" | "setIsPlaying" | "playInOrder" | "playShuffled" @@ -176,14 +178,22 @@ type PlaybackQueueValue = Pick< | "repeatEnabled" > -const PlaybackContext = createContext(null) +type PlaybackProgressValue = Pick< + PlaybackContextValue, + "currentTime" | "duration" +> + const PlaybackActionsContext = createContext(null) const PlaybackQueueContext = createContext(null) +const PlaybackProgressContext = createContext( + null +) -export function usePlayback() { - const context = useContext(PlaybackContext) +/** Ticks while audio plays. Keep consumers small (slider and time labels). */ +export function usePlaybackProgress() { + const context = useContext(PlaybackProgressContext) if (!context) { - throw new Error("usePlayback must be used within PlaybackProvider") + throw new Error("usePlaybackProgress must be used within PlaybackProvider") } return context } @@ -304,6 +314,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { measuredDuration > 0 ? measuredDuration : (currentSong?.durationSeconds ?? 0) + const durationRef = useRef(duration) + durationRef.current = duration const queueSyncKey = useMemo( () => JSON.stringify(queueSongIds), [queueSongIds] @@ -543,18 +555,15 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { } }, []) - const seekTo = useCallback( - async (seconds: number) => { - const playlist = playlistRef.current - if (!playlist) return - const maxDuration = playlist.duration || duration || 0 - const clamped = Math.max(0, Math.min(seconds, maxDuration)) - await playlist.seekTo(clamped) - currentTimeRef.current = clamped - setCurrentTime(clamped) - }, - [duration] - ) + const seekTo = useCallback(async (seconds: number) => { + const playlist = playlistRef.current + if (!playlist) return + const maxDuration = playlist.duration || durationRef.current || 0 + const clamped = Math.max(0, Math.min(seconds, maxDuration)) + await playlist.seekTo(clamped) + currentTimeRef.current = clamped + setCurrentTime(clamped) + }, []) const saveProgress = useCallback( (seconds: number) => { @@ -1260,6 +1269,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { const actionsValue = useMemo( () => ({ + seekTo, + waitForPlaybackReady, setIsPlaying, playInOrder, playShuffled, @@ -1310,12 +1321,14 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { playPlaylistShuffled, playShuffled, reorderQueue, + seekTo, setIsPlaying, skipNext, skipPrevious, skipToHistoryIndex, skipToQueueIndex, toggleShuffle, + waitForPlaybackReady, ] ) @@ -1340,41 +1353,17 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { ] ) - const value = useMemo( - () => ({ - ...actionsValue, - waitForPlaybackReady, - queueSongIds, - queueHistorySongIds, - currentSong, - shuffleEnabled: playback.shuffleEnabled, - repeatEnabled, - isPlaying: isPlaybackActive, - currentTime, - duration, - seekTo, - }), - [ - actionsValue, - waitForPlaybackReady, - currentSong, - currentTime, - duration, - isPlaybackActive, - playback.shuffleEnabled, - queueHistorySongIds, - queueSongIds, - repeatEnabled, - seekTo, - ] + const progressValue = useMemo( + () => ({ currentTime, duration }), + [currentTime, duration] ) return ( - + {children} - + )