aboutsummaryrefslogtreecommitdiff
path: root/src/components/PollCard/PollCard.tsx
blob: 64fab34763a07e15a630425cb815e14e93fc3400 (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Card, CardActionArea, Typography } from '@material-ui/core/';
import { Which, Poll } from 'which-types';
import { useSnackbar } from 'notistack';

import PercentageBar from './PercentageBar';
import UserStrip from '../UserStrip/UserStrip';
import BackgroundImage from '../Image/BackgroundImage';
import { post } from '../../requests';
import { useAuth } from '../../hooks/useAuth';

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

const DATE_FORMAT = {
  month: 'long',
  day: 'numeric',
  year: 'numeric',
  hour: '2-digit',
  minute: '2-digit'
};

const useStyles = makeStyles(theme => ({
  media: {
    display: 'flex',
    height: theme.spacing(50)
  },
  rateLine: {
    position: 'relative',
    width: '100%',
    height: theme.spacing(2),
    backgroundColor: theme.palette.primary.light,
    transitionDuration: '0.5s'
  },
  highlight: {
    backgroundColor: `${theme.palette.primary.main} !important`
  },
  fillRateLine: {
    height: theme.spacing(2),
    backgroundColor: theme.palette.primary.light,
    transitionDuration: '0.5s'
  },
  description: {
    fontSize: 14,
    padding: theme.spacing(0, 2, 1.25),
    wordWrap: 'break-word',
    whiteSpace: 'pre-wrap'
  }
}));

const PollCard: React.FC<PropTypes> = React.memo(({ poll, setPoll }) => {
  const classes = useStyles();
  const { author, contents: { left, right }, vote } = poll;
  const { enqueueSnackbar } = useSnackbar();
  const { isAuthenticated } = useAuth();
  const date: string = new Date(poll.createdAt).toLocaleString('default', DATE_FORMAT);

  const handleVote = (which: Which) => () => {
    if (!isAuthenticated) {
      enqueueSnackbar('Unauthorized users can not vote in polls', {
        variant: 'error'
      });
    } else if (vote) {
      enqueueSnackbar('You have already voted in this poll', {
        variant: 'error'
      });
    } else {
      const newVote = ({ which, pollId: poll._id });
      const newPoll = { ...poll };
      newPoll.contents[which].votes += 1;
      newPoll.vote = {
        _id: '',
        authorId: '',
        createdAt: new Date(),
        ...newVote
      };
      setPoll(newPoll);

      post('votes/', newVote);
    }
  };

  let leftPercentage;
  let rightPercentage;

  if (left.votes || right.votes) {
    leftPercentage = Math.round(100 * (left.votes / (left.votes + right.votes)));
    rightPercentage = 100 - leftPercentage;
  } else {
    leftPercentage = 0;
    rightPercentage = 0;
  }

  const dominant: Which = left.votes >= right.votes ? 'left' : 'right';

  return (
    <Card elevation={3}>
      <UserStrip user={author} info={date} />
      {poll.description && (
        <Typography className={classes.description}>
          {poll.description}
        </Typography>
      )}
      <div className={classes.media}>
        <CardActionArea onDoubleClick={handleVote('left')} className={classes.media}>
          <BackgroundImage src={left.url} />
          <PercentageBar value={leftPercentage} which="left" like={vote?.which === 'left'} />
        </CardActionArea>
        <CardActionArea onDoubleClick={handleVote('right')} className={classes.media}>
          <BackgroundImage src={right.url} />
          <PercentageBar value={rightPercentage} which="right" like={vote?.which === 'right'} />
        </CardActionArea>
      </div>
      <div className={`${classes.rateLine} ${dominant === 'right' ? classes.highlight : ''}`}>
        <div
          className={`${classes.fillRateLine} ${dominant === 'left' ? classes.highlight : ''}`}
          style={{ width: `${leftPercentage}%` }}
        />
      </div>
    </Card>
  );
});

export default PollCard;