UNPKG

2.06 kBJSXView Raw
1/*
2 * <ColorPicker
3 * onUpdate=required func to handle updates
4 * index=number
5 * className=string
6 * numColors=required number of colors to include (handled in css)
7 * >
8 */
9
10var React = require("react/addons");
11var PureRenderMixin = React.addons.PureRenderMixin;
12var cx = React.addons.classSet;
13var PropTypes = React.PropTypes;
14
15var ColorPicker = React.createClass({
16
17 propTypes: {
18 index: PropTypes.number,
19 onChange: PropTypes.func.isRequired,
20 className: PropTypes.string,
21 numColors: PropTypes.number.isRequired
22 },
23
24 mixins: [ PureRenderMixin ],
25
26 getInitialState: function() {
27 return { active: false };
28 },
29
30 _togglePicker: function(e) {
31 if (this.state.active) {
32 e.stopPropagation();
33 document.body.removeEventListener('click', this._togglePicker);
34 } else {
35 document.body.addEventListener('click', this._togglePicker);
36 }
37 this.setState({ active: !this.state.active });
38 },
39
40 _handleInput: function(colorIndex) {
41 this.props.onChange(colorIndex);
42 },
43
44 render: function() {
45 var self = this;
46 var colorPickerEls = [];
47
48 for (var i = 0, l = this.props.numColors; i < l; i++) {
49 colorPickerEls.push(
50 <ColorPickerEl
51 onChange={this._handleInput.bind(null, i)}
52 index={i}
53 key={i}
54 />
55 );
56 }
57
58 var className = cx({
59 "cb-colorpicker-els": true,
60 "active": this.state.active
61 });
62
63 return (
64 <div className="cb-colorpicker">
65 <div
66 className={"cb-colorpicker-current cb-colorpicker-color-" + this.props.colorIndex}
67 onClick={this._togglePicker}
68 />
69 <div className={className}>
70 {colorPickerEls}
71 </div>
72 </div>
73 );
74 }
75
76});
77
78var ColorPickerEl = React.createClass({
79
80 shouldComponentUpdate: function(nextProps, nextState) {
81 return (this.props.index !== nextProps.index);
82 },
83
84 render: function() {
85 return (
86 <div
87 className={"cb-colorpicker-el cb-colorpicker-color-" + this.props.index}
88 onClick={this.props.onChange.bind(null, this.props.index)}
89 onMouseOver={this.props.onChange.bind(null, this.props.index)}
90 />
91 );
92 }
93
94});
95
96module.exports = ColorPicker;