/
collapse.tsx
122 lines (116 loc) · 3.47 KB
/
collapse.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
110
111
112
113
114
115
116
117
118
119
120
121
122
import React, { useRef } from "react";
import { ViewStyle } from "react-native";
import Box, { BoxProps } from "../box/box";
import { AnimatePresence, MotiView } from "moti";
import { MotiWithPearlStyleProps } from "../../../theme/src/types";
import {
BoxStyleProps,
boxStyleFunctions,
} from "../../../theme/src/style-functions";
import { useStyleProps } from "../../../hooks";
export type CollapseProps = BoxProps & {
/** Whether to show the component */
show: boolean;
/**
* If `true`, the opacity of the content will be animated
* @default true
*/
animateOpacity?: boolean;
/**
* The height you want the content in its collapsed state.
* @default 0
*/
startingHeight?: number | string;
/**
* The height you want the content in its expanded state.
* @default "auto"
*/
endingHeight?: number | string;
};
/**
* Collapse is a component that provides an expandable view.
*/
const Collapse = React.memo(
React.forwardRef(
(
{
children,
show,
animateOpacity = true,
startingHeight = 0,
transition = {},
exitTransition = {},
endingHeight = "auto",
...rest
}: CollapseProps,
ref: any
) => {
const actualHeightRef = useRef<number | string>(endingHeight);
const computedStyles = useStyleProps(rest, boxStyleFunctions);
return (
<AnimatePresence>
{show && (
<React.Fragment>
<MotiView
ref={ref}
{...computedStyles}
from={{
...(animateOpacity && { opacity: 0 }),
height: startingHeight,
}}
animate={{
...(animateOpacity && { opacity: 1 }),
height: actualHeightRef.current,
}}
transition={
{
dampingRatio: 1,
duration: 150,
...transition,
type: "spring",
} as MotiWithPearlStyleProps<
ViewStyle,
BoxStyleProps
>["transition"]
}
exit={{
...(animateOpacity && { opacity: 0 }),
height: startingHeight as any,
}}
exitTransition={
{
dampingRatio: 1,
duration: 150,
...exitTransition,
type: "spring",
} as MotiWithPearlStyleProps<
ViewStyle,
BoxStyleProps
>["exitTransition"]
}
>
<Box
onLayout={({ nativeEvent }) => {
const currentHeight =
nativeEvent.layout.height +
(computedStyles.style.paddingTop || 0) +
(computedStyles.style.paddingBottom || 0);
if (
typeof actualHeightRef.current === "string" ||
currentHeight > actualHeightRef.current
)
actualHeightRef.current = Math.ceil(currentHeight);
}}
>
{children}
</Box>
</MotiView>
</React.Fragment>
)}
</AnimatePresence>
);
}
)
);
Collapse.displayName = "Collapse";
export default Collapse;