-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Create usePlayer hook and refactor App component
- Separate all player logic and state into usePlayer hook - Refactor App component to use usePlayer hook
- Loading branch information
1 parent
555441d
commit a7cc45c
Showing
2 changed files
with
59 additions
and
29 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import { useRef, useState } from 'react' | ||
|
||
import { useMediaRemote, useMediaStore, type MediaPlayerInstance } from '@vidstack/react' | ||
|
||
export default function usePlayer() { | ||
const player = useRef<MediaPlayerInstance>(null) | ||
const remote = useMediaRemote(player) | ||
|
||
const { paused, currentTime, duration, canPlay } = useMediaStore(player) | ||
|
||
const [playerSource, setPlayerSource] = useState<string | File>('') | ||
|
||
const pausePlayer = () => remote.pause() | ||
const resetPlayerCurrentTime = () => remote.seek(0) | ||
|
||
async function resetPlayer(): Promise<void> { | ||
const playerReset = paused && currentTime === 0 | ||
if (!playerReset) { | ||
pausePlayer() | ||
resetPlayerCurrentTime() | ||
if (playerSource instanceof File) { | ||
await new Promise((resolve) => { | ||
setPlayerSource('') | ||
resolve(true) | ||
}) | ||
setPlayerSource(playerSource) | ||
} | ||
} | ||
} | ||
|
||
return { | ||
player, | ||
playerPaused: paused, | ||
playerCurrentTime: currentTime, | ||
playerDuration: duration, | ||
playerCanPlay: canPlay, | ||
playerSource, | ||
setPlayerSource, | ||
resumePlayer: () => remote.play(), | ||
pausePlayer, | ||
resetPlayerCurrentTime, | ||
resetPlayer, | ||
} | ||
} |