|
| 1 | +import React, { useState } from 'react'; |
| 2 | +import PropTypes from 'prop-types'; |
| 3 | +import MainSlider from '../components/MainSlider.tsx'; |
| 4 | +import Dropdown from '../components/Dropdown.tsx'; |
| 5 | +import { |
| 6 | + playForward, pause, startPlaying, moveForward, moveBackward, resetSlider, |
| 7 | +} from '../actions/actions.ts'; |
| 8 | +import { useStoreContext } from '../store.tsx'; |
| 9 | + |
| 10 | +const speeds = [ |
| 11 | + { value: 2000, label: '0.5x' }, |
| 12 | + { value: 1000, label: '1.0x' }, |
| 13 | + { value: 500, label: '2.0x' }, |
| 14 | +]; |
| 15 | + |
| 16 | +// start slider movement |
| 17 | +function play(speed, playing, dispatch, snapshotsLength, sliderIndex) { |
| 18 | + if (playing) { |
| 19 | + dispatch(pause()); |
| 20 | + } else { |
| 21 | + let currentIndex = sliderIndex; |
| 22 | + if (currentIndex === snapshotsLength - 1) { |
| 23 | + // dispatch action to reset the slider |
| 24 | + dispatch(resetSlider()); |
| 25 | + currentIndex = 0; |
| 26 | + } |
| 27 | + const intervalId = setInterval(() => { |
| 28 | + if (currentIndex < snapshotsLength - 1) { |
| 29 | + dispatch(playForward()); |
| 30 | + currentIndex += 1; |
| 31 | + } else { |
| 32 | + dispatch(pause()); |
| 33 | + } |
| 34 | + }, speed); |
| 35 | + dispatch(startPlaying(intervalId)); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +function TravelContainer({ snapshotsLength }) { |
| 40 | + const [selectedSpeed, setSpeed] = useState(speeds[1]); |
| 41 | + const [{ tabs, currentTab }, dispatch] = useStoreContext(); |
| 42 | + const { sliderIndex, playing } = tabs[currentTab]; |
| 43 | + |
| 44 | + return ( |
| 45 | + <div className="travel-container"> |
| 46 | + <button |
| 47 | + className="play-button" |
| 48 | + type="button" |
| 49 | + onClick={() => play(selectedSpeed.value, playing, dispatch, snapshotsLength, sliderIndex)} |
| 50 | + > |
| 51 | + {playing ? 'Pause' : 'Play'} |
| 52 | + </button> |
| 53 | + <MainSlider snapshotsLength={snapshotsLength} sliderIndex={sliderIndex} dispatch={dispatch} /> |
| 54 | + <button className="backward-button" onClick={() => dispatch(moveBackward())} type="button"> |
| 55 | + {'<'} |
| 56 | + </button> |
| 57 | + <button className="forward-button" onClick={() => dispatch(moveForward())} type="button"> |
| 58 | + {'>'} |
| 59 | + </button> |
| 60 | + <Dropdown speeds={speeds} selectedSpeed={selectedSpeed} setSpeed={setSpeed} /> |
| 61 | + </div> |
| 62 | + ); |
| 63 | +} |
| 64 | + |
| 65 | +TravelContainer.propTypes = { |
| 66 | + snapshotsLength: PropTypes.number.isRequired, |
| 67 | +}; |
| 68 | + |
| 69 | +export default TravelContainer; |
0 commit comments