-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
transition.tsx
434 lines (363 loc) · 11.6 KB
/
transition.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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import React, {
Fragment,
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
// Types
ElementType,
MutableRefObject,
} from 'react'
import { Props } from '../../types'
import { useId } from '../../hooks/use-id'
import { useIsInitialRender } from '../../hooks/use-is-initial-render'
import { match } from '../../utils/match'
import { useIsMounted } from '../../hooks/use-is-mounted'
import { useIsoMorphicEffect } from '../../hooks/use-iso-morphic-effect'
import { Features, PropsForFeatures, render, RenderStrategy } from '../../utils/render'
import { Reason, transition } from './utils/transition'
import { OpenClosedProvider, State, useOpenClosed } from '../../internal/open-closed'
import { useServerHandoffComplete } from '../../hooks/use-server-handoff-complete'
type ID = ReturnType<typeof useId>
function useSplitClasses(classes: string = '') {
return useMemo(
() => classes.split(' ').filter((className) => className.trim().length > 1),
[classes]
)
}
interface TransitionContextValues {
show: boolean
appear: boolean
initial: boolean
}
let TransitionContext = createContext<TransitionContextValues | null>(null)
TransitionContext.displayName = 'TransitionContext'
enum TreeStates {
Visible = 'visible',
Hidden = 'hidden',
}
export interface TransitionClasses {
enter?: string
enterFrom?: string
enterTo?: string
entered?: string
leave?: string
leaveFrom?: string
leaveTo?: string
}
export interface TransitionEvents {
beforeEnter?: () => void
afterEnter?: () => void
beforeLeave?: () => void
afterLeave?: () => void
}
type TransitionChildProps<TTag> = Props<TTag, TransitionChildRenderPropArg> &
PropsForFeatures<typeof TransitionChildRenderFeatures> &
TransitionClasses &
TransitionEvents & { appear?: boolean }
function useTransitionContext() {
let context = useContext(TransitionContext)
if (context === null) {
throw new Error(
'A <Transition.Child /> is used but it is missing a parent <Transition /> or <Transition.Root />.'
)
}
return context
}
function useParentNesting() {
let context = useContext(NestingContext)
if (context === null) {
throw new Error(
'A <Transition.Child /> is used but it is missing a parent <Transition /> or <Transition.Root />.'
)
}
return context
}
interface NestingContextValues {
children: MutableRefObject<{ id: ID; state: TreeStates }[]>
register: (id: ID) => () => void
unregister: (id: ID, strategy?: RenderStrategy) => void
}
let NestingContext = createContext<NestingContextValues | null>(null)
NestingContext.displayName = 'NestingContext'
function hasChildren(
bag: NestingContextValues['children'] | { children: NestingContextValues['children'] }
): boolean {
if ('children' in bag) return hasChildren(bag.children)
return bag.current.filter(({ state }) => state === TreeStates.Visible).length > 0
}
function useNesting(done?: () => void) {
let doneRef = useRef(done)
let transitionableChildren = useRef<NestingContextValues['children']['current']>([])
let mounted = useIsMounted()
useEffect(() => {
doneRef.current = done
}, [done])
let unregister = useCallback(
(childId: ID, strategy = RenderStrategy.Hidden) => {
let idx = transitionableChildren.current.findIndex(({ id }) => id === childId)
if (idx === -1) return
match(strategy, {
[RenderStrategy.Unmount]() {
transitionableChildren.current.splice(idx, 1)
},
[RenderStrategy.Hidden]() {
transitionableChildren.current[idx].state = TreeStates.Hidden
},
})
if (!hasChildren(transitionableChildren) && mounted.current) {
doneRef.current?.()
}
},
[doneRef, mounted, transitionableChildren]
)
let register = useCallback(
(childId: ID) => {
let child = transitionableChildren.current.find(({ id }) => id === childId)
if (!child) {
transitionableChildren.current.push({ id: childId, state: TreeStates.Visible })
} else if (child.state !== TreeStates.Visible) {
child.state = TreeStates.Visible
}
return () => unregister(childId, RenderStrategy.Unmount)
},
[transitionableChildren, unregister]
)
return useMemo(
() => ({
children: transitionableChildren,
register,
unregister,
}),
[register, unregister, transitionableChildren]
)
}
function noop() {}
let eventNames = ['beforeEnter', 'afterEnter', 'beforeLeave', 'afterLeave'] as const
function ensureEventHooksExist(events: TransitionEvents) {
let result = {} as Record<keyof typeof events, () => void>
for (let name of eventNames) {
result[name] = events[name] ?? noop
}
return result
}
function useEvents(events: TransitionEvents) {
let eventsRef = useRef(ensureEventHooksExist(events))
useEffect(() => {
eventsRef.current = ensureEventHooksExist(events)
}, [events])
return eventsRef
}
// ---
let DEFAULT_TRANSITION_CHILD_TAG = 'div' as const
type TransitionChildRenderPropArg = MutableRefObject<HTMLDivElement>
let TransitionChildRenderFeatures = Features.RenderStrategy
function TransitionChild<TTag extends ElementType = typeof DEFAULT_TRANSITION_CHILD_TAG>(
props: TransitionChildProps<TTag>
) {
let {
// Event "handlers"
beforeEnter,
afterEnter,
beforeLeave,
afterLeave,
// Class names
enter,
enterFrom,
enterTo,
entered,
leave,
leaveFrom,
leaveTo,
// @ts-expect-error
...rest
} = props as typeof props
let container = useRef<HTMLElement | null>(null)
let [state, setState] = useState(TreeStates.Visible)
let strategy = rest.unmount ? RenderStrategy.Unmount : RenderStrategy.Hidden
let { show, appear, initial } = useTransitionContext()
let { register, unregister } = useParentNesting()
let id = useId()
let isTransitioning = useRef(false)
let nesting = useNesting(() => {
// When all children have been unmounted we can only hide ourselves if and only if we are not
// transitioning ourselves. Otherwise we would unmount before the transitions are finished.
if (!isTransitioning.current) {
setState(TreeStates.Hidden)
unregister(id)
events.current.afterLeave()
}
})
useIsoMorphicEffect(() => {
if (!id) return
return register(id)
}, [register, id])
useIsoMorphicEffect(() => {
// If we are in another mode than the Hidden mode then ignore
if (strategy !== RenderStrategy.Hidden) return
if (!id) return
// Make sure that we are visible
if (show && state !== TreeStates.Visible) {
setState(TreeStates.Visible)
return
}
match(state, {
[TreeStates.Hidden]: () => unregister(id),
[TreeStates.Visible]: () => register(id),
})
}, [state, id, register, unregister, show, strategy])
let enterClasses = useSplitClasses(enter)
let enterFromClasses = useSplitClasses(enterFrom)
let enterToClasses = useSplitClasses(enterTo)
let enteredClasses = useSplitClasses(entered)
let leaveClasses = useSplitClasses(leave)
let leaveFromClasses = useSplitClasses(leaveFrom)
let leaveToClasses = useSplitClasses(leaveTo)
let events = useEvents({ beforeEnter, afterEnter, beforeLeave, afterLeave })
let ready = useServerHandoffComplete()
useEffect(() => {
if (ready && state === TreeStates.Visible && container.current === null) {
throw new Error('Did you forget to passthrough the `ref` to the actual DOM node?')
}
}, [container, state, ready])
// Skipping initial transition
let skip = initial && !appear
useIsoMorphicEffect(() => {
let node = container.current
if (!node) return
if (skip) return
isTransitioning.current = true
if (show) events.current.beforeEnter()
if (!show) events.current.beforeLeave()
return show
? transition(
node,
enterClasses,
enterFromClasses,
enterToClasses,
enteredClasses,
(reason) => {
isTransitioning.current = false
if (reason === Reason.Finished) events.current.afterEnter()
}
)
: transition(
node,
leaveClasses,
leaveFromClasses,
leaveToClasses,
enteredClasses,
(reason) => {
isTransitioning.current = false
if (reason !== Reason.Finished) return
// When we don't have children anymore we can safely unregister from the parent and hide
// ourselves.
if (!hasChildren(nesting)) {
setState(TreeStates.Hidden)
unregister(id)
events.current.afterLeave()
}
}
)
}, [
events,
id,
isTransitioning,
unregister,
nesting,
container,
skip,
show,
enterClasses,
enterFromClasses,
enterToClasses,
leaveClasses,
leaveFromClasses,
leaveToClasses,
])
let propsWeControl = { ref: container }
let passthroughProps = rest
return (
<NestingContext.Provider value={nesting}>
<OpenClosedProvider
value={match(state, {
[TreeStates.Visible]: State.Open,
[TreeStates.Hidden]: State.Closed,
})}
>
{render({
props: { ...passthroughProps, ...propsWeControl },
defaultTag: DEFAULT_TRANSITION_CHILD_TAG,
features: TransitionChildRenderFeatures,
visible: state === TreeStates.Visible,
name: 'Transition.Child',
})}
</OpenClosedProvider>
</NestingContext.Provider>
)
}
export function Transition<TTag extends ElementType = typeof DEFAULT_TRANSITION_CHILD_TAG>(
props: TransitionChildProps<TTag> & { show?: boolean; appear?: boolean }
) {
// @ts-expect-error
let { show, appear = false, unmount, ...passthroughProps } = props as typeof props
let usesOpenClosedState = useOpenClosed()
if (show === undefined && usesOpenClosedState !== null) {
show = match(usesOpenClosedState, {
[State.Open]: true,
[State.Closed]: false,
})
}
if (![true, false].includes(show as unknown as boolean)) {
throw new Error('A <Transition /> is used but it is missing a `show={true | false}` prop.')
}
let [state, setState] = useState(show ? TreeStates.Visible : TreeStates.Hidden)
let nestingBag = useNesting(() => {
setState(TreeStates.Hidden)
})
let initial = useIsInitialRender()
let transitionBag = useMemo<TransitionContextValues>(
() => ({ show: show as boolean, appear: appear || !initial, initial }),
[show, appear, initial]
)
useEffect(() => {
if (show) {
setState(TreeStates.Visible)
} else if (!hasChildren(nestingBag)) {
setState(TreeStates.Hidden)
}
}, [show, nestingBag])
let sharedProps = { unmount }
return (
<NestingContext.Provider value={nestingBag}>
<TransitionContext.Provider value={transitionBag}>
{render({
props: {
...sharedProps,
as: Fragment,
children: <TransitionChild {...sharedProps} {...passthroughProps} />,
},
defaultTag: Fragment,
features: TransitionChildRenderFeatures,
visible: state === TreeStates.Visible,
name: 'Transition',
})}
</TransitionContext.Provider>
</NestingContext.Provider>
)
}
Transition.Child = function Child<TTag extends ElementType = typeof DEFAULT_TRANSITION_CHILD_TAG>(
props: TransitionChildProps<TTag>
) {
let hasTransitionContext = useContext(TransitionContext) !== null
let hasOpenClosedContext = useOpenClosed() !== null
return !hasTransitionContext && hasOpenClosedContext ? (
<Transition {...props} />
) : (
<TransitionChild {...props} />
)
}
Transition.Root = Transition