-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
utils.tsx
259 lines (220 loc) · 9.75 KB
/
utils.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
/*
* Copyright 2022 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {AriaLabelingProps, DOMProps as SharedDOMProps} from '@react-types/shared';
import {mergeProps, mergeRefs, useLayoutEffect, useObjectRef} from '@react-aria/utils';
import React, {createContext, CSSProperties, ReactNode, RefCallback, RefObject, useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react';
import ReactDOM from 'react-dom';
// Override forwardRef types so generics work.
declare function forwardRef<T, P = {}>(
render: (props: P, ref: React.Ref<T>) => React.ReactElement | null
): (props: P & React.RefAttributes<T>) => React.ReactElement | null;
export type forwardRefType = typeof forwardRef;
export const slotCallbackSymbol = Symbol('callback');
export const defaultSlot = Symbol('default');
interface SlottedValue<T> {
slots?: Record<string | symbol, T>,
[slotCallbackSymbol]?: (value: T) => void
}
export type ContextValue<T extends SlotProps, E extends Element> = SlottedValue<WithRef<T, E>> | WithRef<T, E> | null | undefined;
type ProviderValue<T> = [React.Context<T>, T];
type ProviderValues<A, B, C, D, E, F, G, H> =
| [ProviderValue<A>]
| [ProviderValue<A>, ProviderValue<B>]
| [ProviderValue<A>, ProviderValue<B>, ProviderValue<C>]
| [ProviderValue<A>, ProviderValue<B>, ProviderValue<C>, ProviderValue<D>]
| [ProviderValue<A>, ProviderValue<B>, ProviderValue<C>, ProviderValue<D>, ProviderValue<E>]
| [ProviderValue<A>, ProviderValue<B>, ProviderValue<C>, ProviderValue<D>, ProviderValue<E>, ProviderValue<F>]
| [ProviderValue<A>, ProviderValue<B>, ProviderValue<C>, ProviderValue<D>, ProviderValue<E>, ProviderValue<F>, ProviderValue<G>]
| [ProviderValue<A>, ProviderValue<B>, ProviderValue<C>, ProviderValue<D>, ProviderValue<E>, ProviderValue<F>, ProviderValue<G>, ProviderValue<H>];
interface ProviderProps<A, B, C, D, E, F, G, H> {
values: ProviderValues<A, B, C, D, E, F, G, H>,
children: React.ReactNode
}
export function Provider<A, B, C, D, E, F, G, H>({values, children}: ProviderProps<A, B, C, D, E, F, G, H>): JSX.Element {
for (let [Context, value] of values) {
// @ts-ignore
children = <Context.Provider value={value}>{children}</Context.Provider>;
}
return children as JSX.Element;
}
export interface StyleProps {
/** The CSS [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) for the element. */
className?: string,
/** The inline [style](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) for the element. */
style?: CSSProperties
}
export interface DOMProps extends StyleProps {
/** The children of the component. */
children?: ReactNode
}
export interface StyleRenderProps<T> {
/** The CSS [className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className) for the element. A function may be provided to compute the class based on component state. */
className?: string | ((values: T) => string),
/** The inline [style](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) for the element. A function may be provided to compute the style based on component state. */
style?: CSSProperties | ((values: T) => CSSProperties)
}
export interface RenderProps<T> extends StyleRenderProps<T> {
/** The children of the component. A function may be provided to alter the children based on component state. */
children?: ReactNode | ((values: T) => ReactNode)
}
interface RenderPropsHookOptions<T> extends RenderProps<T>, SharedDOMProps, AriaLabelingProps {
values: T,
defaultChildren?: ReactNode,
defaultClassName?: string
}
export function useRenderProps<T>(props: RenderPropsHookOptions<T>) {
let {
className,
style,
children,
defaultClassName,
defaultChildren,
values
} = props;
return useMemo(() => {
let computedClassName: string | undefined;
let computedStyle: React.CSSProperties | undefined;
let computedChildren: React.ReactNode | undefined;
if (typeof className === 'function') {
computedClassName = className(values);
} else {
computedClassName = className;
}
if (typeof style === 'function') {
computedStyle = style(values);
} else {
computedStyle = style;
}
if (typeof children === 'function') {
computedChildren = children(values);
} else if (children == null) {
computedChildren = defaultChildren;
} else {
computedChildren = children;
}
return {
className: computedClassName ?? defaultClassName,
style: computedStyle,
children: computedChildren
};
}, [className, style, children, defaultClassName, defaultChildren, values]);
}
export type WithRef<T, E> = T & {ref?: React.ForwardedRef<E>};
export interface SlotProps {
/** A slot name for the component. Slots allow the component to receive props from a parent component. */
slot?: string
}
export function useContextProps<T, U extends SlotProps, E extends Element>(props: T & SlotProps, ref: React.ForwardedRef<E>, context: React.Context<ContextValue<U, E>>): [T, React.RefObject<E>] {
let ctx = useContext(context) || {};
if ('slots' in ctx && ctx.slots) {
if (!props.slot && !ctx.slots[defaultSlot]) {
throw new Error('A slot prop is required');
}
let slot = props.slot || defaultSlot;
if (!ctx.slots[slot]) {
// @ts-ignore
throw new Error(`Invalid slot "${props.slot}". Valid slot names are ` + new Intl.ListFormat().format(Object.keys(ctx.slots).map(p => `"${p}"`)) + '.');
}
ctx = ctx.slots[slot];
}
// @ts-ignore - TS says "Type 'unique symbol' cannot be used as an index type." but not sure why.
let {ref: contextRef, [slotCallbackSymbol]: callback, ...contextProps} = ctx;
let mergedRef = useObjectRef(useMemo(() => mergeRefs(ref, contextRef), [ref, contextRef]));
let mergedProps = mergeProps(contextProps, props) as unknown as T;
// A parent component might need the props from a child, so call slot callback if needed.
useEffect(() => {
if (callback) {
callback(props);
}
}, [callback, props]);
return [mergedProps, mergedRef];
}
export function useSlot(): [RefCallback<Element>, boolean] {
// Assume we do have the slot in the initial render.
let [hasSlot, setHasSlot] = useState(true);
let hasRun = useRef(false);
// A callback ref which will run when the slotted element mounts.
// This should happen before the useLayoutEffect below.
let ref = useCallback(el => {
hasRun.current = true;
setHasSlot(!!el);
}, []);
// If the callback hasn't been called, then reset to false.
useLayoutEffect(() => {
if (!hasRun.current) {
setHasSlot(false);
}
}, []);
return [ref, hasSlot];
}
export function useEnterAnimation(ref: RefObject<HTMLElement>, isReady: boolean = true) {
let [isEntering, setEntering] = useState(true);
useAnimation(ref, isEntering && isReady, useCallback(() => setEntering(false), []));
return isEntering && isReady;
}
export function useExitAnimation(ref: RefObject<HTMLElement>, isOpen: boolean) {
// State to trigger a re-render after animation is complete, which causes the element to be removed from the DOM.
// Ref to track the state we're in, so we don't immediately reset isExiting to true after the animation.
let [isExiting, setExiting] = useState(false);
let [exitState, setExitState] = useState('idle');
// If isOpen becomes false, set isExiting to true.
if (!isOpen && ref.current && exitState === 'idle') {
isExiting = true;
setExiting(true);
setExitState('exiting');
}
// If we exited, and the element has been removed, reset exit state to idle.
if (!ref.current && exitState === 'exited') {
setExitState('idle');
}
useAnimation(
ref,
isExiting,
useCallback(() => {
setExitState('exited');
setExiting(false);
}, [])
);
return isExiting;
}
function useAnimation(ref: RefObject<HTMLElement>, isActive: boolean, onEnd: () => void) {
let prevAnimation = useRef<string | null>(null);
if (isActive && ref.current) {
// This is ok because we only read it in the layout effect below, immediately after the commit phase.
// We could move this to another effect that runs every render, but this would be unnecessarily slow.
// We only need the computed style right before the animation becomes active.
// eslint-disable-next-line rulesdir/pure-render
prevAnimation.current = window.getComputedStyle(ref.current).animation;
}
useLayoutEffect(() => {
if (isActive && ref.current) {
// Make sure there's actually an animation, and it wasn't there before we triggered the update.
let computedStyle = window.getComputedStyle(ref.current);
if (computedStyle.animationName !== 'none' && computedStyle.animation !== prevAnimation.current) {
let onAnimationEnd = (e: AnimationEvent) => {
if (e.target === ref.current) {
element.removeEventListener('animationend', onAnimationEnd);
ReactDOM.flushSync(() => {onEnd();});
}
};
let element = ref.current;
element.addEventListener('animationend', onAnimationEnd);
return () => {
element.removeEventListener('animationend', onAnimationEnd);
};
} else {
onEnd();
}
}
}, [ref, isActive, onEnd]);
}
export const HiddenContext = createContext<boolean>(false);