2020-07-15 08:06:14 +00:00
|
|
|
// @flow
|
|
|
|
|
2021-06-10 12:48:44 +00:00
|
|
|
import React, { useCallback } from 'react';
|
2020-07-15 08:06:14 +00:00
|
|
|
|
|
|
|
import { Icon, IconCheck } from '../../../icons';
|
|
|
|
|
|
|
|
const mainClass = 'toggle-button';
|
|
|
|
|
|
|
|
type Props = {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Text of the button.
|
|
|
|
*/
|
|
|
|
children: React$Node,
|
|
|
|
|
|
|
|
/**
|
|
|
|
* If the button is toggled or not.
|
|
|
|
*/
|
|
|
|
isToggled?: boolean,
|
|
|
|
|
|
|
|
/**
|
|
|
|
* OnClick button handler.
|
|
|
|
*/
|
|
|
|
onClick: Function
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Button used as a toggle.
|
|
|
|
*
|
|
|
|
* @returns {ReactElement}
|
|
|
|
*/
|
|
|
|
function ToggleButton({ children, isToggled, onClick }: Props) {
|
|
|
|
const className = isToggled ? `${mainClass} ${mainClass}--toggled` : mainClass;
|
|
|
|
|
2021-06-10 12:48:44 +00:00
|
|
|
const onKeyPressHandler = useCallback(e => {
|
|
|
|
if (onClick && (e.key === ' ')) {
|
|
|
|
e.preventDefault();
|
|
|
|
onClick();
|
|
|
|
}
|
|
|
|
}, [ onClick ]);
|
|
|
|
|
2020-07-15 08:06:14 +00:00
|
|
|
return (
|
|
|
|
<div
|
2021-06-10 12:48:44 +00:00
|
|
|
aria-checked = { isToggled }
|
2020-07-15 08:06:14 +00:00
|
|
|
className = { className }
|
2021-06-10 12:48:44 +00:00
|
|
|
id = 'toggle-button'
|
|
|
|
onClick = { onClick }
|
|
|
|
onKeyPress = { onKeyPressHandler }
|
|
|
|
role = 'switch'
|
|
|
|
tabIndex = { 0 }>
|
2020-07-15 08:06:14 +00:00
|
|
|
<div className = 'toggle-button-container'>
|
|
|
|
<div className = 'toggle-button-icon-container'>
|
|
|
|
<Icon
|
|
|
|
className = 'toggle-button-icon'
|
|
|
|
size = { 10 }
|
|
|
|
src = { IconCheck } />
|
|
|
|
</div>
|
2021-06-10 12:48:44 +00:00
|
|
|
<label htmlFor = 'toggle-button'>{children}</label>
|
2020-07-15 08:06:14 +00:00
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export default ToggleButton;
|