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 '../../components/CommentInput/CommentInput';
8
9import { BugFragment } from './Bug.generated';
10import { useAddCommentMutation } from './CommentForm.generated';
11import { TimelineDocument } from './TimelineQuery.generated';
12
13type StyleProps = { loading: boolean };
14const useStyles = makeStyles<Theme, StyleProps>((theme) => ({
15 container: {
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 marginLeft: '8px',
32 backgroundColor: '#2ea44fd9',
33 color: '#fff',
34 '&:hover': {
35 backgroundColor: '#2ea44f',
36 },
37 },
38}));
39
40type Props = {
41 bug: BugFragment;
42 commentId: string;
43 onCancleClick?: () => void;
44};
45
46function EditCommentForm({ bug, commentId, onCancleClick }: Props) {
47 const [addComment, { loading }] = useAddCommentMutation();
48 const [issueComment, setIssueComment] = useState('');
49 const [inputProp, setInputProp] = useState<any>('');
50 const classes = useStyles({ loading });
51 const form = useRef<HTMLFormElement>(null);
52
53 const submit = () => {
54 addComment({
55 variables: {
56 input: {
57 prefix: bug.id,
58 message: issueComment,
59 },
60 },
61 refetchQueries: [
62 // TODO: update the cache instead of refetching
63 {
64 query: TimelineDocument,
65 variables: {
66 id: bug.id,
67 first: 100,
68 },
69 },
70 ],
71 awaitRefetchQueries: true,
72 }).then(() => resetForm());
73 };
74
75 function resetForm() {
76 setInputProp({
77 value: '',
78 });
79 }
80
81 const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
82 e.preventDefault();
83 if (issueComment.length > 0) submit();
84 };
85
86 function getCancleButton() {
87 return (
88 <Button onClick={onCancleClick} variant="contained">
89 Cancle
90 </Button>
91 );
92 }
93
94 return (
95 <Paper className={classes.container}>
96 <form onSubmit={handleSubmit} ref={form}>
97 <CommentInput
98 inputProps={inputProp}
99 loading={loading}
100 onChange={(comment: string) => setIssueComment(comment)}
101 />
102 <div className={classes.actions}>
103 {onCancleClick ? getCancleButton() : ''}
104 <Button
105 className={classes.greenButton}
106 variant="contained"
107 color="primary"
108 type="submit"
109 disabled={loading || issueComment.length === 0}
110 >
111 Update Comment
112 </Button>
113 </div>
114 </form>
115 </Paper>
116 );
117}
118
119export default EditCommentForm;