stacker.news/components/comments.js

112 lines
2.7 KiB
JavaScript
Raw Normal View History

2021-12-21 21:29:42 +00:00
import { gql, useApolloClient, useLazyQuery, useQuery } from '@apollo/client'
import { useEffect, useState } from 'react'
2021-04-22 22:14:32 +00:00
import Comment, { CommentSkeleton } from './comment'
2021-12-21 21:29:42 +00:00
import styles from './header.module.css'
import { Nav, Navbar } from 'react-bootstrap'
import { COMMENTS_QUERY } from '../fragments/items'
import { COMMENTS } from '../fragments/comments'
2021-04-15 19:41:02 +00:00
2021-12-21 21:29:42 +00:00
export function CommentsHeader ({ handleSort }) {
const [sort, setSort] = useState('hot')
const getHandleClick = sort => {
return () => {
setSort(sort)
handleSort(sort)
}
}
return (
2022-01-07 18:55:40 +00:00
<Navbar className='py-1'>
2021-12-21 21:29:42 +00:00
<Nav
className={styles.navbarNav}
activeKey={sort}
>
<Nav.Item>
<Nav.Link
eventKey='hot'
className={styles.navLink}
onClick={getHandleClick('hot')}
>
hot
</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link
eventKey='recent'
className={styles.navLink}
onClick={getHandleClick('recent')}
>
recent
</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link
eventKey='top'
className={styles.navLink}
onClick={getHandleClick('top')}
>
top
</Nav.Link>
</Nav.Item>
</Nav>
</Navbar>
)
}
export default function Comments ({ parentId, comments, ...props }) {
const client = useApolloClient()
2021-06-24 23:56:01 +00:00
useEffect(() => {
const hash = window.location.hash
if (hash) {
document.querySelector(hash).scrollIntoView({ behavior: 'smooth' })
}
}, [])
2021-12-21 21:29:42 +00:00
const [getComments, { loading }] = useLazyQuery(COMMENTS_QUERY, {
fetchPolicy: 'network-only',
onCompleted: data => {
client.writeFragment({
id: `Item:${parentId}`,
fragment: gql`
${COMMENTS}
fragment Comments on Item {
comments {
...CommentsRecursive
}
}
`,
fragmentName: 'Comments',
data: {
comments: data.comments
}
})
}
})
2021-06-24 23:56:01 +00:00
2021-12-21 21:29:42 +00:00
return (
<>
{comments.length ? <CommentsHeader handleSort={sort => getComments({ variables: { id: parentId, sort } })} /> : null}
{loading
? <CommentsSkeleton />
: comments.map(item => (
<Comment key={item.id} item={item} {...props} />
))}
</>
)
2021-04-27 00:55:48 +00:00
}
export function CommentsSkeleton () {
2021-05-05 18:13:14 +00:00
return <CommentSkeleton skeletonChildren={7} />
2021-04-27 00:55:48 +00:00
}
export function CommentsQuery ({ query, ...props }) {
2021-10-26 20:49:37 +00:00
const { error, data } = useQuery(query)
2021-04-17 18:15:18 +00:00
2021-04-22 22:14:32 +00:00
if (error) return <div>Failed to load!</div>
if (!data) {
2021-04-27 00:55:48 +00:00
return <CommentsSkeleton />
2021-04-22 22:14:32 +00:00
}
2021-04-15 19:41:02 +00:00
2021-04-27 00:55:48 +00:00
return <Comments comments={data.comments} {...props} />
2021-04-15 19:41:02 +00:00
}