-
Notifications
You must be signed in to change notification settings - Fork 24.2k
/
ScrollViewStickyHeader.js
311 lines (284 loc) · 10.8 KB
/
ScrollViewStickyHeader.js
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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import type {LayoutEvent} from '../../Types/CoreEventTypes';
import Animated from '../../Animated/Animated';
import {isPublicInstance as isFabricPublicInstance} from '../../ReactNative/ReactFabricPublicInstance/ReactFabricPublicInstanceUtils';
import StyleSheet from '../../StyleSheet/StyleSheet';
import Platform from '../../Utilities/Platform';
import useMergeRefs from '../../Utilities/useMergeRefs';
import * as React from 'react';
import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
export type Props = $ReadOnly<{
children?: ExactReactElement_DEPRECATED<$FlowFixMe>,
nextHeaderLayoutY: ?number,
onLayout: (event: LayoutEvent) => void,
scrollAnimatedValue: Animated.Value,
// Will cause sticky headers to stick at the bottom of the ScrollView instead
// of the top.
inverted: ?boolean,
// The height of the parent ScrollView. Currently only set when inverted.
scrollViewHeight: ?number,
nativeID?: ?string,
hiddenOnScroll?: ?boolean,
}>;
type Instance = {
...React.ElementRef<typeof Animated.View>,
setNextHeaderY: number => void,
...
};
const ScrollViewStickyHeaderWithForwardedRef: React.AbstractComponent<
Props,
Instance,
> = React.forwardRef(function ScrollViewStickyHeader(props, forwardedRef) {
const {
inverted,
scrollViewHeight,
hiddenOnScroll,
scrollAnimatedValue,
nextHeaderLayoutY: _nextHeaderLayoutY,
} = props;
const [measured, setMeasured] = useState<boolean>(false);
const [layoutY, setLayoutY] = useState<number>(0);
const [layoutHeight, setLayoutHeight] = useState<number>(0);
const [translateY, setTranslateY] = useState<?number>(null);
const [nextHeaderLayoutY, setNextHeaderLayoutY] =
useState<?number>(_nextHeaderLayoutY);
const [isFabric, setIsFabric] = useState<boolean>(false);
const callbackRef = useCallback((ref: Instance | null): void => {
if (ref == null) {
return;
}
ref.setNextHeaderY = setNextHeaderLayoutY;
setIsFabric(isFabricPublicInstance(ref));
}, []);
const ref: (React.ElementRef<typeof Animated.View> | null) => void =
// $FlowFixMe[incompatible-type] - Ref is mutated by `callbackRef`.
useMergeRefs<Instance>(callbackRef, forwardedRef);
const offset = useMemo(
() =>
hiddenOnScroll === true
? Animated.diffClamp(
scrollAnimatedValue
.interpolate({
extrapolateLeft: 'clamp',
inputRange: [layoutY, layoutY + 1],
outputRange: ([0, 1]: Array<number>),
})
.interpolate({
inputRange: [0, 1],
outputRange: ([0, -1]: Array<number>),
}),
-layoutHeight,
0,
)
: null,
[scrollAnimatedValue, layoutHeight, layoutY, hiddenOnScroll],
);
const [animatedTranslateY, setAnimatedTranslateY] = useState<Animated.Node>(
() => {
const inputRange: Array<number> = [-1, 0];
const outputRange: Array<number> = [0, 0];
const initialTranslateY = scrollAnimatedValue.interpolate({
inputRange,
outputRange,
});
if (offset != null) {
return Animated.add(initialTranslateY, offset);
}
return initialTranslateY;
},
);
const haveReceivedInitialZeroTranslateY = useRef<boolean>(true);
const translateYDebounceTimer = useRef<?TimeoutID>(null);
useEffect(() => {
if (translateY !== 0 && translateY != null) {
haveReceivedInitialZeroTranslateY.current = false;
}
}, [translateY]);
// This is called whenever the (Interpolated) Animated Value
// updates, which is several times per frame during scrolling.
// To ensure that the Fabric ShadowTree has the most recent
// translate style of this node, we debounce the value and then
// pass it through to the underlying node during render.
// This is:
// 1. Only an issue in Fabric.
// 2. Worse in Android than iOS. In Android, but not iOS, you
// can touch and move your finger slightly and still trigger
// a "tap" event. In iOS, moving will cancel the tap in
// both Fabric and non-Fabric. On Android when you move
// your finger, the hit-detection moves from the Android
// platform to JS, so we need the ShadowTree to have knowledge
// of the current position.
const animatedValueListener = useCallback(({value}: $FlowFixMe) => {
const debounceTimeout: number = Platform.OS === 'android' ? 15 : 64;
// When the AnimatedInterpolation is recreated, it always initializes
// to a value of zero and emits a value change of 0 to its listeners.
if (value === 0 && !haveReceivedInitialZeroTranslateY.current) {
haveReceivedInitialZeroTranslateY.current = true;
return;
}
if (translateYDebounceTimer.current != null) {
clearTimeout(translateYDebounceTimer.current);
}
translateYDebounceTimer.current = setTimeout(
() => setTranslateY(value),
debounceTimeout,
);
}, []);
useEffect(() => {
const inputRange: Array<number> = [-1, 0];
const outputRange: Array<number> = [0, 0];
if (measured) {
if (inverted === true) {
// The interpolation looks like:
// - Negative scroll: no translation
// - `stickStartPoint` is the point at which the header will start sticking.
// It is calculated using the ScrollView viewport height so it is a the bottom.
// - Headers that are in the initial viewport will never stick, `stickStartPoint`
// will be negative.
// - From 0 to `stickStartPoint` no translation. This will cause the header
// to scroll normally until it reaches the top of the scroll view.
// - From `stickStartPoint` to when the next header y hits the bottom edge of the header: translate
// equally to scroll. This will cause the header to stay at the top of the scroll view.
// - Past the collision with the next header y: no more translation. This will cause the
// header to continue scrolling up and make room for the next sticky header.
// In the case that there is no next header just translate equally to
// scroll indefinitely.
if (scrollViewHeight != null) {
const stickStartPoint = layoutY + layoutHeight - scrollViewHeight;
if (stickStartPoint > 0) {
inputRange.push(stickStartPoint);
outputRange.push(0);
inputRange.push(stickStartPoint + 1);
outputRange.push(1);
// If the next sticky header has not loaded yet (probably windowing) or is the last
// we can just keep it sticked forever.
const collisionPoint =
(nextHeaderLayoutY || 0) - layoutHeight - scrollViewHeight;
if (collisionPoint > stickStartPoint) {
inputRange.push(collisionPoint, collisionPoint + 1);
outputRange.push(
collisionPoint - stickStartPoint,
collisionPoint - stickStartPoint,
);
}
}
}
} else {
// The interpolation looks like:
// - Negative scroll: no translation
// - From 0 to the y of the header: no translation. This will cause the header
// to scroll normally until it reaches the top of the scroll view.
// - From header y to when the next header y hits the bottom edge of the header: translate
// equally to scroll. This will cause the header to stay at the top of the scroll view.
// - Past the collision with the next header y: no more translation. This will cause the
// header to continue scrolling up and make room for the next sticky header.
// In the case that there is no next header just translate equally to
// scroll indefinitely.
inputRange.push(layoutY);
outputRange.push(0);
// If the next sticky header has not loaded yet (probably windowing) or is the last
// we can just keep it sticked forever.
const collisionPoint = (nextHeaderLayoutY || 0) - layoutHeight;
if (collisionPoint >= layoutY) {
inputRange.push(collisionPoint, collisionPoint + 1);
outputRange.push(collisionPoint - layoutY, collisionPoint - layoutY);
} else {
inputRange.push(layoutY + 1);
outputRange.push(1);
}
}
}
let newAnimatedTranslateY: Animated.Node = scrollAnimatedValue.interpolate({
inputRange,
outputRange,
});
if (offset != null) {
newAnimatedTranslateY = Animated.add(newAnimatedTranslateY, offset);
}
// add the event listener
let animatedListenerId;
if (isFabric) {
animatedListenerId = newAnimatedTranslateY.addListener(
animatedValueListener,
);
}
setAnimatedTranslateY(newAnimatedTranslateY);
// clean up the event listener and timer
return () => {
if (animatedListenerId) {
newAnimatedTranslateY.removeListener(animatedListenerId);
}
if (translateYDebounceTimer.current != null) {
clearTimeout(translateYDebounceTimer.current);
}
};
}, [
nextHeaderLayoutY,
measured,
layoutHeight,
layoutY,
scrollViewHeight,
scrollAnimatedValue,
inverted,
offset,
animatedValueListener,
isFabric,
]);
const _onLayout = (event: LayoutEvent) => {
setLayoutY(event.nativeEvent.layout.y);
setLayoutHeight(event.nativeEvent.layout.height);
setMeasured(true);
props.onLayout(event);
const child = React.Children.only<$FlowFixMe>(props.children);
if (child.props.onLayout) {
child.props.onLayout(event);
}
};
const child = React.Children.only<$FlowFixMe>(props.children);
const passthroughAnimatedPropExplicitValues =
isFabric && translateY != null
? {
style: {transform: [{translateY: translateY}]},
}
: null;
return (
/* $FlowFixMe[prop-missing] passthroughAnimatedPropExplicitValues isn't properly
included in the Animated.View flow type. */
<Animated.View
collapsable={false}
nativeID={props.nativeID}
onLayout={_onLayout}
ref={ref}
style={[
child.props.style,
styles.header,
{transform: [{translateY: animatedTranslateY}]},
]}
passthroughAnimatedPropExplicitValues={
passthroughAnimatedPropExplicitValues
}>
{React.cloneElement(child, {
style: styles.fill, // We transfer the child style to the wrapper.
onLayout: undefined, // we call this manually through our this._onLayout
})}
</Animated.View>
);
});
const styles = StyleSheet.create({
header: {
zIndex: 10,
position: 'relative',
},
fill: {
flex: 1,
},
});
export default ScrollViewStickyHeaderWithForwardedRef;