]> git.localhorst.tv Git - alttp.git/blob - resources/js/components/common/ToggleSwitch.js
add myustery circus link
[alttp.git] / resources / js / components / common / ToggleSwitch.js
1 import PropTypes from 'prop-types';
2 import React from 'react';
3
4 import Icon from './Icon';
5
6 const ToggleSwitch = ({
7         isInvalid = false,
8         isValid = false,
9         name = '',
10         offLabel = '',
11         onBlur = null,
12         onChange = null,
13         onLabel = null,
14         readonly = false,
15         title = null,
16         value = false,
17 }) => {
18         const toggle = () => {
19                 if (readonly) return;
20                 if (onChange) onChange({ target: { name, value: !value } });
21         };
22
23         const handleClick = event => {
24                 event.stopPropagation();
25                 toggle();
26         };
27
28         const handleKey = event => {
29                 if ([13, 32].includes(event.which)) {
30                         toggle();
31                         event.preventDefault();
32                         event.stopPropagation();
33                 }
34         };
35
36         const classNames = ['form-control', 'custom-toggle'];
37         if (value) classNames.push('is-toggled');
38         if (isInvalid) classNames.push('is-invalid');
39         if (isValid) classNames.push('is-valid');
40         if (readonly) classNames.push('readonly');
41
42         return <div
43                         className={classNames.join(' ')}
44                         role="button"
45                         aria-pressed={value}
46                         tabIndex="0"
47                         title={title}
48                         onBlur={onBlur ? () => onBlur({ target: { name, value } }) : null}
49                         onClick={handleClick}
50                         onKeyDown={handleKey}
51                 >
52                         <div className="handle">
53                                 <span className="handle-label">
54                                         {value
55                                                 ? onLabel || <Icon name="check" />
56                                                 : offLabel || <Icon name="times" />
57                                         }
58                                 </span>
59                         </div>
60                 </div>;
61 };
62
63 ToggleSwitch.propTypes = {
64         isInvalid: PropTypes.bool,
65         isValid: PropTypes.bool,
66         name: PropTypes.string,
67         offLabel: PropTypes.string,
68         onBlur: PropTypes.func,
69         onChange: PropTypes.func,
70         onLabel: PropTypes.string,
71         readonly: PropTypes.bool,
72         title: PropTypes.string,
73         value: PropTypes.bool,
74 };
75
76 export default ToggleSwitch;