/
index.tsx
109 lines (99 loc) · 2.7 KB
/
index.tsx
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
107
108
109
import * as React from "react";
import styled, { css } from "styled-components";
import getSpacingToken from "../common/getSpacingToken";
import FormLabel from "../FormLabel";
import defaultTheme from "../defaultTheme";
import Stack from "../Stack";
import SwitchSegment, { StyledText, StyledLabel } from "./SwitchSegment";
import ErrorFormTooltip from "../ErrorFormTooltip";
import useErrorTooltip from "../ErrorFormTooltip/hooks/useErrorTooltip";
import type { Props } from "./types";
const StyledWrapper = styled.label<{
$maxWidth?: Props["maxWidth"];
spaceAfter?: Props["spaceAfter"];
}>`
${({ theme, $maxWidth }) => css`
display: flex;
width: 100%;
position: relative;
flex-direction: column;
max-width: ${$maxWidth};
margin-bottom: ${getSpacingToken};
gap: ${theme.orbit.spaceXXXSmall};
${StyledLabel} {
&:nth-child(odd) {
${StyledText} {
border-radius: 5px 0 0 5px;
}
}
&:nth-child(even) {
${StyledText} {
border-radius: 0 5px 5px 0;
}
}
}
`};
`;
StyledWrapper.defaultProps = {
theme: defaultTheme,
};
const SegmentedSwitch = ({
options,
dataTest,
onChange,
showTooltip,
spaceAfter,
onFocus,
maxWidth,
help,
error,
label,
}: Props) => {
const hasTooltip = Boolean(error || help);
const { tooltipShown, tooltipShownHover, setTooltipShown, setTooltipShownHover, labelRef } =
useErrorTooltip({ onFocus, hasTooltip });
React.useEffect(() => {
if (hasTooltip) {
if (showTooltip) setTooltipShown(true);
else setTooltipShown(false);
}
}, [showTooltip, hasTooltip, setTooltipShown]);
return (
<StyledWrapper spaceAfter={spaceAfter} data-test={dataTest} $maxWidth={maxWidth} ref={labelRef}>
{label && (
<FormLabel
help={!!help}
error={!!error}
onMouseEnter={() => setTooltipShownHover(true)}
onMouseLeave={() => setTooltipShownHover(false)}
>
{label}
</FormLabel>
)}
<Stack flex spacing="none">
{options.map(({ value, label: optionLabel, ...props }) => (
<SwitchSegment
key={value}
value={value}
label={optionLabel}
setTooltipShown={setTooltipShown}
onChange={onChange}
onFocus={onFocus}
{...props}
/>
))}
</Stack>
{hasTooltip && (
<ErrorFormTooltip
help={help}
error={error}
helpClosable={false}
shown={tooltipShown || tooltipShownHover}
onShown={prev => setTooltipShown(!prev)}
referenceElement={labelRef}
/>
)}
</StyledWrapper>
);
};
export default SegmentedSwitch;