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
|
import React, {useState} from 'react';
import { makeStyles } from '@material-ui/core/styles';
import {
Card,
CardActionArea,
CardMedia,
Avatar,
CardHeader
} from '@material-ui/core/';
import { Poll } from '../../types';
import PercentageBar from './PercentageBar';
import {post} from '../../requests';
import teal from "@material-ui/core/colors/teal";
interface PropTypes {
poll: Poll;
navigate: (prefix: string, id: string) => void;
}
const useStyles = makeStyles(theme => ({
root: {
maxWidth: theme.spacing(75),
height: 488,
margin: '40px auto',
},
images: {
height: theme.spacing(50),
width: 300
},
imagesBlock: {
display: 'flex'
},
avatar: {
cursor: 'pointer'
},
rateLine: {
position:'relative',
margin: '0 auto',
width: '100%',
height:16,
backgroundColor: teal[100]
},
fillRateLine: {
height:16,
backgroundColor: teal[800],
transitionDuration: '0.5s'
},
}));
const PollCard: React.FC<PropTypes> = ({ poll, navigate }) => {
const classes = useStyles();
const { author, contents } = poll;
const [rate, setRate] = useState<{left: number, right: number}>({left: contents.left.votes,right: contents.right.votes});
const handleNavigate = () => {
navigate('profile', poll.author._id);
};
const vote = (which: 'left' | 'right') => {
post(`polls/${ poll._id }/votes/`,{ which }).then((response)=>{
console.log(response.data);
const leftV = response.data.contents.left.votes;
const rightV = response.data.contents.right.votes;
setRate({left: leftV, right: rightV});
})
.catch(error => {
console.log(error.response)
});
};
const leftPercentage = Math.round(100 * (rate.left / (rate.left + rate.right)));
const rightPercentage = 100 - leftPercentage;
return (
<Card className={classes.root}>
<CardHeader
avatar={(
<Avatar
aria-label="avatar"
src={author.avatarUrl}
alt={author.name[0].toUpperCase()}
onClick={handleNavigate}
className={classes.avatar}
/>
)}
title={author.name}
/>
<div className={classes.imagesBlock}>
<CardActionArea onDoubleClick={() => vote('left')}>
<CardMedia
className={classes.images}
image={contents.left.url}
/>
<PercentageBar value={leftPercentage} which="left" />
</CardActionArea>
<CardActionArea onDoubleClick={() => vote('right')}>
<CardMedia
className={classes.images}
image={contents.right.url}
/>
<PercentageBar value={rightPercentage} which="right" />
</CardActionArea>
</div>
<div className={classes.rateLine}>
<div className={classes.fillRateLine} style={{width: `${leftPercentage}%`}} />
</div>
</Card>
);
};
export default PollCard;
|