-
Notifications
You must be signed in to change notification settings - Fork 12
/
SegmentedControl.js
106 lines (92 loc) · 2.37 KB
/
SegmentedControl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { __ } from '@wordpress/i18n';
import { contextConnect, useContextSystem } from '@wp-g2/context';
import { cx } from '@wp-g2/styles';
import { mergeRefs, noop, useResizeAware, useUpdateEffect } from '@wp-g2/utils';
import React, { useRef } from 'react';
import { RadioGroup, useRadioState } from 'reakit';
import { View } from '../View';
import * as styles from './SegmentedControl.styles';
import Backdrop from './SegmentedControlBackdrop';
import Button from './SegmentedControlButton';
function SegmentControl(props, forwardedRef) {
const {
className,
baseId,
isAdaptiveWidth = false,
isBlock = false,
id,
label = __('SegmentControl'),
options = [],
onChange = noop,
size = 'medium',
value,
...otherProps
} = useContextSystem(props, 'SegmentedControl');
const containerRef = useRef();
const [resizeListener, sizes] = useResizeAware();
const radio = useRadioState({
baseId: baseId || id,
unstable_virtual: true,
state: value || options[0]?.value,
});
// Propagate radio.state change
useUpdateEffect(() => {
onChange(radio.state);
}, [radio.state]);
// Sync incoming value with radio.state
useUpdateEffect(() => {
if (value !== radio.state) {
radio.setState(value);
}
}, [value]);
const classes = cx(
styles.SegmentedControl,
isBlock && styles.block,
styles[size],
className,
);
return (
<RadioGroup
{...radio}
aria-label={label}
as={View}
className={classes}
{...otherProps}
ref={mergeRefs([containerRef, forwardedRef])}
>
{resizeListener}
<Backdrop
{...radio}
containerRef={containerRef}
containerWidth={sizes.width}
/>
{options.map((option, index) => {
const showSeparator = getShowSeparator(radio, index);
return (
<Button
{...radio}
{...option}
isBlock={!isAdaptiveWidth}
key={option.value || index}
showSeparator={showSeparator}
/>
);
})}
</RadioGroup>
);
}
function getShowSeparator(radio, index) {
const { currentId, items } = radio;
const isLast = index === items.length - 1;
const isActive = items[index]?.id === currentId;
const isNextActive = items[index + 1]?.id === currentId;
let showSeparator = true;
if (items.length < 3) {
showSeparator = false;
}
if (isActive || isNextActive || isLast) {
showSeparator = false;
}
return showSeparator;
}
export default contextConnect(SegmentControl, 'SegmentControl');