53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
import { generateId } from "@/lib/id"
|
|
import { mockFavorites } from "@/lib/mock"
|
|
import type { Favorite } from "@/lib/types"
|
|
import { create } from "zustand"
|
|
|
|
interface FavoriteState {
|
|
favorites: Favorite[]
|
|
listFavoritesByUser: (userId: string) => Favorite[]
|
|
isFavorited: (userId: string, targetType: "player" | "shop", targetId: string) => boolean
|
|
toggleFavorite: (userId: string, targetType: "player" | "shop", targetId: string) => boolean
|
|
}
|
|
|
|
export const useFavoriteStore = create<FavoriteState>((set, get) => ({
|
|
favorites: mockFavorites,
|
|
listFavoritesByUser: (userId) => get().favorites.filter((favorite) => favorite.userId === userId),
|
|
isFavorited: (userId, targetType, targetId) =>
|
|
get().favorites.some(
|
|
(favorite) =>
|
|
favorite.userId === userId &&
|
|
favorite.targetType === targetType &&
|
|
favorite.targetId === targetId,
|
|
),
|
|
toggleFavorite: (userId, targetType, targetId) => {
|
|
const state = get()
|
|
const existing = state.favorites.find(
|
|
(favorite) =>
|
|
favorite.userId === userId &&
|
|
favorite.targetType === targetType &&
|
|
favorite.targetId === targetId,
|
|
)
|
|
|
|
if (existing) {
|
|
set((prev) => ({
|
|
favorites: prev.favorites.filter((favorite) => favorite.id !== existing.id),
|
|
}))
|
|
return false
|
|
}
|
|
|
|
const next: Favorite = {
|
|
id: generateId("fav"),
|
|
userId,
|
|
targetType,
|
|
targetId,
|
|
createdAt: new Date().toISOString(),
|
|
}
|
|
|
|
set((prev) => ({
|
|
favorites: [next, ...prev.favorites],
|
|
}))
|
|
return true
|
|
},
|
|
}))
|