add sorter for comments

pull/51/head
sunface 4 years ago
parent 3295ac48ed
commit 664216ca87

@ -30,7 +30,6 @@ const PostPage = () => {
const router = useRouter() const router = useRouter()
const id = router.query.post_id const id = router.query.post_id
const [post, setPost]: [Post, any] = useState(null) const [post, setPost]: [Post, any] = useState(null)
const [comments, setComments]: [Comment[], any] = useState([])
useEffect(() => { useEffect(() => {
if (id) { if (id) {
getData() getData()
@ -49,14 +48,8 @@ const PostPage = () => {
const getData = async () => { const getData = async () => {
const res = await requestApi.get(`/story/post/${id}`) const res = await requestApi.get(`/story/post/${id}`)
setPost(res.data) setPost(res.data)
getComments(res.data.id)
} }
const getComments = async (id) => {
const res = await requestApi.get(`/story/comments/${id}`)
setComments(res.data)
}
return ( return (
<> <>
@ -80,7 +73,7 @@ const PostPage = () => {
</Box> </Box>
<HStack ml="2" spacing="3" mt="4">{post.rawTags.map(tag => <TagTextCard key={tag.id} tag={tag} />)}</HStack> <HStack ml="2" spacing="3" mt="4">{post.rawTags.map(tag => <TagTextCard key={tag.id} tag={tag} />)}</HStack>
<Box mt="6" p="2"><Comments storyID={post.id} comments={comments} onChange={() => getComments(post.id)} /></Box> <Box mt="6" p="2"><Comments storyID={post.id} /></Box>
</Box> </Box>
<Box pt="16"> <Box pt="16">
<PostSidebar post={post} /> <PostSidebar post={post} />

@ -51,7 +51,13 @@ func SubmitComment(c *gin.Context) {
func GetStoryComments(c *gin.Context) { func GetStoryComments(c *gin.Context) {
storyID := c.Param("id") storyID := c.Param("id")
comments, err := story.GetComments(storyID) sorter := c.Query("sorter")
if !models.ValidSearchFilter(sorter) {
c.JSON(http.StatusBadRequest, e.ParamInvalid)
return
}
comments, err := story.GetComments(storyID, sorter)
if err != nil { if err != nil {
c.JSON(err.Status, common.RespError(err.Message)) c.JSON(err.Status, common.RespError(err.Message))
return return
@ -63,7 +69,7 @@ func GetStoryComments(c *gin.Context) {
comment.Liked = interaction.GetLiked(comment.ID, user.ID) comment.Liked = interaction.GetLiked(comment.ID, user.ID)
} }
replies, err := story.GetComments(comment.ID) replies, err := story.GetComments(comment.ID, sorter)
if err != nil { if err != nil {
continue continue
} }

@ -72,8 +72,8 @@ func EditComment(c *models.Comment) *e.Error {
return nil return nil
} }
func GetComments(storyID string) (models.Comments, *e.Error) { func GetComments(storyID string, sorter string) ([]*models.Comment, *e.Error) {
comments := make(models.Comments, 0) comments := make([]*models.Comment, 0)
rows, err := db.Conn.Query("SELECT id,target_id,creator,md,created,updated FROM comments WHERE target_id=?", storyID) rows, err := db.Conn.Query("SELECT id,target_id,creator,md,created,updated FROM comments WHERE target_id=?", storyID)
if err != nil && err != sql.ErrNoRows { if err != nil && err != sql.ErrNoRows {
logger.Warn("get comments error", "error", err) logger.Warn("get comments error", "error", err)
@ -100,7 +100,11 @@ func GetComments(storyID string) (models.Comments, *e.Error) {
comments = append(comments, c) comments = append(comments, c)
} }
sort.Sort(comments) if sorter == models.FilterFavorites {
sort.Sort(models.FavorComments(comments))
} else {
sort.Sort(models.Comments(comments))
}
return comments, nil return comments, nil
} }

@ -22,3 +22,11 @@ func (ar Comments) Swap(i, j int) { ar[i], ar[j] = ar[j], ar[i] }
func (ar Comments) Less(i, j int) bool { func (ar Comments) Less(i, j int) bool {
return ar[i].Created.Unix() > ar[j].Created.Unix() return ar[i].Created.Unix() > ar[j].Created.Unix()
} }
type FavorComments []*Comment
func (ar FavorComments) Len() int { return len(ar) }
func (ar FavorComments) Swap(i, j int) { ar[i], ar[j] = ar[j], ar[i] }
func (ar FavorComments) Less(i, j int) bool {
return ar[i].Likes > ar[j].Likes
}

@ -1,24 +1,36 @@
import React, { useState } from "react" import React, { useEffect, useState } from "react"
import {Text, Flex, HStack, Button, VStack } from "@chakra-ui/react" import {Text, Flex, HStack, Button, VStack, Select } from "@chakra-ui/react"
import Card from "components/card" import Card from "components/card"
import useSession from "hooks/use-session" import useSession from "hooks/use-session"
import { requestApi } from "utils/axios/request" import { requestApi } from "utils/axios/request"
import CommentCard from "./comment" import CommentCard from "./comment"
import CommentEditor from "./editor" import CommentEditor from "./editor"
import { Comment } from "src/types/comments" import { Comment } from "src/types/comments"
import { SearchFilter } from "src/types/search"
import { upperFirst } from "lodash"
interface Props { interface Props {
storyID: string storyID: string
comments: Comment[]
onChange: any
} }
export const Comments = ({storyID, comments,onChange }: Props) => { export const Comments = ({storyID}: Props) => {
const [comments, setComments]: [Comment[], any] = useState([])
const [editorVisible,setEditorVisible] = useState(false) const [editorVisible,setEditorVisible] = useState(false)
const [sorter,setSorter] = useState(SearchFilter.Favorites)
const session = useSession() const session = useSession()
useEffect(() => {
getComments()
},[])
const submitComment = async (md) => { const submitComment = async (md) => {
await requestApi.post('/story/comment',{targetID: storyID, md: md}) await requestApi.post('/story/comment',{targetID: storyID, md: md})
setEditorVisible(false) setEditorVisible(false)
onChange() getComments()
}
const getComments = async (s?) => {
const res = await requestApi.get(`/story/comments/${storyID}?sorter=${s??sorter}`)
setComments(res.data)
} }
const countComments = () => { const countComments = () => {
@ -34,8 +46,12 @@ export const Comments = ({storyID, comments,onChange }: Props) => {
<VStack spacing="4" alignItems="left" id="comments"> <VStack spacing="4" alignItems="left" id="comments">
<Card> <Card>
<Flex justifyContent="space-between"> <Flex justifyContent="space-between">
<HStack> <HStack spacing="4">
<Text fontWeight="600" fontSize="1.1rem">Comments ({countComments()})</Text> <Text fontWeight="600" fontSize="1.1rem">Comments ({countComments()})</Text>
<Select fontWeight="550" cursor="pointer" width="100px" value={sorter} onChange={e => {setSorter(e.currentTarget.value as SearchFilter);getComments(e.currentTarget.value)}} variant="unstyled">
<option value={SearchFilter.Favorites}>{upperFirst(SearchFilter.Favorites)}</option>
<option value={SearchFilter.Recent}>{upperFirst(SearchFilter.Recent)}</option>
</Select>
</HStack> </HStack>
<Button variant="outline" colorScheme="teal" onClick={() => setEditorVisible(true)} _focus={null}>Add comment</Button> <Button variant="outline" colorScheme="teal" onClick={() => setEditorVisible(true)} _focus={null}>Add comment</Button>
@ -44,7 +60,7 @@ export const Comments = ({storyID, comments,onChange }: Props) => {
{editorVisible && session && <CommentEditor user={session.user} md="" onSubmit={md => submitComment(md)} onCancel={() => setEditorVisible(false)}/>} {editorVisible && session && <CommentEditor user={session.user} md="" onSubmit={md => submitComment(md)} onCancel={() => setEditorVisible(false)}/>}
{comments.map(comment => <CommentCard user={session?.user} key={comment.id} comment={comment} onChange={onChange}/>)} {comments.map(comment => <CommentCard user={session?.user} key={comment.id} comment={comment} onChange={getComments}/>)}
</VStack> </VStack>
) )
} }

Loading…
Cancel
Save