1 | import _extends from "@babel/runtime/helpers/esm/extends";
|
2 | import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
|
3 | var _excluded = ["children", "type", "name", "value", "onChange"];
|
4 | import React from 'react';
|
5 | import invariant from 'invariant';
|
6 | import { useUncontrolled } from 'uncontrollable';
|
7 | import chainFunction from './createChainedFunction';
|
8 | import { map } from './ElementChildren';
|
9 | import ButtonGroup from './ButtonGroup';
|
10 | import ToggleButton from './ToggleButton';
|
11 | var defaultProps = {
|
12 | type: 'radio',
|
13 | vertical: false
|
14 | };
|
15 | var ToggleButtonGroup = React.forwardRef(function (props, ref) {
|
16 | var _useUncontrolled = useUncontrolled(props, {
|
17 | value: 'onChange'
|
18 | }),
|
19 | children = _useUncontrolled.children,
|
20 | type = _useUncontrolled.type,
|
21 | name = _useUncontrolled.name,
|
22 | value = _useUncontrolled.value,
|
23 | onChange = _useUncontrolled.onChange,
|
24 | controlledProps = _objectWithoutPropertiesLoose(_useUncontrolled, _excluded);
|
25 |
|
26 | var getValues = function getValues() {
|
27 | return value == null ? [] : [].concat(value);
|
28 | };
|
29 |
|
30 | var handleToggle = function handleToggle(inputVal, event) {
|
31 | if (!onChange) {
|
32 | return;
|
33 | }
|
34 |
|
35 | var values = getValues();
|
36 | var isActive = values.indexOf(inputVal) !== -1;
|
37 |
|
38 | if (type === 'radio') {
|
39 | if (!isActive && onChange) onChange(inputVal, event);
|
40 | return;
|
41 | }
|
42 |
|
43 | if (isActive) {
|
44 | onChange(values.filter(function (n) {
|
45 | return n !== inputVal;
|
46 | }), event);
|
47 | } else {
|
48 | onChange([].concat(values, [inputVal]), event);
|
49 | }
|
50 | };
|
51 |
|
52 | !(type !== 'radio' || !!name) ? process.env.NODE_ENV !== "production" ? invariant(false, 'A `name` is required to group the toggle buttons when the `type` ' + 'is set to "radio"') : invariant(false) : void 0;
|
53 | return React.createElement(ButtonGroup, _extends({}, controlledProps, {
|
54 | ref: ref,
|
55 | toggle: true
|
56 | }), map(children, function (child) {
|
57 | var values = getValues();
|
58 | var _child$props = child.props,
|
59 | childVal = _child$props.value,
|
60 | childOnChange = _child$props.onChange;
|
61 |
|
62 | var handler = function handler(e) {
|
63 | return handleToggle(childVal, e);
|
64 | };
|
65 |
|
66 | return React.cloneElement(child, {
|
67 | type: type,
|
68 | name: child.name || name,
|
69 | checked: values.indexOf(childVal) !== -1,
|
70 | onChange: chainFunction(childOnChange, handler)
|
71 | });
|
72 | }));
|
73 | });
|
74 | ToggleButtonGroup.defaultProps = defaultProps;
|
75 | ToggleButtonGroup.Button = ToggleButton;
|
76 | export default ToggleButtonGroup; |
\ | No newline at end of file |