index.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { jwtDecode } from '../App'
  2. export function authReducer(state, { type, token }) {
  3. if (!state) {
  4. if (localStorage.authToken) {
  5. type = 'AUTH_LOGIN'
  6. token = localStorage.authToken
  7. } else {
  8. return {}
  9. }
  10. }
  11. if (type === 'AUTH_LOGIN') {
  12. let auth = jwtDecode(token)
  13. if (auth) {
  14. localStorage.authToken = token
  15. return { token, payload: auth }
  16. }
  17. }
  18. if (type === 'AUTH_LOGOUT') {
  19. localStorage.authToken = ''
  20. return {}
  21. }
  22. return state
  23. }
  24. export function promiseReducer(state = {}, { type, name, status, payload, error }) {
  25. if (type === 'PROMISE') {
  26. return {
  27. ...state,
  28. [name]: { status, payload: (state === 'PENDING' && state[name] && state[name].payload) || payload, error }
  29. }
  30. }
  31. return state
  32. }
  33. export function playerReducer(state, { type, track, playlist, duration, currentTime, volume, playlistIndex }) {
  34. if (!state || type === 'EJECT_TRACK') return {}
  35. if (type === 'PLAY_TRACK') return { ...state, 'isPlaying': true }
  36. if (type === 'PAUSE_TRACK') return { ...state, 'isPlaying': false, 'currentTime': currentTime }
  37. if (type === 'SET_CURRTIME') {
  38. console.log('set_currtime')
  39. return { ...state, 'currentTime': currentTime }
  40. }
  41. if (type === 'SET_DURATION') {
  42. console.log('SET_DURATION')
  43. return { ...state, 'duration': duration }
  44. }
  45. if (type === 'SET_VOLUME') return { ...state, 'volume': volume }
  46. if (type === 'SET_PLAYLIST') { return { ...state, 'playlist': playlist} }
  47. if (type === 'SET_INDEX') { return { ...state, 'playlistIndex': playlistIndex} }
  48. if (type === 'SET_TRACK') {
  49. return {
  50. isPlaying: false,
  51. track: track,
  52. playlist: playlist,
  53. duration: duration, //общая длительность трека
  54. currentTime: currentTime,// текущая позиция в треке
  55. volume: volume,
  56. //playlistIndex: playlist.indexOf(track)
  57. playlistIndex:
  58. playlist.constructor.name === 'Array'? playlist.indexOf(track) : playlist.tracks.indexOf(track)
  59. }
  60. }
  61. return state
  62. }
  63. export const localStoreReducer = (reducer, localStorageName) => {
  64. return (
  65. (state, action) => {
  66. let newState
  67. if (!state && localStorage.getItem(localStorageName)) {
  68. newState = JSON.parse(localStorage.getItem(localStorageName))
  69. console.log(newState)
  70. } else {
  71. newState = reducer(state, action)
  72. localStorage.setItem(localStorageName, JSON.stringify(newState))
  73. }
  74. return newState
  75. }
  76. )
  77. }