/
ValueContainer.tsx
103 lines (88 loc) · 2.82 KB
/
ValueContainer.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
import * as React from 'react';
import { useEffect, useState, ReactElement, ReactNode } from 'react';
import { TransitionGroup } from 'react-transition-group';
import { ValueContainerProps } from '../components/containers';
import { GroupBase } from '../types';
export type ValueContainerComponent = <
Option,
IsMulti extends boolean,
Group extends GroupBase<Option>
>(
props: ValueContainerProps<Option, IsMulti, Group>
) => ReactElement;
interface IsMultiValueContainerProps extends ValueContainerProps {
component: ValueContainerComponent;
}
// make ValueContainer a transition group
const AnimatedValueContainer =
(WrappedComponent: ValueContainerComponent) =>
<Option, IsMulti extends boolean, Group extends GroupBase<Option>>(
props: ValueContainerProps<Option, IsMulti, Group>
) =>
props.isMulti ? (
<IsMultiValueContainer component={WrappedComponent} {...(props as any)} />
) : (
<TransitionGroup component={WrappedComponent} {...(props as any)} />
);
const IsMultiValueContainer = ({
component,
...restProps
}: IsMultiValueContainerProps) => {
const multiProps = useIsMultiValueContainer(restProps);
return <TransitionGroup component={component} {...(multiProps as any)} />;
};
const useIsMultiValueContainer = ({
children,
...props
}: ValueContainerProps) => {
const {
isMulti,
hasValue,
innerProps,
selectProps: { components, controlShouldRenderValue },
} = props;
const [cssDisplayFlex, setCssDisplayFlex] = useState(
isMulti && controlShouldRenderValue && hasValue
);
const [removingValue, setRemovingValue] = useState(false);
useEffect(() => {
if (hasValue && !cssDisplayFlex) {
setCssDisplayFlex(true);
}
}, [hasValue, cssDisplayFlex]);
useEffect(() => {
if (removingValue && !hasValue && cssDisplayFlex) {
setCssDisplayFlex(false);
}
setRemovingValue(false);
}, [removingValue, hasValue, cssDisplayFlex]);
const onExited = () => setRemovingValue(true);
const childMapper = (child: ReactNode) => {
if (isMulti && React.isValidElement(child)) {
// Add onExited callback to MultiValues
if (child.type === components.MultiValue) {
return React.cloneElement(child, { onExited });
}
// While container flexed, Input cursor is shown after Placeholder text,
// so remove Placeholder until display is set back to grid
if (child.type === components.Placeholder && cssDisplayFlex) {
return null;
}
}
return child;
};
const newInnerProps = {
...innerProps,
style: {
...innerProps?.style,
display: cssDisplayFlex ? 'flex' : 'grid',
},
};
const newProps = {
...props,
innerProps: newInnerProps,
children: React.Children.toArray(children).map(childMapper),
};
return newProps;
};
export default AnimatedValueContainer;