refactor: simplify audio state handling (#4188)

* chore: allow pause audio when playing

* refactor: update PlayerAction props to use state instead of isPlaying and isLoading

* refactor: remove playingAudioUrl from EntryExtraData

* refactor: simplify audio state

* refactor: simplify audio state handling

* chore: review
This commit is contained in:
Whitewater
2025-07-19 15:14:34 +08:00
committed by GitHub
parent 7a4b7554e0
commit d45e4bac06
8 changed files with 61 additions and 67 deletions
@@ -6,12 +6,17 @@ import { ThemedBlurView } from "@/src/components/common/ThemedBlurView"
import { PlatformActivityIndicator } from "@/src/components/ui/loading/PlatformActivityIndicator"
import { PauseCuteFiIcon } from "@/src/icons/pause_cute_fi"
import { PlayCuteFiIcon } from "@/src/icons/play_cute_fi"
import type { SimpleMediaState } from "@/src/lib/player"
import { NativePressable } from "../pressable/NativePressable"
interface PlayerActionProps {
isPlaying: boolean
isLoading?: boolean
/**
* This is the state of the media instead of the play button.
*
* When the media is paused, the play button should be shown.
*/
mediaState: SimpleMediaState
onPress: () => void
className?: string
iconSize?: number
@@ -19,8 +24,7 @@ interface PlayerActionProps {
}
export function PlayerAction({
isPlaying,
isLoading = false,
mediaState,
onPress,
className = "",
iconSize = 24,
@@ -30,6 +34,18 @@ export function PlayerAction({
onPress()
}, [onPress])
let playButtonIcon = <PlayCuteFiIcon color="white" width={iconSize} height={iconSize} />
switch (mediaState) {
case "playing": {
playButtonIcon = <PauseCuteFiIcon color="white" width={iconSize} height={iconSize} />
break
}
case "loading": {
playButtonIcon = <PlatformActivityIndicator />
break
}
}
return (
<NativePressable
className={cn("absolute inset-0 flex items-center justify-center", className)}
@@ -41,13 +57,7 @@ export function PlayerAction({
intensity={30}
experimentalBlurMethod="none"
/>
{isPlaying ? (
<PauseCuteFiIcon color="white" width={iconSize} height={iconSize} />
) : isLoading ? (
<PlatformActivityIndicator />
) : (
<PlayCuteFiIcon color="white" width={iconSize} height={iconSize} />
)}
{playButtonIcon}
</View>
</NativePressable>
)
@@ -73,8 +73,7 @@ export function VideoPlayer({
{status !== "readyToPlay" && <View className="absolute inset-0">{placeholder}</View>}
<PlayerAction
iconSize={32}
isPlaying={false}
isLoading={status !== "readyToPlay"}
mediaState={status === "readyToPlay" ? "paused" : "loading"}
onPress={handlePressPlay}
/>
</View>
+17 -15
View File
@@ -1,28 +1,30 @@
import type { AttachmentsModel } from "@follow/database/schemas/types"
import { atom, useAtom } from "jotai"
import { useCallback, useEffect } from "react"
import TrackPlayer, { State, useActiveTrack, usePlaybackState } from "react-native-track-player"
import TrackPlayer, { useActiveTrack, useIsPlaying } from "react-native-track-player"
import { PlayerRegistered } from "../initialize/player"
import { toast } from "./toast"
const LOADING_SUFFIX = "_loading"
export type SimpleMediaState = "playing" | "paused" | "loading"
export function usePlayingUrl() {
/**
* Learn more https://rntp.dev/docs/guides/play-button
*/
export function useAudioPlayState(audioUrl?: string): SimpleMediaState {
const playState = useIsPlaying()
const activeTrack = useActiveTrack()
const playerState = usePlaybackState()
const isPlaying = !!activeTrack?.url && playerState.state === State.Playing
const isLoading = playerState.state === State.Buffering || playerState.state === State.Loading
return isPlaying ? activeTrack?.url : isLoading ? `${activeTrack?.url}${LOADING_SUFFIX}` : null
}
const playingUrl = activeTrack?.url
export function getAttachmentState(playingUrl?: string, attachment?: AttachmentsModel) {
if (!playingUrl || !attachment || !attachment.mime_type?.startsWith("audio/")) {
return null
const isCurrentTrack = !audioUrl || playingUrl === audioUrl
if (!playingUrl || !isCurrentTrack) {
// By default the audio should be in "paused" state
return "paused"
}
const isPlaying = attachment.url === playingUrl
const isLoading = playingUrl === `${attachment.url}${LOADING_SUFFIX}`
return isPlaying ? "playing" : isLoading ? "loading" : null
if (playState.bufferingDuringPlay === true) {
return "loading"
}
return playState.playing ? "playing" : "paused"
}
class Player {
@@ -403,11 +403,7 @@ const PreviewFeeds = (props: { id: string; view: FeedViewType }) => {
const renderItem = useCallback(
({ item: id }: ListRenderItemInfo<string>) => (
<EntryNormalItem
entryId={id}
extraData={{ entryIds: null, playingAudioUrl: null }}
view={props.view}
/>
<EntryNormalItem entryId={id} extraData={{ entryIds: null }} view={props.view} />
),
[props.view],
)
@@ -7,7 +7,6 @@ import { View } from "react-native"
import { useActionLanguage, useGeneralSettingKey } from "@/src/atoms/settings/general"
import { useBottomTabBarHeight } from "@/src/components/layouts/tabbar/hooks"
import { usePlayingUrl } from "@/src/lib/player"
import { checkLanguage } from "@/src/lib/translation"
import { useHeaderHeight } from "@/src/modules/screen/hooks/useHeaderHeight"
@@ -27,11 +26,7 @@ export const EntryListContentArticle = ({
}: { entryIds: string[] | null; active?: boolean; view: FeedViewType } & {
ref?: React.Ref<ElementRef<typeof TimelineSelectorList> | null>
}) => {
const playingAudioUrl = usePlayingUrl()
const extraData: EntryExtraData = useMemo(
() => ({ playingAudioUrl, entryIds }),
[playingAudioUrl, entryIds],
)
const extraData: EntryExtraData = useMemo(() => ({ entryIds }), [entryIds])
const { fetchNextPage, isFetching, refetch, isRefetching, hasNextPage, fetchedTime, isReady } =
useEntries()
@@ -25,7 +25,7 @@ export const EntryListContentSocial = ({
ref?: React.Ref<ElementRef<typeof TimelineSelectorList> | null>
}) => {
const { fetchNextPage, isFetching, refetch, isRefetching, hasNextPage, isReady } = useEntries()
const extraData: EntryExtraData = useMemo(() => ({ playingAudioUrl: null, entryIds }), [entryIds])
const extraData: EntryExtraData = useMemo(() => ({ entryIds }), [entryIds])
const { onScroll: hackOnScroll, ref, style: hackStyle } = usePagerListPerformanceHack()
useImperativeHandle(forwardRef, () => ref.current!)
@@ -22,7 +22,8 @@ import { ItemPressable } from "@/src/components/ui/pressable/ItemPressable"
import { PlayerAction } from "@/src/components/ui/video/PlayerAction"
import { useNavigation } from "@/src/lib/navigation/hooks"
import { isIOS } from "@/src/lib/platform"
import { getAttachmentState, player } from "@/src/lib/player"
import { player, useAudioPlayState } from "@/src/lib/player"
import { toast } from "@/src/lib/toast"
import { EntryDetailScreen } from "@/src/screens/(stack)/entries/[entryId]/EntryDetailScreen"
import { EntryItemContextMenu } from "../../context-menu/entry"
@@ -153,9 +154,7 @@ export const EntryNormalItem = memo(
/>
)}
</View>
{view !== FeedViewType.Notifications && (
<ThumbnailImage entryId={entryId} playingAudioUrl={extraData.playingAudioUrl} />
)}
{view !== FeedViewType.Notifications && <ThumbnailImage entryId={entryId} />}
</ItemPressable>
</EntryItemContextMenu>
)
@@ -164,13 +163,7 @@ export const EntryNormalItem = memo(
EntryNormalItem.displayName = "EntryNormalItem"
const ThumbnailImage = ({
playingAudioUrl,
entryId,
}: {
playingAudioUrl: string | null
entryId: string
}) => {
const ThumbnailImage = ({ entryId }: { entryId: string }) => {
const entry = useEntry(entryId, (state) => ({
feedId: state.feedId,
media: state.media,
@@ -188,9 +181,7 @@ const ThumbnailImage = ({
const blurhash = mediaModel?.blurhash
const audio = entry?.attachments?.find((attachment) => attachment.mime_type?.startsWith("audio/"))
const audioState = getAttachmentState(playingAudioUrl ?? undefined, audio)
const isPlaying = audioState === "playing"
const isLoading = audioState === "loading"
const audioState = useAudioPlayState(audio?.url)
const video = mediaModel?.type === "video" ? mediaModel : null
const videoViewRef = useRef<null | VideoView>(null)
@@ -212,18 +203,22 @@ const ThumbnailImage = ({
return
}
if (!audio) return
if (isLoading) return
if (isPlaying) {
if (audioState !== "paused") {
player.pause()
return
}
player.play({
url: audio.url,
title: entry?.title,
artist: feed?.title,
artwork: image,
})
}, [audio, entry?.title, feed?.title, image, isLoading, isPlaying, video, videoPlayer])
try {
player.play({
url: audio.url,
title: entry?.title,
artist: feed?.title,
artwork: image,
})
} catch (error) {
console.error("Error playing audio:", error)
toast.error("Failed to play audio")
}
}, [audio, audioState, entry?.title, feed?.title, image, video, videoPlayer])
const [imageError, setImageError] = useState(audio && !image)
const handleImageError = useCallback(() => {
@@ -275,9 +270,7 @@ const ThumbnailImage = ({
{/* Show feed icon if no image but audio is present */}
{imageError && <FeedIcon feed={feed} size={96} />}
{(video || audio) && (
<PlayerAction isPlaying={isPlaying} isLoading={isLoading} onPress={handlePressPlay} />
)}
{(video || audio) && <PlayerAction mediaState={audioState} onPress={handlePressPlay} />}
</View>
)
}
@@ -1,4 +1,3 @@
export type EntryExtraData = {
playingAudioUrl: string | null
entryIds: string[] | null
}