1
0
mirror of https://github.com/kremalicious/umami.git synced 2024-12-22 09:13:37 +01:00
umami/components/common/MenuButton.js

84 lines
2.0 KiB
JavaScript
Raw Normal View History

2020-09-21 06:31:53 +02:00
import React, { useState, useRef } from 'react';
import PropTypes from 'prop-types';
2020-09-21 06:31:53 +02:00
import classNames from 'classnames';
import Menu from 'components/common/Menu';
import Button from 'components/common/Button';
import useDocumentClick from 'hooks/useDocumentClick';
import styles from './MenuButton.module.css';
function MenuButton({
2020-09-21 06:31:53 +02:00
icon,
value,
options,
2020-10-04 03:05:46 +02:00
buttonClassName,
menuClassName,
2020-09-21 06:31:53 +02:00
menuPosition = 'bottom',
menuAlign = 'right',
onSelect,
renderValue,
}) {
const [showMenu, setShowMenu] = useState(false);
const ref = useRef();
const selectedOption = options.find(e => e.value === value);
function handleSelect(value) {
onSelect(value);
setShowMenu(false);
}
function toggleMenu() {
setShowMenu(state => !state);
}
useDocumentClick(e => {
2021-01-21 04:11:36 +01:00
if (!ref.current?.contains(e.target)) {
2020-09-21 06:31:53 +02:00
setShowMenu(false);
}
});
return (
<div className={styles.container} ref={ref}>
<Button
icon={icon}
2020-10-04 03:05:46 +02:00
className={classNames(styles.button, buttonClassName, { [styles.open]: showMenu })}
2020-09-21 06:31:53 +02:00
onClick={toggleMenu}
variant="light"
>
<div className={styles.text}>{renderValue ? renderValue(selectedOption) : value}</div>
</Button>
{showMenu && (
<Menu
2020-10-04 03:05:46 +02:00
className={menuClassName}
2020-09-21 06:31:53 +02:00
options={options}
selectedOption={selectedOption}
onSelect={handleSelect}
float={menuPosition}
align={menuAlign}
/>
)}
</div>
);
}
MenuButton.propTypes = {
icon: PropTypes.node,
value: PropTypes.any,
options: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.node,
value: PropTypes.any,
className: PropTypes.string,
render: PropTypes.func,
divider: PropTypes.bool,
}),
),
buttonClassName: PropTypes.string,
menuClassName: PropTypes.string,
menuPosition: PropTypes.oneOf(['top', 'bottom']),
menuAlign: PropTypes.oneOf(['left', 'right']),
onSelect: PropTypes.func,
renderValue: PropTypes.func,
};
export default MenuButton;