queue.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { useThrottleCallback } from '@react-hook/throttle';
  2. import { AxiosInstance, AxiosResponse } from 'axios';
  3. import { Dispatch, useCallback, useContext, useEffect } from 'react';
  4. import { LocalAction, queueShifted, songInfoFetched, stateSet } from '../actions';
  5. import { DispatchContext, StateContext } from '../context/state';
  6. import { NullSong, Song, songExists } from '../types';
  7. import { getApiUrl } from '../utils/url';
  8. import { useRequestCallback } from './request';
  9. function useNextOrPrevSong(
  10. key: 'next' | 'prev',
  11. dispatch: Dispatch<LocalAction>,
  12. ): [(songId: number) => void, boolean] {
  13. const sendRequest = useCallback(
  14. (axios: AxiosInstance, id: number): Promise<AxiosResponse<Song | NullSong>> =>
  15. axios.get(`${getApiUrl()}/${key}-song?id=${id}`),
  16. [key],
  17. );
  18. const [onRequest, response, loading] = useRequestCallback<number, Song | NullSong>({
  19. sendRequest,
  20. });
  21. useEffect(() => {
  22. if (response) {
  23. if (songExists(response)) {
  24. dispatch(songInfoFetched(response, true));
  25. } else {
  26. dispatch(stateSet({ songId: null, playing: false, seekTime: -1 }));
  27. }
  28. }
  29. }, [dispatch, response]);
  30. const debouncedRequest = useThrottleCallback(onRequest, 5, true);
  31. return [debouncedRequest, loading];
  32. }
  33. export function usePlayQueue(): {
  34. onNext: () => void;
  35. onPrev: () => void;
  36. loading: boolean;
  37. } {
  38. const dispatch = useContext(DispatchContext);
  39. const {
  40. player: { queue, songId },
  41. } = useContext(StateContext);
  42. const [onRequestNext, loadingNext] = useNextOrPrevSong('next', dispatch);
  43. const [onRequestPrev, loadingPrev] = useNextOrPrevSong('prev', dispatch);
  44. const loading = loadingNext || loadingPrev;
  45. const firstQueuedSongId = queue[0];
  46. const onNext = useCallback(() => {
  47. if (firstQueuedSongId) {
  48. dispatch(queueShifted());
  49. } else if (!loading && songId) {
  50. onRequestNext(songId);
  51. }
  52. }, [dispatch, firstQueuedSongId, songId, loading, onRequestNext]);
  53. const onPrev = useCallback(() => {
  54. if (!loading && songId) {
  55. onRequestPrev(songId);
  56. }
  57. }, [songId, loading, onRequestPrev]);
  58. return { onNext, onPrev, loading };
  59. }