react-toolbox/components/dropdown/index.jsx

85 lines
2.4 KiB
React
Raw Normal View History

import React from 'react';
2015-10-09 16:55:00 +03:00
import style from './style';
2015-09-19 18:42:57 +03:00
2015-10-22 02:31:17 +03:00
class Dropdown extends React.Component {
static propTypes = {
auto: React.PropTypes.bool,
2015-09-19 18:42:57 +03:00
className: React.PropTypes.string,
disabled: React.PropTypes.bool,
label: React.PropTypes.string,
onChange: React.PropTypes.func,
source: React.PropTypes.array.isRequired,
2015-09-19 18:42:57 +03:00
template: React.PropTypes.func,
value: React.PropTypes.string
};
static defaultProps = {
auto: true,
className: '',
disabled: false
};
state = {
active: false,
up: false
};
2015-09-19 18:42:57 +03:00
2015-10-22 02:31:17 +03:00
handleClick = (event) => {
const client = event.target.getBoundingClientRect();
const screen_height = window.innerHeight || document.documentElement.offsetHeight;
const up = this.props.auto ? client.top > ((screen_height / 2) + client.height) : false;
this.setState({active: true, up});
2015-10-22 02:31:17 +03:00
};
2015-09-19 18:42:57 +03:00
handleSelect = (item) => {
if (!this.props.disabled && this.props.onChange) {
this.props.onChange(item);
this.setState({active: false});
2015-09-19 18:42:57 +03:00
}
2015-10-22 02:31:17 +03:00
};
2015-09-19 18:42:57 +03:00
getSelectedItem = () => {
if (this.props.value) {
for (const item of this.props.source) {
if (item.value === this.props.value) return item;
}
} else {
return this.props.source[0];
}
};
2015-10-09 16:55:00 +03:00
renderItem (item, idx) {
const className = item.value === this.props.value ? style.selected : null;
return (
<li key={idx} className={className} onMouseDown={this.handleSelect.bind(this, item.value)}>
{ this.props.template ? this.props.template(item) : item.label }
</li>
);
}
2015-10-09 16:55:00 +03:00
render () {
let className = style.root;
const selected = this.getSelectedItem();
if (this.state.up) className += ` ${style.up}`;
2015-10-09 16:55:00 +03:00
if (this.state.active) className += ` ${style.active}`;
if (this.props.disabled) className += ` ${style.disabled}`;
if (this.props.className) className += ` ${this.props.className}`;
2015-10-09 16:55:00 +03:00
2015-09-19 18:42:57 +03:00
return (
<div data-react-toolbox='dropdown' className={className}>
{ this.props.label ? <label className={style.label}>{this.props.label}</label> : null }
<ul ref='values' className={style.values}>
{ this.props.source.map(this.renderItem.bind(this)) }
</ul>
2015-10-09 16:55:00 +03:00
<div ref='value' className={style.value} onClick={this.handleClick}>
{ this.props.template ? this.props.template(selected) : <span>{selected.label}</span> }
2015-09-19 18:42:57 +03:00
</div>
</div>
);
}
2015-10-21 13:25:07 +03:00
}
2015-10-22 02:31:17 +03:00
export default Dropdown;