feat: wire post interactions and persist favorites state

This commit is contained in:
zetaloop
2026-02-21 15:45:20 +08:00
parent 1ff499720f
commit 3a1f9c2b7f
6 changed files with 158 additions and 52 deletions
+32 -3
View File
@@ -1,24 +1,53 @@
"use client"
import { Heart } from "lucide-react"
import { useState } from "react"
import { useEffect, useMemo, useState } from "react"
import { Button } from "@/components/ui/button"
import { useRequireAuth } from "@/lib/use-require-auth"
import { useAuthStore } from "@/store/auth"
interface FavoriteButtonProps {
initialFavorited: boolean
targetType: "player" | "shop"
targetId: string
}
export function FavoriteButton({ initialFavorited }: FavoriteButtonProps) {
export function FavoriteButton({ initialFavorited, targetType, targetId }: FavoriteButtonProps) {
const [favorited, setFavorited] = useState(initialFavorited)
const { requireAuth } = useRequireAuth()
const userId = useAuthStore((s) => s.user?.id)
const storageKey = useMemo(
() => `favorite:${userId ?? "guest"}:${targetType}:${targetId}`,
[userId, targetType, targetId],
)
useEffect(() => {
const stored = window.localStorage.getItem(storageKey)
if (stored === "1") {
setFavorited(true)
return
}
if (stored === "0") {
setFavorited(false)
return
}
setFavorited(initialFavorited)
}, [storageKey, initialFavorited])
return (
<Button
variant={favorited ? "default" : "outline"}
size="sm"
className="gap-1.5"
onClick={() => requireAuth(() => setFavorited(!favorited))}
onClick={() =>
requireAuth(() =>
setFavorited((prev) => {
const next = !prev
window.localStorage.setItem(storageKey, next ? "1" : "0")
return next
}),
)
}
>
<Heart className={`h-4 w-4 ${favorited ? "fill-current" : ""}`} />
{favorited ? "已收藏" : "收藏"}