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