CommentInput.tsx

  1import React, { useState, useRef, useEffect } from 'react';
  2
  3import Button from '@material-ui/core/Button';
  4import Paper from '@material-ui/core/Paper';
  5import Tab from '@material-ui/core/Tab';
  6import Tabs from '@material-ui/core/Tabs';
  7import TextField from '@material-ui/core/TextField';
  8import { makeStyles, Theme } from '@material-ui/core/styles';
  9
 10import Content from 'src/components/Content';
 11
 12import { useAddCommentMutation } from './CommentForm.generated';
 13import { TimelineDocument } from './TimelineQuery.generated';
 14
 15const useStyles = makeStyles((theme) => ({
 16  container: {
 17    margin: theme.spacing(2, 0),
 18    padding: theme.spacing(0, 2, 2, 2),
 19  },
 20  textarea: {},
 21  tabContent: {
 22    margin: theme.spacing(2, 0),
 23  },
 24  preview: {
 25    borderBottom: `solid 3px ${theme.palette.grey['200']}`,
 26    minHeight: '5rem',
 27  },
 28  actions: {
 29    display: 'flex',
 30    justifyContent: 'flex-end',
 31  },
 32}));
 33
 34type TabPanelProps = {
 35  children: React.ReactNode;
 36  value: number;
 37  index: number;
 38} & React.HTMLProps<HTMLDivElement>;
 39function TabPanel({ children, value, index, ...props }: TabPanelProps) {
 40  return (
 41    <div
 42      role="tabpanel"
 43      hidden={value !== index}
 44      id={`editor-tabpanel-${index}`}
 45      aria-labelledby={`editor-tab-${index}`}
 46      {...props}
 47    >
 48      {value === index && children}
 49    </div>
 50  );
 51}
 52
 53const a11yProps = (index: number) => ({
 54  id: `editor-tab-${index}`,
 55  'aria-controls': `editor-tabpanel-${index}`,
 56});
 57
 58type Props = {
 59  loading: boolean;
 60  onChange: (comment: string) => void;
 61};
 62
 63function CommentInput({ loading, onChange }: Props) {
 64  const [input, setInput] = useState<string>('');
 65  const [tab, setTab] = useState(0);
 66  const classes = useStyles();
 67
 68  useEffect(() => {
 69    onChange(input);
 70  }, [input]);
 71
 72  return (
 73    <div>
 74      <Tabs value={tab} onChange={(_, t) => setTab(t)}>
 75        <Tab label="Write" {...a11yProps(0)} />
 76        <Tab label="Preview" {...a11yProps(1)} />
 77      </Tabs>
 78      <div className={classes.tabContent}>
 79        <TabPanel value={tab} index={0}>
 80          <TextField
 81            fullWidth
 82            label="Comment"
 83            placeholder="Leave a comment"
 84            className={classes.textarea}
 85            multiline
 86            value={input}
 87            variant="filled"
 88            rows="4" // TODO: rowsMin support
 89            onChange={(e: any) => setInput(e.target.value)}
 90            disabled={loading}
 91          />
 92        </TabPanel>
 93        <TabPanel value={tab} index={1} className={classes.preview}>
 94          <Content markdown={input} />
 95        </TabPanel>
 96      </div>
 97    </div>
 98  );
 99}
100
101export default CommentInput;