216 lines
6.3 KiB
TypeScript
216 lines
6.3 KiB
TypeScript
import type { OptimisticUpdate } from "convex/browser"
|
|
import { useMutation, type ReactMutation } from "convex/react"
|
|
import type { FunctionArgs, FunctionReference } from "convex/server"
|
|
import {
|
|
createContext,
|
|
useCallback,
|
|
useContext,
|
|
useMemo,
|
|
useRef,
|
|
type ReactNode,
|
|
} from "react"
|
|
|
|
import { useCachedQuery } from "@/hooks/use-cached-query"
|
|
import { api } from "@otunes/convex/_generated/api"
|
|
import { favoriteOptimisticUpdates } from "@otunes/convex/client/favorites"
|
|
import type { Id } from "@otunes/convex/_generated/dataModel"
|
|
import { showError } from "@/lib/toast"
|
|
|
|
/**
|
|
* `useMutation(...).withOptimisticUpdate(...)` with a stable identity. Pass a
|
|
* module-level update so it does not change between renders.
|
|
*/
|
|
function useOptimisticMutation<Mutation extends FunctionReference<"mutation">>(
|
|
mutation: Mutation,
|
|
optimisticUpdate: OptimisticUpdate<FunctionArgs<Mutation>>
|
|
): ReactMutation<Mutation> {
|
|
const base = useMutation(mutation)
|
|
return useMemo(
|
|
() => base.withOptimisticUpdate(optimisticUpdate),
|
|
[base, optimisticUpdate]
|
|
)
|
|
}
|
|
|
|
type FavoriteTables = { song: "songs"; album: "albums"; artist: "artists" }
|
|
export type FavoriteKind = keyof FavoriteTables
|
|
|
|
type FavoritesContextValue = {
|
|
isSongFavorite: (songId: string) => boolean
|
|
isAlbumFavorite: (albumId: string) => boolean
|
|
isArtistFavorite: (artistId: string) => boolean
|
|
toggleSongFavorite: (songId: Id<"songs">) => Promise<void>
|
|
toggleAlbumFavorite: (albumId: Id<"albums">) => Promise<void>
|
|
toggleArtistFavorite: (artistId: Id<"artists">) => Promise<void>
|
|
favoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
|
|
/** Idempotent; throws so callers like Siri can report failures. */
|
|
setFavorite: <Kind extends FavoriteKind>(
|
|
kind: Kind,
|
|
id: Id<FavoriteTables[Kind]>,
|
|
favorite: boolean
|
|
) => Promise<void>
|
|
/** Throws so callers like Siri can report failures. */
|
|
addFavoriteSongs: (songIds: Id<"songs">[]) => Promise<void>
|
|
}
|
|
|
|
function showFavoritesError(error: unknown) {
|
|
showError(
|
|
error instanceof Error ? error.message : "Failed to update favorites"
|
|
)
|
|
}
|
|
|
|
const FavoritesContext = createContext<FavoritesContextValue | null>(null)
|
|
|
|
export function useFavorites() {
|
|
const context = useContext(FavoritesContext)
|
|
if (!context) {
|
|
throw new Error("useFavorites must be used within FavoritesProvider")
|
|
}
|
|
return context
|
|
}
|
|
|
|
export function FavoritesProvider({ children }: { children: ReactNode }) {
|
|
const favorites = useCachedQuery(api.favorites.getUserFavorites)
|
|
const favoriteSong = useOptimisticMutation(
|
|
api.favorites.favoriteSong,
|
|
favoriteOptimisticUpdates.favoriteSong
|
|
)
|
|
const unfavoriteSong = useOptimisticMutation(
|
|
api.favorites.unfavoriteSong,
|
|
favoriteOptimisticUpdates.unfavoriteSong
|
|
)
|
|
const favoriteAlbum = useOptimisticMutation(
|
|
api.favorites.favoriteAlbum,
|
|
favoriteOptimisticUpdates.favoriteAlbum
|
|
)
|
|
const unfavoriteAlbum = useOptimisticMutation(
|
|
api.favorites.unfavoriteAlbum,
|
|
favoriteOptimisticUpdates.unfavoriteAlbum
|
|
)
|
|
const favoriteArtist = useOptimisticMutation(
|
|
api.favorites.favoriteArtist,
|
|
favoriteOptimisticUpdates.favoriteArtist
|
|
)
|
|
const unfavoriteArtist = useOptimisticMutation(
|
|
api.favorites.unfavoriteArtist,
|
|
favoriteOptimisticUpdates.unfavoriteArtist
|
|
)
|
|
const favoriteSongsMutation = useOptimisticMutation(
|
|
api.favorites.favoriteSongs,
|
|
favoriteOptimisticUpdates.favoriteSongs
|
|
)
|
|
|
|
const songIds = useMemo(
|
|
() => new Set(favorites?.favoriteSongs.map(String) ?? []),
|
|
[favorites?.favoriteSongs]
|
|
)
|
|
const albumIds = useMemo(
|
|
() => new Set(favorites?.favoriteAlbums.map(String) ?? []),
|
|
[favorites?.favoriteAlbums]
|
|
)
|
|
const artistIds = useMemo(
|
|
() => new Set(favorites?.favoriteArtists.map(String) ?? []),
|
|
[favorites?.favoriteArtists]
|
|
)
|
|
const idsRef = useRef({ songIds, albumIds, artistIds })
|
|
idsRef.current = { songIds, albumIds, artistIds }
|
|
|
|
const setFavorite = useCallback(
|
|
async <Kind extends FavoriteKind>(
|
|
kind: Kind,
|
|
id: Id<FavoriteTables[Kind]>,
|
|
favorite: boolean
|
|
) => {
|
|
if (kind === "song") {
|
|
const songId = id as Id<"songs">
|
|
await (favorite ? favoriteSong : unfavoriteSong)({ songId })
|
|
} else if (kind === "album") {
|
|
const albumId = id as Id<"albums">
|
|
await (favorite ? favoriteAlbum : unfavoriteAlbum)({ albumId })
|
|
} else {
|
|
const artistId = id as Id<"artists">
|
|
await (favorite ? favoriteArtist : unfavoriteArtist)({ artistId })
|
|
}
|
|
},
|
|
[
|
|
favoriteSong,
|
|
unfavoriteSong,
|
|
favoriteAlbum,
|
|
unfavoriteAlbum,
|
|
favoriteArtist,
|
|
unfavoriteArtist,
|
|
]
|
|
)
|
|
|
|
const toggleSongFavorite = useCallback(
|
|
(songId: Id<"songs">) =>
|
|
setFavorite("song", songId, !idsRef.current.songIds.has(songId)).catch(
|
|
showFavoritesError
|
|
),
|
|
[setFavorite]
|
|
)
|
|
|
|
const toggleAlbumFavorite = useCallback(
|
|
(albumId: Id<"albums">) =>
|
|
setFavorite(
|
|
"album",
|
|
albumId,
|
|
!idsRef.current.albumIds.has(albumId)
|
|
).catch(showFavoritesError),
|
|
[setFavorite]
|
|
)
|
|
|
|
const toggleArtistFavorite = useCallback(
|
|
(artistId: Id<"artists">) =>
|
|
setFavorite(
|
|
"artist",
|
|
artistId,
|
|
!idsRef.current.artistIds.has(artistId)
|
|
).catch(showFavoritesError),
|
|
[setFavorite]
|
|
)
|
|
|
|
const addFavoriteSongs = useCallback(
|
|
async (ids: Id<"songs">[]) => {
|
|
const unique = [...new Set(ids)]
|
|
if (unique.length > 0) await favoriteSongsMutation({ songIds: unique })
|
|
},
|
|
[favoriteSongsMutation]
|
|
)
|
|
|
|
const favoriteSongs = useCallback(
|
|
(ids: Id<"songs">[]) => addFavoriteSongs(ids).catch(showFavoritesError),
|
|
[addFavoriteSongs]
|
|
)
|
|
|
|
const value = useMemo(
|
|
() => ({
|
|
isSongFavorite: (songId: string) => songIds.has(songId),
|
|
isAlbumFavorite: (albumId: string) => albumIds.has(albumId),
|
|
isArtistFavorite: (artistId: string) => artistIds.has(artistId),
|
|
toggleSongFavorite,
|
|
toggleAlbumFavorite,
|
|
toggleArtistFavorite,
|
|
favoriteSongs,
|
|
setFavorite,
|
|
addFavoriteSongs,
|
|
}),
|
|
[
|
|
songIds,
|
|
albumIds,
|
|
artistIds,
|
|
toggleSongFavorite,
|
|
toggleAlbumFavorite,
|
|
toggleArtistFavorite,
|
|
favoriteSongs,
|
|
setFavorite,
|
|
addFavoriteSongs,
|
|
]
|
|
)
|
|
|
|
return (
|
|
<FavoritesContext.Provider value={value}>
|
|
{children}
|
|
</FavoritesContext.Provider>
|
|
)
|
|
}
|