From d45e4bac0621635ab0505cf5c8ff4de5eb750cb5 Mon Sep 17 00:00:00 2001 From: Whitewater Date: Sat, 19 Jul 2025 15:14:34 +0800 Subject: [PATCH] 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 --- .../src/components/ui/video/PlayerAction.tsx | 32 ++++++++----- .../src/components/ui/video/VideoPlayer.tsx | 3 +- apps/mobile/src/lib/player.ts | 32 ++++++------- .../mobile/src/modules/context-menu/feeds.tsx | 6 +-- .../entry-list/EntryListContentArticle.tsx | 7 +-- .../entry-list/EntryListContentSocial.tsx | 2 +- .../entry-list/templates/EntryNormalItem.tsx | 45 ++++++++----------- apps/mobile/src/modules/entry-list/types.ts | 1 - 8 files changed, 61 insertions(+), 67 deletions(-) diff --git a/apps/mobile/src/components/ui/video/PlayerAction.tsx b/apps/mobile/src/components/ui/video/PlayerAction.tsx index 75b0884b0..88d324e2e 100644 --- a/apps/mobile/src/components/ui/video/PlayerAction.tsx +++ b/apps/mobile/src/components/ui/video/PlayerAction.tsx @@ -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 = + switch (mediaState) { + case "playing": { + playButtonIcon = + break + } + case "loading": { + playButtonIcon = + break + } + } + return ( - {isPlaying ? ( - - ) : isLoading ? ( - - ) : ( - - )} + {playButtonIcon} ) diff --git a/apps/mobile/src/components/ui/video/VideoPlayer.tsx b/apps/mobile/src/components/ui/video/VideoPlayer.tsx index 183f33efc..8b17cb82d 100644 --- a/apps/mobile/src/components/ui/video/VideoPlayer.tsx +++ b/apps/mobile/src/components/ui/video/VideoPlayer.tsx @@ -73,8 +73,7 @@ export function VideoPlayer({ {status !== "readyToPlay" && {placeholder}} diff --git a/apps/mobile/src/lib/player.ts b/apps/mobile/src/lib/player.ts index cf11380c2..31cf60e0e 100644 --- a/apps/mobile/src/lib/player.ts +++ b/apps/mobile/src/lib/player.ts @@ -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 { diff --git a/apps/mobile/src/modules/context-menu/feeds.tsx b/apps/mobile/src/modules/context-menu/feeds.tsx index 95684ae35..48c2967f4 100644 --- a/apps/mobile/src/modules/context-menu/feeds.tsx +++ b/apps/mobile/src/modules/context-menu/feeds.tsx @@ -403,11 +403,7 @@ const PreviewFeeds = (props: { id: string; view: FeedViewType }) => { const renderItem = useCallback( ({ item: id }: ListRenderItemInfo) => ( - + ), [props.view], ) diff --git a/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx b/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx index d5b6eda81..33171b662 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx @@ -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 | 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() diff --git a/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx b/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx index f71aabe8e..ae7c882fc 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx @@ -25,7 +25,7 @@ export const EntryListContentSocial = ({ ref?: React.Ref | 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!) diff --git a/apps/mobile/src/modules/entry-list/templates/EntryNormalItem.tsx b/apps/mobile/src/modules/entry-list/templates/EntryNormalItem.tsx index 601d4c371..931074943 100644 --- a/apps/mobile/src/modules/entry-list/templates/EntryNormalItem.tsx +++ b/apps/mobile/src/modules/entry-list/templates/EntryNormalItem.tsx @@ -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 !== FeedViewType.Notifications && ( - - )} + {view !== FeedViewType.Notifications && } ) @@ -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) @@ -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 && } - {(video || audio) && ( - - )} + {(video || audio) && } ) } diff --git a/apps/mobile/src/modules/entry-list/types.ts b/apps/mobile/src/modules/entry-list/types.ts index 271b4cd35..8fb9106c9 100644 --- a/apps/mobile/src/modules/entry-list/types.ts +++ b/apps/mobile/src/modules/entry-list/types.ts @@ -1,4 +1,3 @@ export type EntryExtraData = { - playingAudioUrl: string | null entryIds: string[] | null }