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