fix(post): persist creation through backend
This commit is contained in:
@@ -13,15 +13,16 @@ import {
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { createPost, listOrders, uploadFile } from "@/lib/api"
|
||||
import { toApiError } from "@/lib/errors"
|
||||
import { notifyInfo, notifySuccess } from "@/lib/toast"
|
||||
import { useRequireAuth } from "@/lib/use-require-auth"
|
||||
import { useAuthStore } from "@/store/auth"
|
||||
import { useOrderStore } from "@/store/orders"
|
||||
import { usePostStore } from "@/store/posts"
|
||||
import { standardSchemaResolver } from "@hookform/resolvers/standard-schema"
|
||||
import { ArrowLeft, ImagePlus, X } from "lucide-react"
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useState } from "react"
|
||||
import { type ChangeEvent, useEffect, useState } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { z } from "zod"
|
||||
|
||||
@@ -32,19 +33,16 @@ const postSchema = z.object({
|
||||
|
||||
const tagOptions = ["英雄联盟", "王者荣耀", "CS2", "原神", "上分", "攻略", "好评", "吐槽", "求组队"]
|
||||
|
||||
type PostType = "normal" | "show_order"
|
||||
|
||||
export default function NewPostPage() {
|
||||
const router = useRouter()
|
||||
const { isAuthenticated, requireAuth } = useRequireAuth()
|
||||
const currentRole = useAuthStore((state) => state.currentRole)
|
||||
const userId = useAuthStore((state) => state.user?.id)
|
||||
const user = useAuthStore((state) => state.user)
|
||||
const orders = useOrderStore((state) => state.orders)
|
||||
const posts = usePostStore((state) => state.posts)
|
||||
const createPost = usePostStore((state) => state.createPost)
|
||||
const [postType, setPostType] = useState("normal")
|
||||
const [orders, setOrders] = useState<Awaited<ReturnType<typeof listOrders>>>([])
|
||||
const [postType, setPostType] = useState<PostType>("normal")
|
||||
const [selectedTags, setSelectedTags] = useState<string[]>([])
|
||||
const [imageCount, setImageCount] = useState(0)
|
||||
const [selectedQuotePostId, setSelectedQuotePostId] = useState<string | undefined>(undefined)
|
||||
const [imageFiles, setImageFiles] = useState<File[]>([])
|
||||
const [selectedOrderId, setSelectedOrderId] = useState<string | undefined>(undefined)
|
||||
const canShowOrder = currentRole === "consumer"
|
||||
const effectivePostType = canShowOrder || postType !== "show_order" ? postType : "normal"
|
||||
@@ -63,9 +61,37 @@ export default function NewPostPage() {
|
||||
)
|
||||
}
|
||||
|
||||
const availableOrders = orders.filter(
|
||||
(order) => order.status === "completed" && order.consumerId === userId,
|
||||
)
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated || !canShowOrder) {
|
||||
return
|
||||
}
|
||||
|
||||
let cancelled = false
|
||||
|
||||
listOrders({ role: "consumer", status: "completed" })
|
||||
.then((items) => {
|
||||
if (cancelled) return
|
||||
setOrders(items)
|
||||
})
|
||||
.catch((error) => {
|
||||
if (cancelled) return
|
||||
notifyInfo(toApiError(error).msg)
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [canShowOrder, isAuthenticated])
|
||||
|
||||
const handleSelectImages = (event: ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(event.target.files ?? [])
|
||||
if (files.length === 0) return
|
||||
|
||||
setImageFiles((prev) => [...prev, ...files].slice(0, 9))
|
||||
event.target.value = ""
|
||||
}
|
||||
|
||||
const availableOrders = isAuthenticated && canShowOrder ? orders : []
|
||||
|
||||
const onSubmit = async (data: z.infer<typeof postSchema>) => {
|
||||
if (!isAuthenticated) {
|
||||
@@ -73,20 +99,21 @@ export default function NewPostPage() {
|
||||
return
|
||||
}
|
||||
|
||||
requireAuth(() => {
|
||||
if (!user) return
|
||||
|
||||
createPost({
|
||||
author: user,
|
||||
try {
|
||||
const images = await Promise.all(imageFiles.map((file) => uploadFile(file, "post")))
|
||||
await createPost({
|
||||
title: data.title,
|
||||
content: data.content,
|
||||
images: Array.from({ length: imageCount }).map(() => "/posts/p1-1.jpg"),
|
||||
images,
|
||||
tags: selectedTags,
|
||||
linkedOrderId: effectivePostType === "show_order" ? selectedOrderId : undefined,
|
||||
})
|
||||
|
||||
notifySuccess("帖子已发布")
|
||||
router.push("/community")
|
||||
})
|
||||
} catch (error) {
|
||||
notifyInfo(toApiError(error).msg)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -107,14 +134,16 @@ export default function NewPostPage() {
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label>帖子类型</Label>
|
||||
<Select value={effectivePostType} onValueChange={setPostType}>
|
||||
<Select
|
||||
value={effectivePostType}
|
||||
onValueChange={(value) => setPostType(value as PostType)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="normal">普通帖</SelectItem>
|
||||
{canShowOrder && <SelectItem value="show_order">秀单帖</SelectItem>}
|
||||
<SelectItem value="quote">引用帖</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -137,48 +166,6 @@ export default function NewPostPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{effectivePostType === "quote" && (
|
||||
<div className="space-y-2">
|
||||
<Label>引用帖子</Label>
|
||||
<Select value={selectedQuotePostId} onValueChange={setSelectedQuotePostId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择要引用的帖子" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{posts.map((post) => (
|
||||
<SelectItem key={post.id} value={post.id}>
|
||||
{post.title}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="mt-2 rounded-xl border bg-muted/50 p-3 text-sm text-muted-foreground">
|
||||
<p className="font-medium text-foreground">预览:</p>
|
||||
{selectedQuotePostId ? (
|
||||
(() => {
|
||||
const post = posts.find((p) => p.id === selectedQuotePostId)
|
||||
if (!post) return <p className="mt-1">未找到帖子</p>
|
||||
return (
|
||||
<div className="mt-2 rounded-lg border bg-background p-3">
|
||||
<p className="font-medium text-foreground">{post.title}</p>
|
||||
<p className="mt-1 line-clamp-2 text-xs text-muted-foreground">
|
||||
{post.content}
|
||||
</p>
|
||||
<div className="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>@{post.author.nickname}</span>
|
||||
<span>·</span>
|
||||
<span>{new Date(post.createdAt).toLocaleDateString("zh-CN")}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})()
|
||||
) : (
|
||||
<p className="mt-1">选择一个帖子以查看预览...</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="title">标题</Label>
|
||||
<Input id="title" placeholder="请输入帖子标题" {...register("title")} />
|
||||
@@ -196,30 +183,41 @@ export default function NewPostPage() {
|
||||
<div className="space-y-2">
|
||||
<Label>图片(最多9张)</Label>
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{Array.from({ length: imageCount }).map((_, i) => (
|
||||
{imageFiles.map((file) => (
|
||||
<div
|
||||
key={`img-${i.toString()}`}
|
||||
key={`${file.name}-${file.lastModified}-${file.size}`}
|
||||
className="h-20 w-20 rounded-lg bg-muted flex items-center justify-center relative"
|
||||
>
|
||||
<span className="text-xs text-muted-foreground">图片</span>
|
||||
<span className="max-w-16 truncate text-xs text-muted-foreground">
|
||||
{file.name}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setImageCount((c) => c - 1)}
|
||||
onClick={() =>
|
||||
setImageFiles((files) => files.filter((item) => item !== file))
|
||||
}
|
||||
className="absolute -top-1 -right-1 h-4 w-4 rounded-full bg-destructive text-destructive-foreground flex items-center justify-center"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{imageCount < 9 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setImageCount((c) => c + 1)}
|
||||
className="h-20 w-20 rounded-lg border-2 border-dashed border-muted-foreground/25 flex flex-col items-center justify-center gap-1 text-muted-foreground hover:border-muted-foreground/50 transition-colors"
|
||||
{imageFiles.length < 9 && (
|
||||
<Label
|
||||
htmlFor="post-images"
|
||||
className="h-20 w-20 cursor-pointer rounded-lg border-2 border-dashed border-muted-foreground/25 flex flex-col items-center justify-center gap-1 text-muted-foreground hover:border-muted-foreground/50 transition-colors"
|
||||
>
|
||||
<ImagePlus className="h-5 w-5" />
|
||||
<span className="text-[10px]">添加</span>
|
||||
</button>
|
||||
<Input
|
||||
id="post-images"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="sr-only"
|
||||
onChange={handleSelectImages}
|
||||
/>
|
||||
</Label>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user