queue.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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' | 'shuffle',
  11. dispatch: Dispatch<LocalAction>,
  12. ): [(songId: number | null) => void, boolean] {
  13. const sendRequest = useCallback(
  14. (axios: AxiosInstance, id: number | null): Promise<AxiosResponse<Song | NullSong>> =>
  15. axios.get(`${getApiUrl()}/${key}-song${id === null ? '' : `?id=${id}`}`),
  16. [key],
  17. );
  18. const [onRequest, response, loading] = useRequestCallback<number | null, 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. shuffleMode: boolean,
  35. ): {
  36. onNext: () => void;
  37. onPrev: () => void;
  38. loading: boolean;
  39. } {
  40. const dispatch = useContext(DispatchContext);
  41. const {
  42. player: { queue, songId },
  43. } = useContext(StateContext);
  44. const [onRequestNext, loadingNext] = useNextOrPrevSong(
  45. shuffleMode ? 'shuffle' : 'next',
  46. dispatch,
  47. );
  48. const [onRequestPrev, loadingPrev] = useNextOrPrevSong('prev', dispatch);
  49. const loading = loadingNext || loadingPrev;
  50. const firstQueuedSongId = queue[0];
  51. const onNext = useCallback(() => {
  52. if (firstQueuedSongId) {
  53. dispatch(queueShifted());
  54. } else if (!loading && songId) {
  55. onRequestNext(songId);
  56. }
  57. }, [dispatch, firstQueuedSongId, songId, loading, onRequestNext]);
  58. const onPrev = useCallback(() => {
  59. if (!loading && songId) {
  60. onRequestPrev(songId);
  61. }
  62. }, [songId, loading, onRequestPrev]);
  63. return { onNext, onPrev, loading };
  64. }