2019-12-13 08:28:28 +01:00
|
|
|
import React, { useState, useEffect, useRef } from 'react'
|
2019-12-13 02:05:04 +01:00
|
|
|
|
2019-12-13 08:28:28 +01:00
|
|
|
import { FaPlay, FaPause, FaStop } from 'react-icons/fa'
|
2019-12-13 02:05:04 +01:00
|
|
|
|
2019-12-13 08:28:28 +01:00
|
|
|
function safeCall(fn) {
|
|
|
|
typeof fn === 'function' && fn()
|
|
|
|
}
|
2019-12-13 02:05:04 +01:00
|
|
|
|
2019-12-13 08:28:28 +01:00
|
|
|
export const Player = ({ onTick, onStart, onStop, onPause, delay }) => {
|
|
|
|
const [isRunning, start, stop] = usePlayer(stop => onTick(stop), delay)
|
|
|
|
|
|
|
|
const handleStart = () => {
|
|
|
|
safeCall(onStart)
|
|
|
|
start()
|
|
|
|
}
|
|
|
|
|
|
|
|
const handleStop = () => {
|
|
|
|
safeCall(onStop)
|
|
|
|
stop()
|
|
|
|
}
|
|
|
|
|
|
|
|
const handlePause = () => {
|
|
|
|
safeCall(onPause)
|
|
|
|
stop()
|
|
|
|
}
|
2019-12-13 02:05:04 +01:00
|
|
|
|
|
|
|
return (
|
|
|
|
<div>
|
2019-12-13 08:28:28 +01:00
|
|
|
<button onClick={handleStop}>
|
|
|
|
<FaStop />
|
|
|
|
</button>
|
|
|
|
{isRunning && (
|
|
|
|
<button onClick={handlePause}>
|
|
|
|
<FaPause />
|
|
|
|
</button>
|
|
|
|
)}{' '}
|
|
|
|
{!isRunning && (
|
|
|
|
<button onClick={handleStart}>
|
|
|
|
<FaPlay />
|
|
|
|
</button>
|
|
|
|
)}
|
2019-12-13 02:05:04 +01:00
|
|
|
</div>
|
|
|
|
)
|
|
|
|
}
|
2019-12-13 08:28:28 +01:00
|
|
|
|
|
|
|
function usePlayer(onTick, delay) {
|
|
|
|
const [isRunning, setRunning] = useState(false)
|
|
|
|
const start = () => setRunning(true)
|
|
|
|
const stop = () => setRunning(false)
|
|
|
|
|
|
|
|
useInterval(() => onTick(stop), isRunning ? delay : null)
|
|
|
|
return [isRunning, start, stop]
|
|
|
|
}
|
|
|
|
|
|
|
|
// from: https://overreacted.io/making-setinterval-declarative-with-react-hooks/
|
|
|
|
function useInterval(callback, delay) {
|
|
|
|
const savedCallback = useRef()
|
|
|
|
|
|
|
|
// Remember the latest callback.
|
|
|
|
useEffect(() => {
|
|
|
|
savedCallback.current = callback
|
|
|
|
}, [callback])
|
|
|
|
|
|
|
|
// Set up the interval.
|
|
|
|
useEffect(() => {
|
|
|
|
function tick() {
|
|
|
|
savedCallback.current()
|
|
|
|
}
|
|
|
|
if (delay !== null) {
|
|
|
|
let id = setInterval(tick, delay)
|
|
|
|
return () => clearInterval(id)
|
|
|
|
}
|
|
|
|
}, [delay])
|
|
|
|
}
|