aboutsummaryrefslogtreecommitdiff
path: root/src/pages/FeedPage/PollSubmission.tsx
blob: 42612f069f24be5b5a47257f0613c6cf9797cda2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Collapse from '@material-ui/core/Collapse';
import {
  Button,
  Card,
  ClickAwayListener,
  Divider
} from '@material-ui/core';
import { User, Poll, Which } from 'which-types';
import PollSubmissionImage from './PollSubmissionImage';
import UserStrip from '../../components/UserStrip/UserStrip';
import { post } from '../../requests';
import { Contents } from './types';
import { useAuth } from '../../hooks/useAuth';

interface PropTypes{
  addPoll: (poll: Poll) => void;
}

const useStyles = makeStyles(theme => ({
  root: {
    height: theme.spacing(50),
    display: 'flex'
  }
}));

const emptyContents: Contents = {
  left: { url: '' },
  right: { url: '' }
};

const PollSubmission: React.FC<PropTypes> = ({ addPoll }) => {
  const classes = useStyles();
  const [expanded, setExpanded] = useState(false);
  const [contents, setContents] = useState<Contents>(emptyContents);
  const { user } = useAuth();

  const readyToSubmit = contents.left.url && contents.right.url;

  const setUrl = (which: Which) => (url: string): void => {
    setContents({ ...contents, [which]: { url } });
  };

  const handleClickAway = () => {
    setExpanded(false);
  };

  const handleClick = () => {
    if (expanded && readyToSubmit) {
      post('/polls/', { contents }).then(response => {
        addPoll(response.data);
      });
      setContents({ ...emptyContents });
    }
    setExpanded(!expanded);
  };

  return (
    <ClickAwayListener onClickAway={handleClickAway}>
      <Card>
        <Collapse in={expanded} timeout="auto" unmountOnExit>
          {user && <UserStrip user={user} info="" />}
          <Divider />
          <div className={classes.root}>
            <PollSubmissionImage url={contents.left.url} setUrl={setUrl('left')} />
            <PollSubmissionImage url={contents.right.url} setUrl={setUrl('right')} />
          </div>
        </Collapse>
        <Button
          color="primary"
          disabled={expanded && !readyToSubmit}
          variant={expanded ? 'contained' : 'outlined'}
          onClick={handleClick}
          fullWidth
        >
          {expanded ? 'Submit' : 'Create a Poll'}
        </Button>
      </Card>
    </ClickAwayListener>
  );
};

export default PollSubmission;