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