refactor(auth): unify current user state usage across UI

This commit is contained in:
zetaloop
2026-02-22 08:03:09 +08:00
parent 7bcb73f139
commit 312061330c
8 changed files with 47 additions and 44 deletions
+6 -7
View File
@@ -11,12 +11,11 @@ import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Separator } from "@/components/ui/separator"
import { Switch } from "@/components/ui/switch"
import { Textarea } from "@/components/ui/textarea"
import { currentUser } from "@/lib/mock"
import type { UserRole } from "@/lib/types"
import { useAuthStore } from "@/store/auth"
export default function SettingsPage() {
const { currentRole, verifiedRoles, switchRole } = useAuthStore()
const { currentRole, verifiedRoles, switchRole, user } = useAuthStore()
const isRoleVerified = (role: UserRole) => verifiedRoles.includes(role)
@@ -31,8 +30,8 @@ export default function SettingsPage() {
<CardContent className="flex items-center gap-4">
<div className="relative">
<Avatar className="h-20 w-20">
<AvatarImage src={currentUser.avatar} />
<AvatarFallback className="text-lg">{currentUser.nickname[0]}</AvatarFallback>
<AvatarImage src={user?.avatar} />
<AvatarFallback className="text-lg">{user?.nickname?.[0] ?? "?"}</AvatarFallback>
</Avatar>
<button
type="button"
@@ -52,15 +51,15 @@ export default function SettingsPage() {
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="nickname"></Label>
<Input id="nickname" defaultValue={currentUser.nickname} />
<Input id="nickname" defaultValue={user?.nickname ?? ""} />
</div>
<div className="space-y-2">
<Label htmlFor="bio"></Label>
<Textarea id="bio" defaultValue={currentUser.bio} rows={3} />
<Textarea id="bio" defaultValue={user?.bio ?? ""} rows={3} />
</div>
<div className="space-y-2">
<Label htmlFor="phone"></Label>
<Input id="phone" defaultValue={currentUser.phone} disabled />
<Input id="phone" defaultValue={user?.phone ?? ""} disabled />
<p className="text-xs text-muted-foreground"></p>
</div>
<Button></Button>
+2 -2
View File
@@ -9,7 +9,7 @@ import { z } from "zod"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { currentUser } from "@/lib/mock"
import { getCurrentUserForLogin } from "@/lib/api"
import { useAuthStore } from "@/store/auth"
const loginSchema = z.object({
@@ -30,7 +30,7 @@ export default function LoginPage() {
const onSubmit = async (_data: z.infer<typeof loginSchema>) => {
await new Promise((r) => setTimeout(r, 500))
login(currentUser, ["consumer", "player", "owner"])
login(getCurrentUserForLogin(), ["consumer", "player", "owner"])
router.push("/")
}
+2 -2
View File
@@ -9,7 +9,7 @@ import { z } from "zod"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { currentUser } from "@/lib/mock"
import { getCurrentUserForLogin } from "@/lib/api"
import { useAuthStore } from "@/store/auth"
const registerSchema = z
@@ -37,7 +37,7 @@ export default function RegisterPage() {
const onSubmit = async (_data: z.infer<typeof registerSchema>) => {
await new Promise((r) => setTimeout(r, 500))
login(currentUser, ["consumer"])
login(getCurrentUserForLogin(), ["consumer"])
router.push("/")
}
+5 -7
View File
@@ -28,8 +28,8 @@ export default function ChatDetailPage({ params }: { params: Promise<{ id: strin
)
}
const currentUserId = user?.id ?? session.participants[0].id
const other = session.participants.find((p) => p.id !== currentUserId) ?? session.participants[1]
const userId = user?.id ?? session.participants[0].id
const other = session.participants.find((p) => p.id !== userId) ?? session.participants[1]
return (
<div className="flex flex-col h-[calc(100vh-3.5rem)]">
@@ -69,7 +69,7 @@ export default function ChatDetailPage({ params }: { params: Promise<{ id: strin
</div>
)
}
const isMine = msg.senderId === currentUserId
const isMine = msg.senderId === userId
return (
<div key={msg.id} className={cn("flex gap-2", isMine && "flex-row-reverse")}>
<Avatar className="h-8 w-8 shrink-0">
@@ -107,13 +107,11 @@ export default function ChatDetailPage({ params }: { params: Promise<{ id: strin
const text = input.trim()
if (!text) return
const sender = session.participants.find(
(participant) => participant.id === currentUserId,
)
const sender = session.participants.find((participant) => participant.id === userId)
sendTextMessage(
session.id,
{
id: currentUserId,
id: userId,
name: sender?.name ?? user?.nickname ?? "",
avatar: sender?.avatar ?? user?.avatar ?? "",
},
+3 -3
View File
@@ -55,7 +55,7 @@ export default function OrderListPage() {
const orders = useOrderStore((state) => state.orders)
const sessions = useChatStore((state) => state.sessions)
const ensureOrderSession = useChatStore((state) => state.ensureOrderSession)
const currentUserId = user?.id ?? "u1"
const userId = user?.id ?? "u1"
const ownerShopId = "shop1"
useEffect(() => {
@@ -74,8 +74,8 @@ export default function OrderListPage() {
}, [orders, ensureOrderSession])
const roleFiltered = orders.filter((order) => {
if (currentRole === "consumer") return order.consumerId === currentUserId
if (currentRole === "player") return order.playerId === currentUserId
if (currentRole === "consumer") return order.consumerId === userId
if (currentRole === "player") return order.playerId === userId
return order.shopId === ownerShopId
})
+23 -17
View File
@@ -29,11 +29,11 @@ import {
} from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"
import { currentUser, mockShops } from "@/lib/mock"
import type { UserRole } from "@/lib/types"
import { cn } from "@/lib/utils"
import { useAuthStore } from "@/store/auth"
import { useNotificationStore } from "@/store/notifications"
import { useShopStore } from "@/store/shops"
const roleLabels: Record<UserRole, string> = {
consumer: "消费者",
@@ -45,7 +45,10 @@ export function Header() {
const [mobileOpen, setMobileOpen] = useState(false)
const pathname = usePathname()
const router = useRouter()
const { isAuthenticated, currentRole, verifiedRoles, switchRole, logout } = useAuthStore()
const { isAuthenticated, currentRole, verifiedRoles, switchRole, logout, user } = useAuthStore()
const ownerShop = useShopStore((state) =>
user ? state.shops.find((shop) => shop.owner.id === user.id) : undefined,
)
const navLinks =
currentRole === "consumer"
@@ -84,6 +87,17 @@ export function Header() {
if (q.trim()) router.push(`/search?q=${encodeURIComponent(q.trim())}`)
}
const profileHref =
currentRole === "player"
? user
? `/player/${user.id}`
: "/settings"
: currentRole === "owner"
? `/shop/${ownerShop?.id ?? "shop1"}`
: user
? `/user/${user.id}`
: "/settings"
return (
<header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="container mx-auto flex h-14 items-center gap-4 px-4">
@@ -155,25 +169,17 @@ export function Header() {
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="rounded-full h-9 w-9">
<Avatar className="h-7 w-7">
<AvatarImage src={currentUser.avatar} />
<AvatarFallback>{currentUser.nickname[0]}</AvatarFallback>
<AvatarImage src={user?.avatar} />
<AvatarFallback>{user?.nickname?.[0] ?? "?"}</AvatarFallback>
</Avatar>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuLabel>{currentUser.nickname}</DropdownMenuLabel>
<DropdownMenuLabel>{user?.nickname ?? "未登录"}</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem asChild>
<Link
href={
currentRole === "player"
? `/player/${currentUser.id}`
: currentRole === "owner"
? `/shop/${mockShops.find((s) => s.owner.id === currentUser.id)?.id ?? "shop1"}`
: `/user/${currentUser.id}`
}
>
<Link href={profileHref}>
<User className="mr-2 h-4 w-4" />
</Link>
@@ -254,11 +260,11 @@ export function Header() {
{isAuthenticated && (
<div className="flex items-center gap-2 px-1">
<Avatar className="h-8 w-8">
<AvatarImage src={currentUser.avatar} />
<AvatarFallback>{currentUser.nickname[0]}</AvatarFallback>
<AvatarImage src={user?.avatar} />
<AvatarFallback>{user?.nickname?.[0] ?? "?"}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{currentUser.nickname}</p>
<p className="text-sm font-medium truncate">{user?.nickname ?? "未登录"}</p>
<p className="text-xs text-muted-foreground">{roleLabels[currentRole]}</p>
</div>
</div>
+2 -2
View File
@@ -14,7 +14,7 @@ import {
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { currentUser } from "@/lib/mock"
import { getCurrentUserForLogin } from "@/lib/api"
import { useAuthStore } from "@/store/auth"
import { useLoginDialogStore } from "@/store/login-dialog"
@@ -42,7 +42,7 @@ export function LoginDialog({ open, onOpenChange }: LoginDialogProps) {
const onSubmit = async (_data: z.infer<typeof loginSchema>) => {
await new Promise((r) => setTimeout(r, 500))
login(currentUser, ["consumer", "player", "owner"])
login(getCurrentUserForLogin(), ["consumer", "player", "owner"])
consumePendingAction()
onOpenChange(false)
}
+4 -4
View File
@@ -2,7 +2,7 @@
import { Heart } from "lucide-react"
import { useState } from "react"
import { currentUser } from "@/lib/mock"
import { generateId } from "@/lib/id"
import type { Comment } from "@/lib/types"
import { useRequireAuth } from "@/lib/use-require-auth"
import { useAuthStore } from "@/store/auth"
@@ -32,14 +32,14 @@ export function PostComments({ initialComments, postId }: PostCommentsProps) {
requireAuth(() => {
const nextContent = content.trim()
if (!nextContent) return
const author = user ?? currentUser
if (!user) return
const createdAt = new Date().toISOString()
setComments((prev) => [
...prev,
{
id: `comment-${postId}-${createdAt}`,
id: generateId(`comment-${postId}`),
postId,
author,
author: user,
content: nextContent,
likeCount: 0,
liked: false,