/
rating.html
98 lines (81 loc) · 2.74 KB
/
rating.html
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
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/store.js/1.3.20/store.min.js"></script>
<div class="product-stars"></div>
<script type="text/babel">
var Star = React.createClass({
render: function() {
var parent = this.props.parent;
var className = "fa ";
if (parent.state.rating >= this.props.rating) {
className += "fa-star";
} else {
className += "fa-star-o";
}
return (
<a className={className}
href="#"
onClick={this.props.onClick.bind(null, this)}></a>
)
}
});
var ProductRater = React.createClass({
getInitialState: function() {
return {
rating: 0,
score: 0,
votes: 0,
message: null
}
},
componentDidMount: function() {
Snipcart.api.products.metadata(this.props.productId)
.then(this.updateScore);
},
updateScore: function (meta) {
if (meta && meta.score && meta.votes) {
var rating = Math.round(meta.score / meta.votes);
this.setState({votes: meta.votes, score: meta.score, rating: rating})
}
},
starClicked: function(component, evnt) {
var ratedOn = store.get('ratedOn:' + this.props.productId);
if (ratedOn) {
this.toggleMessage('Looks like you already rated this product.');
return;
}
var e = evnt;
var votes = this.state.votes + 1;
var score = this.state.score + component.props.rating;
store.set('ratedOn:' + this.props.productId, new Date());
Snipcart.api.products.metadata(this.props.productId, {
votes: votes,
score: score
})
.then (this.updateScore)
.then (() => {
this.toggleMessage('Your vote has been recorded!');
});
},
toggleMessage: function (message) {
this.setState({message: message});
window.setTimeout(() => {
this.setState({message: null})
}, 5000);
},
render: function() {
var stars = []
for (var i = 1; i <= 5; i++) {
stars.push(<Star parent={this} onClick={this.starClicked} rating={i} key={i} />)
}
return (
<div>
<div>{stars}</div>
<span className="flash-message">{this.state.message}</span>
</div>
)
}
});
ReactDOM.render(<ProductRater productId="{{ page.sku }}"/>, document.querySelector('.product-stars'));
</script>