]> git.immae.eu Git - github/fretlink/time-picker.git/blob - src/module/Select.jsx
add gregorianCalendarLocale prop
[github/fretlink/time-picker.git] / src / module / Select.jsx
1 import React, {PropTypes} from 'react';
2 import ReactDom from 'react-dom';
3 import classnames from 'classnames';
4
5 const scrollTo = (element, to, duration) => {
6 // jump to target if duration zero
7 if (duration <= 0) {
8 element.scrollTop = to;
9 return;
10 }
11 const difference = to - element.scrollTop;
12 const perTick = difference / duration * 10;
13
14 setTimeout(() => {
15 element.scrollTop = element.scrollTop + perTick;
16 if (element.scrollTop === to) return;
17 scrollTo(element, to, duration - 10);
18 }, 10);
19 };
20
21 const Select = React.createClass({
22 propTypes: {
23 prefixCls: PropTypes.string,
24 options: PropTypes.array,
25 gregorianCalendarLocale: PropTypes.object,
26 selectedIndex: PropTypes.number,
27 type: PropTypes.string,
28 onSelect: PropTypes.func,
29 },
30
31 componentDidMount() {
32 // jump to selected option
33 this.scrollToSelected(0);
34 },
35
36 componentDidUpdate() {
37 // smooth scroll to selected option
38 this.scrollToSelected(200);
39 },
40
41 onSelect(value) {
42 const { onSelect, type } = this.props;
43 onSelect(type, value);
44 },
45
46 getOptions() {
47 const { options, selectedIndex, prefixCls } = this.props;
48 return options.map((item, index) => {
49 const selected = selectedIndex === index;
50 const cls = classnames({
51 [`${prefixCls}-select-option-selected`]: selected,
52 });
53 return <li className={cls} key={index} onClick={this.onSelect.bind(this, +item)}>{item}</li>;
54 });
55 },
56
57 scrollToSelected(duration) {
58 // move to selected item
59 const select = ReactDom.findDOMNode(this);
60 const list = ReactDom.findDOMNode(this.refs.list);
61 let index = this.props.selectedIndex - 2;
62 if (index < 0) {
63 index = 0;
64 }
65 const topOption = list.children[index];
66 const to = topOption.offsetTop - select.offsetTop;
67 scrollTo(select, to, duration);
68 },
69
70 render() {
71 if (this.props.options.length === 0) {
72 return null;
73 }
74
75 const { prefixCls } = this.props;
76
77 return (
78 <div className={`${prefixCls}-select`}>
79 <ul ref="list">{this.getOptions()}</ul>
80 </div>
81 );
82 },
83 });
84
85 export default Select;