]> git.immae.eu Git - github/fretlink/time-picker.git/blame - src/module/Select.jsx
add new options about disabled time
[github/fretlink/time-picker.git] / src / module / Select.jsx
CommitLineData
02de449a 1import React, {PropTypes} from 'react';
2import ReactDom from 'react-dom';
3import classnames from 'classnames';
4
5const scrollTo = (element, to, duration) => {
0b9ef41f 6 const requestAnimationFrame = window.requestAnimationFrame ||
7 function requestAnimationFrameTimeout() {
8 return setTimeout(arguments[0], 10);
9 };
02de449a 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
0b9ef41f 18 requestAnimationFrame(() => {
02de449a 19 element.scrollTop = element.scrollTop + perTick;
20 if (element.scrollTop === to) return;
21 scrollTo(element, to, duration - 10);
0b9ef41f 22 });
02de449a 23};
24
25const Select = React.createClass({
26 propTypes: {
27 prefixCls: PropTypes.string,
28 options: PropTypes.array,
8133e8cf 29 gregorianCalendarLocale: PropTypes.object,
02de449a 30 selectedIndex: PropTypes.number,
31 type: PropTypes.string,
32 onSelect: PropTypes.func,
182e9fcc 33 onMouseEnter: PropTypes.func,
02de449a 34 },
35
36 componentDidMount() {
37 // jump to selected option
38 this.scrollToSelected(0);
39 },
40
41 componentDidUpdate() {
42 // smooth scroll to selected option
a9fbba23 43 this.scrollToSelected(120);
02de449a 44 },
45
8133e8cf 46 onSelect(value) {
02de449a 47 const { onSelect, type } = this.props;
02de449a 48 onSelect(type, value);
49 },
50
51 getOptions() {
8133e8cf 52 const { options, selectedIndex, prefixCls } = this.props;
02de449a 53 return options.map((item, index) => {
8133e8cf 54 const cls = classnames({
518b852e
M
55 [`${prefixCls}-select-option-selected`]: selectedIndex === index,
56 [`${prefixCls}-select-option-disabled`]: item.disabled,
8133e8cf 57 });
518b852e
M
58 let onclick = null;
59 if (!item.disabled) {
60 onclick = this.onSelect.bind(this, +item.value);
61 }
62 return <li className={cls} key={index} onClick={onclick} disabled={item.disabled}>{item.value}</li>;
02de449a 63 });
64 },
65
66 scrollToSelected(duration) {
67 // move to selected item
68 const select = ReactDom.findDOMNode(this);
69 const list = ReactDom.findDOMNode(this.refs.list);
5fcf22e0 70 let index = this.props.selectedIndex;
02de449a 71 if (index < 0) {
72 index = 0;
73 }
74 const topOption = list.children[index];
428cfa8d 75 const to = topOption.offsetTop;
85d09ad3 76 scrollTo(select, to, duration);
02de449a 77 },
78
79 render() {
80 if (this.props.options.length === 0) {
81 return null;
82 }
83
84 const { prefixCls } = this.props;
85
86 return (
182e9fcc 87 <div className={`${prefixCls}-select`}
88 onMouseEnter={this.props.onMouseEnter}>
02de449a 89 <ul ref="list">{this.getOptions()}</ul>
90 </div>
91 );
92 },
93});
94
95export default Select;