forked from roginfarrer/collapsed
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
200 lines (188 loc) · 5.4 KB
/
index.ts
File metadata and controls
200 lines (188 loc) · 5.4 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import { useState, useRef, TransitionEvent, CSSProperties } from 'react'
import { flushSync } from 'react-dom'
import raf from 'raf'
import {
noop,
callAll,
getElementHeight,
getAutoHeightDuration,
mergeRefs,
usePaddingWarning,
useEffectAfterMount,
useControlledState,
useId,
} from './utils'
import {
UseCollapseInput,
UseCollapseOutput,
GetCollapsePropsOutput,
GetCollapsePropsInput,
GetTogglePropsOutput,
GetTogglePropsInput,
} from './types'
const easeInOut = 'cubic-bezier(0.4, 0, 0.2, 1)'
export default function useCollapse({
duration,
easing = easeInOut,
collapseStyles = {},
expandStyles = {},
onExpandStart = noop,
onExpandEnd = noop,
onCollapseStart = noop,
onCollapseEnd = noop,
isExpanded: configIsExpanded,
defaultExpanded = false,
hasDisabledAnimation = false,
...initialConfig
}: UseCollapseInput = {}): UseCollapseOutput {
const [isExpanded, setExpanded] = useControlledState(
configIsExpanded,
defaultExpanded
)
const uniqueId = useId()
const el = useRef<HTMLElement | null>(null)
usePaddingWarning(el)
const collapsedHeight = `${initialConfig.collapsedHeight || 0}px`
const collapsedStyles = {
display: collapsedHeight === '0px' ? 'none' : 'block',
height: collapsedHeight,
overflow: 'hidden',
}
const [styles, setStylesRaw] = useState<CSSProperties>(
isExpanded ? {} : collapsedStyles
)
const setStyles = (newStyles: {} | ((oldStyles: {}) => {})): void => {
// We rely on reading information from layout
// at arbitrary times, so ensure all style changes
// happen before we might attempt to read them.
flushSync(() => {
setStylesRaw(newStyles)
})
}
const mergeStyles = (newStyles: {}): void => {
setStyles((oldStyles) => ({ ...oldStyles, ...newStyles }))
}
function getTransitionStyles(height: number | string): CSSProperties {
if (hasDisabledAnimation) {
return {}
}
const _duration = duration || getAutoHeightDuration(height)
return {
transition: `height ${_duration}ms ${easing}`,
}
}
useEffectAfterMount(() => {
if (isExpanded) {
raf(() => {
onExpandStart()
mergeStyles({
...expandStyles,
willChange: 'height',
display: 'block',
overflow: 'hidden',
})
raf(() => {
const height = getElementHeight(el)
mergeStyles({
...getTransitionStyles(height),
height,
})
})
})
} else {
raf(() => {
onCollapseStart()
const height = getElementHeight(el)
mergeStyles({
...collapseStyles,
...getTransitionStyles(height),
willChange: 'height',
height,
})
raf(() => {
mergeStyles({
height: collapsedHeight,
overflow: 'hidden',
})
})
})
}
}, [isExpanded, collapsedHeight])
const handleTransitionEnd = (e: TransitionEvent): void => {
// Sometimes onTransitionEnd is triggered by another transition,
// such as a nested collapse panel transitioning. But we only
// want to handle this if this component's element is transitioning
if (e.target !== el.current || e.propertyName !== 'height') {
return
}
// The height comparisons below are a final check before
// completing the transition
// Sometimes this callback is run even though we've already begun
// transitioning the other direction
// The conditions give us the opportunity to bail out,
// which will prevent the collapsed content from flashing on the screen
if (isExpanded) {
const height = getElementHeight(el)
// If the height at the end of the transition
// matches the height we're animating to,
if (height === styles.height) {
setStyles({})
} else {
// If the heights don't match, this could be due the height
// of the content changing mid-transition
mergeStyles({ height })
}
onExpandEnd()
// If the height we should be animating to matches the collapsed height,
// it's safe to apply the collapsed overrides
} else if (styles.height === collapsedHeight) {
setStyles(collapsedStyles)
onCollapseEnd()
}
}
function getToggleProps({
disabled = false,
onClick = noop,
...rest
}: GetTogglePropsInput = {}): GetTogglePropsOutput {
return {
type: 'button',
role: 'button',
id: `react-collapsed-toggle-${uniqueId}`,
'aria-controls': `react-collapsed-panel-${uniqueId}`,
'aria-expanded': isExpanded,
tabIndex: 0,
disabled,
...rest,
onClick: disabled ? noop : callAll(onClick, () => setExpanded((n) => !n)),
}
}
function getCollapseProps({
style = {},
onTransitionEnd = noop,
refKey = 'ref',
...rest
}: GetCollapsePropsInput = {}): GetCollapsePropsOutput {
const theirRef: any = rest[refKey]
return {
id: `react-collapsed-panel-${uniqueId}`,
'aria-hidden': !isExpanded,
...rest,
[refKey]: mergeRefs(el, theirRef),
onTransitionEnd: callAll(handleTransitionEnd, onTransitionEnd),
style: {
boxSizing: 'border-box',
// additional styles passed, e.g. getCollapseProps({style: {}})
...style,
// style overrides from state
...styles,
},
}
}
return {
getToggleProps,
getCollapseProps,
isExpanded,
setExpanded,
}
}