refactor(community): extract comment store and post/comment API adapters

This commit is contained in:
zetaloop
2026-02-23 11:04:40 +08:00
parent 8e62b15403
commit 77d23d0c9d
9 changed files with 201 additions and 63 deletions
+47
View File
@@ -0,0 +1,47 @@
import { create } from "zustand"
import { generateId } from "@/lib/id"
import { mockComments } from "@/lib/mock"
import type { Comment, User } from "@/lib/types"
interface CommentState {
comments: Comment[]
addComment: (postId: string, author: User, content: string) => Comment | null
toggleCommentLike: (commentId: string) => void
}
export const useCommentStore = create<CommentState>((set) => ({
comments: mockComments,
addComment: (postId, author, content) => {
const normalizedContent = content.trim()
if (!normalizedContent) return null
const comment: Comment = {
id: generateId("comment"),
postId,
author,
content: normalizedContent,
likeCount: 0,
liked: false,
createdAt: new Date().toISOString(),
}
set((state) => ({
comments: [...state.comments, comment],
}))
return comment
},
toggleCommentLike: (commentId) => {
set((state) => ({
comments: state.comments.map((comment) => {
if (comment.id !== commentId) return comment
const liked = !comment.liked
return {
...comment,
liked,
likeCount: liked ? comment.likeCount + 1 : Math.max(0, comment.likeCount - 1),
}
}),
}))
},
}))
+20
View File
@@ -17,6 +17,8 @@ interface CreatePostInput {
interface PostState {
posts: Post[]
createPost: (input: CreatePostInput) => Post
togglePostLike: (postId: string) => void
incrementCommentCount: (postId: string) => void
}
export const usePostStore = create<PostState>((set) => ({
@@ -45,4 +47,22 @@ export const usePostStore = create<PostState>((set) => ({
return post
},
togglePostLike: (postId) =>
set((state) => ({
posts: state.posts.map((post) => {
if (post.id !== postId) return post
const liked = !post.liked
return {
...post,
liked,
likeCount: liked ? post.likeCount + 1 : Math.max(0, post.likeCount - 1),
}
}),
})),
incrementCommentCount: (postId) =>
set((state) => ({
posts: state.posts.map((post) =>
post.id === postId ? { ...post, commentCount: post.commentCount + 1 } : post,
),
})),
}))