-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
use-transition.ts
306 lines (266 loc) · 8.84 KB
/
use-transition.ts
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import { useRef, useState, type MutableRefObject } from 'react'
import { disposables } from '../utils/disposables'
import { useDisposables } from './use-disposables'
import { useFlags } from './use-flags'
import { useIsoMorphicEffect } from './use-iso-morphic-effect'
if (
typeof process !== 'undefined' &&
typeof globalThis !== 'undefined' &&
typeof Element !== 'undefined' &&
// Strange string concatenation is on purpose to prevent `esbuild` from
// replacing `process.env.NODE_ENV` with `production` in the build output,
// eliminating this whole branch.
process?.env?.['NODE' + '_' + 'ENV'] === 'test'
) {
if (typeof Element?.prototype?.getAnimations === 'undefined') {
Element.prototype.getAnimations = function getAnimationsPolyfill() {
console.warn(
[
'Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.',
'Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.',
'',
'Example usage:',
'```js',
"import { mockAnimationsApi } from 'jsdom-testing-mocks'",
'mockAnimationsApi()',
'```',
].join('\n')
)
return []
}
}
}
/**
* ```
* ┌──────┐ │ ┌──────────────┐
* │Closed│ │ │Closed │
* └──────┘ │ └──────────────┘
* ┌──────┐┌──────┐┌──────┐│┌──────┐┌──────┐┌──────┐
* │Frame ││Frame ││Frame │││Frame ││Frame ││Frame │
* └──────┘└──────┘└──────┘│└──────┘└──────┘└──────┘
* ┌──────────────────────┐│┌──────────────────────┐
* │Enter │││Leave │
* └──────────────────────┘│└──────────────────────┘
* ┌──────────────────────┐│┌──────────────────────┐
* │Transition │││Transition │
* ├──────────────────────┘│└──────────────────────┘
* │
* └─ Applied when `Enter` or `Leave` is applied.
* ```
*/
enum TransitionState {
None = 0,
Closed = 1 << 0,
Enter = 1 << 1,
Leave = 1 << 2,
}
type TransitionData = {
closed?: boolean
enter?: boolean
leave?: boolean
transition?: boolean
}
export function transitionDataAttributes(data: TransitionData) {
let attributes: Record<string, string> = {}
for (let key in data) {
if (data[key as keyof TransitionData] === true) {
attributes[`data-${key}`] = ''
}
}
return attributes
}
export function useTransition(
enabled: boolean,
element: HTMLElement | null,
show: boolean,
events?: {
start?(show: boolean): void
end?(show: boolean): void
}
): [visible: boolean, data: TransitionData] {
let [visible, setVisible] = useState(show)
let { hasFlag, addFlag, removeFlag } = useFlags(
enabled && visible ? TransitionState.Enter | TransitionState.Closed : TransitionState.None
)
let inFlight = useRef(false)
let cancelledRef = useRef(false)
let d = useDisposables()
useIsoMorphicEffect(() => {
if (!enabled) return
if (show) {
setVisible(true)
}
if (!element) {
if (show) {
addFlag(TransitionState.Enter | TransitionState.Closed)
}
return
}
events?.start?.(show)
return transition(element, {
inFlight,
prepare() {
if (cancelledRef.current) {
// Cancelled a cancellation, we're back to the original state.
cancelledRef.current = false
} else {
// If we were already in-flight, then we want to cancel the current
// transition.
cancelledRef.current = inFlight.current
}
inFlight.current = true
if (cancelledRef.current) return
if (show) {
addFlag(TransitionState.Enter | TransitionState.Closed)
removeFlag(TransitionState.Leave)
} else {
addFlag(TransitionState.Leave)
removeFlag(TransitionState.Enter)
}
},
run() {
if (cancelledRef.current) {
// If we cancelled a transition, then the `show` state is going to
// be inverted already, but that doesn't mean we have to go to that
// new state.
//
// What we actually want is to revert to the "idle" state (the
// stable state where an `Enter` transitions to, and a `Leave`
// transitions from.)
//
// Because of this, it might look like we are swapping the flags in
// the following branches, but that's not the case.
if (show) {
removeFlag(TransitionState.Enter | TransitionState.Closed)
addFlag(TransitionState.Leave)
} else {
removeFlag(TransitionState.Leave)
addFlag(TransitionState.Enter | TransitionState.Closed)
}
} else {
if (show) {
removeFlag(TransitionState.Closed)
} else {
addFlag(TransitionState.Closed)
}
}
},
done() {
if (cancelledRef.current) {
if (typeof element.getAnimations === 'function' && element.getAnimations().length > 0) {
return
}
}
inFlight.current = false
removeFlag(TransitionState.Enter | TransitionState.Leave | TransitionState.Closed)
if (!show) {
setVisible(false)
}
events?.end?.(show)
},
})
}, [enabled, show, element, d])
if (!enabled) {
return [
show,
{
closed: undefined,
enter: undefined,
leave: undefined,
transition: undefined,
},
] as const
}
return [
visible,
{
closed: hasFlag(TransitionState.Closed),
enter: hasFlag(TransitionState.Enter),
leave: hasFlag(TransitionState.Leave),
transition: hasFlag(TransitionState.Enter) || hasFlag(TransitionState.Leave),
},
] as const
}
function transition(
node: HTMLElement,
{
prepare,
run,
done,
inFlight,
}: {
prepare: () => void
run: () => void
done: () => void
inFlight: MutableRefObject<boolean>
}
) {
let d = disposables()
// Prepare the transitions by ensuring that all the "before" classes are
// applied and flushed to the DOM.
prepareTransition(node, {
prepare,
inFlight,
})
// This is a workaround for a bug in all major browsers.
//
// 1. When an element is just mounted
// 2. And you apply a transition to it (e.g.: via a class)
// 3. And you're using `getComputedStyle` and read any returned value
// 4. Then the `transition` immediately jumps to the end state
//
// This means that no transition happens at all. To fix this, we delay the
// actual transition by one frame.
d.nextFrame(() => {
// Initiate the transition by applying the new classes.
run()
// Wait for the transition, once the transition is complete we can cleanup.
// We wait for a frame such that the browser has time to flush the changes
// to the DOM.
d.requestAnimationFrame(() => {
d.add(waitForTransition(node, done))
})
})
return d.dispose
}
function waitForTransition(node: HTMLElement | null, done: () => void) {
let d = disposables()
if (!node) return d.dispose
let cancelled = false
d.add(() => {
cancelled = true
})
let transitions =
node.getAnimations?.().filter((animation) => animation instanceof CSSTransition) ?? []
// If there are no transitions, we can stop early.
if (transitions.length === 0) {
done()
return d.dispose
}
// Wait for all the transitions to complete.
Promise.allSettled(transitions.map((transition) => transition.finished)).then(() => {
if (!cancelled) {
done()
}
})
return d.dispose
}
function prepareTransition(
node: HTMLElement,
{ inFlight, prepare }: { inFlight?: MutableRefObject<boolean>; prepare: () => void }
) {
// If we are already transitioning, then we don't need to force cancel the
// current transition (by triggering a reflow).
if (inFlight?.current) {
prepare()
return
}
let previous = node.style.transition
// Force cancel current transition
node.style.transition = 'none'
prepare()
// Trigger a reflow, flushing the CSS changes
node.offsetHeight
// Reset the transition to what it was before
node.style.transition = previous
}