1import React, { useState, useRef } from 'react';
2
3import Button from '@material-ui/core/Button';
4import Paper from '@material-ui/core/Paper';
5import { makeStyles, Theme } from '@material-ui/core/styles';
6
7import CommentInput from '../../layout/CommentInput/CommentInput';
8
9import { useAddCommentMutation } from './CommentForm.generated';
10import { TimelineDocument } from './TimelineQuery.generated';
11
12type StyleProps = { loading: boolean };
13const useStyles = makeStyles<Theme, StyleProps>((theme) => ({
14 container: {
15 margin: theme.spacing(2, 0),
16 padding: theme.spacing(0, 2, 2, 2),
17 },
18 textarea: {},
19 tabContent: {
20 margin: theme.spacing(2, 0),
21 },
22 preview: {
23 borderBottom: `solid 3px ${theme.palette.grey['200']}`,
24 minHeight: '5rem',
25 },
26 actions: {
27 display: 'flex',
28 justifyContent: 'flex-end',
29 },
30 greenButton: {
31 backgroundColor: '#2ea44fd9',
32 color: '#fff',
33 '&:hover': {
34 backgroundColor: '#2ea44f',
35 },
36 },
37}));
38
39type Props = {
40 bugId: string;
41};
42
43function CommentForm({ bugId }: Props) {
44 const [addComment, { loading }] = useAddCommentMutation();
45 const [issueComment, setIssueComment] = useState('');
46 const [inputProp, setInputProp] = useState<any>('');
47 const classes = useStyles({ loading });
48 const form = useRef<HTMLFormElement>(null);
49
50 const submit = () => {
51 addComment({
52 variables: {
53 input: {
54 prefix: bugId,
55 message: issueComment,
56 },
57 },
58 refetchQueries: [
59 // TODO: update the cache instead of refetching
60 {
61 query: TimelineDocument,
62 variables: {
63 id: bugId,
64 first: 100,
65 },
66 },
67 ],
68 awaitRefetchQueries: true,
69 }).then(() => resetForm());
70 };
71
72 function resetForm() {
73 setInputProp({
74 value: '',
75 });
76 }
77
78 const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
79 e.preventDefault();
80 if (issueComment.length > 0) submit();
81 };
82
83 return (
84 <Paper className={classes.container}>
85 <form onSubmit={handleSubmit} ref={form}>
86 <CommentInput
87 inputProps={inputProp}
88 loading={loading}
89 onChange={(comment: string) => setIssueComment(comment)}
90 />
91 <div className={classes.actions}>
92 <Button
93 className={classes.greenButton}
94 variant="contained"
95 color="primary"
96 type="submit"
97 disabled={loading || issueComment.length === 0}
98 >
99 Comment
100 </Button>
101 </div>
102 </form>
103 </Paper>
104 );
105}
106
107export default CommentForm;