refactor star

This commit is contained in:
austinried
2022-03-20 09:33:15 +09:00
parent 1803e9dc7c
commit a15159014c
10 changed files with 122 additions and 146 deletions

View File

@@ -1,35 +1,63 @@
import { Store, useStore, useStoreDeep } from '@app/state/store'
import { useStore } from '@app/state/store'
import { StarParams } from '@app/subsonic/params'
import { useCallback, useEffect } from 'react'
export const useArtistInfo = (id: string) => {
const artistInfo = useStoreDeep(useCallback(store => store.entities.artistInfo[id], [id]))
const fetchArtistInfo = useStore(store => store.fetchLibraryArtistInfo)
type StarrableItem = 'album' | 'artist' | 'song'
useEffect(() => {
if (!artistInfo) {
fetchArtistInfo(id)
}
}, [artistInfo, fetchArtistInfo, id])
function starParams(id: string, type: StarrableItem): StarParams {
const params: StarParams = {}
if (type === 'album') {
params.albumId = id
} else if (type === 'artist') {
params.artistId = id
} else {
params.id = id
}
return artistInfo
return params
}
export const useStarred = (id: string, type: string) => {
return useStore(
export const useStar = (id: string, type: StarrableItem) => {
const fetchAlbum = useStore(store => store.fetchLibraryAlbum)
const fetchArtist = useStore(store => store.fetchLibraryArtist)
const fetchSong = useStore(store => store.fetchLibrarySong)
const _starred = useStore(
useCallback(
(state: Store) => {
switch (type) {
case 'song':
return state.starredSongs[id]
case 'album':
return state.starredAlbums[id]
case 'artist':
return state.starredArtists[id]
default:
return false
store => {
if (type === 'album') {
return store.entities.albums[id] ? !!store.entities.albums[id].starred : null
} else if (type === 'artist') {
return store.entities.artists[id] ? !!store.entities.artists[id].starred : null
} else {
return store.entities.songs[id] ? !!store.entities.songs[id].starred : null
}
},
[type, id],
[id, type],
),
)
useEffect(() => {
if (_starred === null) {
if (type === 'album') {
fetchAlbum(id)
} else if (type === 'artist') {
fetchArtist(id)
} else {
fetchSong(id)
}
}
}, [fetchAlbum, fetchArtist, fetchSong, id, _starred, type])
const starred = !!_starred
const _star = useStore(store => store.star)
const _unstar = useStore(store => store.unstar)
const star = useCallback(() => _star(starParams(id, type)), [_star, id, type])
const unstar = useCallback(() => _unstar(starParams(id, type)), [_unstar, id, type])
const toggleStar = useCallback(() => (starred ? unstar() : star()), [star, starred, unstar])
return { star, unstar, toggleStar, starred }
}