stacker.news/components/reply.js

90 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-07-01 23:51:58 +00:00
import { Form, MarkdownInput, SubmitButton } from '../components/form'
2021-04-14 23:56:29 +00:00
import * as Yup from 'yup'
import { gql, useMutation } from '@apollo/client'
import styles from './reply.module.css'
2021-04-22 22:14:32 +00:00
import { COMMENTS } from '../fragments/comments'
2021-05-25 00:08:56 +00:00
import { useMe } from './me'
2021-07-08 18:42:57 +00:00
import ActionTooltip from './action-tooltip'
2021-04-14 23:56:29 +00:00
export const CommentSchema = Yup.object({
text: Yup.string().required('required').trim()
})
2021-05-20 01:09:32 +00:00
export default function Reply ({ parentId, onSuccess, autoFocus }) {
2021-05-25 00:08:56 +00:00
const me = useMe()
2021-04-14 23:56:29 +00:00
const [createComment] = useMutation(
gql`
2021-04-17 18:15:18 +00:00
${COMMENTS}
2021-04-14 23:56:29 +00:00
mutation createComment($text: String!, $parentId: ID!) {
createComment(text: $text, parentId: $parentId) {
2021-04-17 18:15:18 +00:00
...CommentFields
comments {
...CommentsRecursive
}
2021-04-14 23:56:29 +00:00
}
2021-04-17 18:15:18 +00:00
}`, {
update (cache, { data: { createComment } }) {
cache.modify({
2021-04-27 00:55:48 +00:00
id: `Item:${parentId}`,
2021-04-17 18:15:18 +00:00
fields: {
comments (existingCommentRefs = []) {
2021-04-17 18:15:18 +00:00
const newCommentRef = cache.writeFragment({
data: createComment,
fragment: COMMENTS,
fragmentName: 'CommentsRecursive'
})
return [newCommentRef, ...existingCommentRefs]
2021-04-27 21:30:58 +00:00
},
ncomments (existingNComments = 0) {
return existingNComments + 1
2021-04-17 18:15:18 +00:00
}
}
})
}
}
2021-04-14 23:56:29 +00:00
)
return (
<div className={styles.reply}>
<Form
initial={{
text: ''
}}
schema={CommentSchema}
2021-04-18 18:50:04 +00:00
onSubmit={async (values, { resetForm }) => {
const { error } = await createComment({ variables: { ...values, parentId } })
2021-04-14 23:56:29 +00:00
if (error) {
throw new Error({ message: error.toString() })
}
2021-04-18 18:50:04 +00:00
resetForm({ text: '' })
if (onSuccess) {
onSuccess()
}
2021-04-14 23:56:29 +00:00
}}
>
2021-07-01 23:51:58 +00:00
<MarkdownInput
2021-04-14 23:56:29 +00:00
name='text'
as='textarea'
rows={4}
2021-05-20 01:09:32 +00:00
autoFocus={autoFocus}
2021-04-14 23:56:29 +00:00
required
2021-05-25 00:08:56 +00:00
hint={me?.freeComments ? <span className='text-success'>{me.freeComments} free comments left</span> : null}
2021-04-14 23:56:29 +00:00
/>
2021-07-08 18:42:57 +00:00
<ActionTooltip>
<SubmitButton variant='secondary' className='mt-1'>reply</SubmitButton>
</ActionTooltip>
2021-04-14 23:56:29 +00:00
</Form>
</div>
)
}
2021-04-27 00:55:48 +00:00
export function ReplySkeleton () {
return (
<div className={`${styles.reply} ${styles.skeleton}`}>
<div className={`${styles.input} clouds`} />
<div className={`${styles.button} clouds`} />
</div>
)
}