2017-06-04 10:40:14 +08:00
|
|
|
import React, { Component } from 'react';
|
|
|
|
import PropTypes from 'prop-types';
|
2016-09-07 03:10:18 +08:00
|
|
|
import { findDOMNode } from 'react-dom';
|
2016-09-15 01:48:50 +08:00
|
|
|
import cx from 'classnames';
|
2016-09-07 03:10:18 +08:00
|
|
|
|
|
|
|
import KEY_CODES from '/imports/utils/keyCodes';
|
2016-09-02 04:19:37 +08:00
|
|
|
|
|
|
|
const propTypes = {
|
2017-06-04 10:40:14 +08:00
|
|
|
children: PropTypes.element.isRequired,
|
2016-09-02 04:19:37 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
export default class DropdownTrigger extends Component {
|
|
|
|
constructor(props) {
|
|
|
|
super(props);
|
2016-09-07 03:10:18 +08:00
|
|
|
this.handleClick = this.handleClick.bind(this);
|
|
|
|
this.handleKeyDown = this.handleKeyDown.bind(this);
|
|
|
|
}
|
|
|
|
|
|
|
|
handleClick() {
|
|
|
|
const { dropdownToggle } = this.props;
|
|
|
|
return dropdownToggle();
|
|
|
|
}
|
|
|
|
|
|
|
|
handleKeyDown(event) {
|
2017-06-03 03:25:02 +08:00
|
|
|
const { dropdownShow, dropdownHide } = this.props;
|
2016-09-07 03:10:18 +08:00
|
|
|
|
|
|
|
if ([KEY_CODES.SPACE, KEY_CODES.ENTER].includes(event.which)) {
|
2016-09-07 22:43:54 +08:00
|
|
|
event.preventDefault();
|
|
|
|
event.stopPropagation();
|
2016-09-07 20:04:10 +08:00
|
|
|
|
2016-09-07 03:10:18 +08:00
|
|
|
return findDOMNode(this).click();
|
|
|
|
}
|
|
|
|
|
|
|
|
if ([KEY_CODES.ARROW_UP, KEY_CODES.ARROW_DOWN].includes(event.which)) {
|
|
|
|
dropdownShow();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (KEY_CODES.ESCAPE === event.which) {
|
|
|
|
dropdownHide();
|
|
|
|
}
|
2016-09-02 04:19:37 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
render() {
|
2017-10-13 08:20:27 +08:00
|
|
|
const remainingProps = { ...this.props };
|
2017-10-12 03:11:04 +08:00
|
|
|
delete remainingProps.dropdownToggle;
|
|
|
|
delete remainingProps.dropdownShow;
|
|
|
|
delete remainingProps.dropdownHide;
|
2018-04-16 23:59:16 +08:00
|
|
|
delete remainingProps.dropdownIsOpen;
|
2017-10-12 03:11:04 +08:00
|
|
|
|
|
|
|
const {
|
|
|
|
children,
|
|
|
|
className,
|
|
|
|
...restProps
|
|
|
|
} = remainingProps;
|
|
|
|
|
2016-09-02 04:19:37 +08:00
|
|
|
const TriggerComponent = React.Children.only(children);
|
|
|
|
|
2017-10-06 04:13:29 +08:00
|
|
|
const TriggerComponentBounded = React.cloneElement(TriggerComponent, {
|
|
|
|
...restProps,
|
2016-09-07 03:10:18 +08:00
|
|
|
onClick: this.handleClick,
|
|
|
|
onKeyDown: this.handleKeyDown,
|
2016-09-02 04:19:37 +08:00
|
|
|
'aria-haspopup': true,
|
2016-09-15 01:48:50 +08:00
|
|
|
className: cx(children.props.className, className),
|
2016-09-02 04:19:37 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
return TriggerComponentBounded;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
DropdownTrigger.propTypes = propTypes;
|