-
-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathindex.tsx
More file actions
582 lines (504 loc) · 19.4 KB
/
index.tsx
File metadata and controls
582 lines (504 loc) · 19.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
import React, {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
} from "react";
import Reanimated, {
clamp,
interpolate,
runOnUI,
scrollTo,
useAnimatedReaction,
useAnimatedRef,
useDerivedValue,
useSharedValue,
} from "react-native-reanimated";
import { KeyboardControllerNative } from "../../bindings";
import {
useFocusedInputHandler,
useReanimatedFocusedInput,
useWindowDimensions,
} from "../../hooks";
import { findNodeHandle } from "../../utils/findNodeHandle";
import useCombinedRef from "../hooks/useCombinedRef";
import useScrollState from "../hooks/useScrollState";
import ScrollViewWithBottomPadding from "../ScrollViewWithBottomPadding";
import { useSmoothKeyboardHandler } from "./useSmoothKeyboardHandler";
import { debounce, scrollDistanceWithRespectToSnapPoints } from "./utils";
import type { AnimatedScrollViewComponent } from "../ScrollViewWithBottomPadding";
import type {
LayoutChangeEvent,
ScrollView,
ScrollViewProps,
} from "react-native";
import type {
FocusedInputLayoutChangedEvent,
FocusedInputSelectionChangedEvent,
NativeEvent,
} from "react-native-keyboard-controller";
export type KeyboardAwareScrollViewProps = {
/** The distance between the keyboard and the caret inside a focused `TextInput` when the keyboard is shown. Default is `0`. */
bottomOffset?: number;
/** Prevents automatic scrolling of the `ScrollView` when the keyboard gets hidden, maintaining the current screen position. Default is `false`. */
disableScrollOnKeyboardHide?: boolean;
/** Controls whether this `KeyboardAwareScrollView` instance should take effect. Default is `true`. */
enabled?: boolean;
/** Adjusting the bottom spacing of KeyboardAwareScrollView. Default is `0`. */
extraKeyboardSpace?: number;
/** Custom component for `ScrollView`. Default is `ScrollView`. */
ScrollViewComponent?: AnimatedScrollViewComponent;
} & ScrollViewProps;
export type KeyboardAwareScrollViewRef = {
assureFocusedInputVisible: () => void;
} & ScrollView;
// Everything begins from `onStart` handler. This handler is called every time,
// when keyboard changes its size or when focused `TextInput` was changed. In
// this handler we are calculating/memoizing values which later will be used
// during layout movement. For that we calculate:
// - layout of focused field (`layout`) - to understand whether there will be overlap
// - initial keyboard size (`initialKeyboardSize`) - used in scroll interpolation
// - future keyboard height (`keyboardHeight`) - used in scroll interpolation
// - current scroll position (`scrollPosition`) - used to scroll from this point
//
// Once we've calculated all necessary variables - we can actually start to use them.
// It happens in `onMove` handler - this function simply calls `maybeScroll` with
// current keyboard frame height. This functions makes the smooth transition.
//
// When the transition has finished we go to `onEnd` handler. In this handler
// we verify, that the current field is not overlapped within a keyboard frame.
// For full `onStart`/`onMove`/`onEnd` flow it may look like a redundant thing,
// however there could be some cases, when `onMove` is not called:
// - on iOS when TextInput was changed - keyboard transition is instant
// - on Android when TextInput was changed and keyboard size wasn't changed
// So `onEnd` handler handle the case, when `onMove` wasn't triggered.
//
// ====================================================================================================================+
// -----------------------------------------------------Flow chart-----------------------------------------------------+
// ====================================================================================================================+
//
// +============================+ +============================+ +==================================+
// + User Press on TextInput + => + Keyboard starts showing + => + As keyboard moves frame by frame + =>
// + + + (run `onStart`) + + `onMove` is getting called +
// +============================+ +============================+ +==================================+
//
// +============================+ +============================+ +=====================================+
// + Keyboard is shown and we + => + User moved focus to + => + Only `onStart`/`onEnd` maybe called +
// + call `onEnd` handler + + another `TextInput` + + (without involving `onMove`) +
// +============================+ +============================+ +=====================================+
//
/**
* A ScrollView component that automatically handles keyboard appearance and disappearance
* by adjusting its content position to ensure the focused input remains visible.
*
* The component uses a sophisticated animation system to smoothly handle keyboard transitions
* and maintain proper scroll position during keyboard interactions.
*
* @returns A ScrollView component that handles keyboard interactions.
* @see {@link https://kirillzyusko.github.io/react-native-keyboard-controller/docs/api/components/keyboard-aware-scroll-view|Documentation} page for more details.
* @example
* ```tsx
* <KeyboardAwareScrollView bottomOffset={20}>
* <TextInput placeholder="Enter text" />
* <TextInput placeholder="Another input" />
* </KeyboardAwareScrollView>
* ```
*/
const KeyboardAwareScrollView = forwardRef<
KeyboardAwareScrollViewRef,
React.PropsWithChildren<KeyboardAwareScrollViewProps>
>(
(
{
children,
onLayout,
bottomOffset = 0,
disableScrollOnKeyboardHide = false,
enabled = true,
extraKeyboardSpace = 0,
ScrollViewComponent = Reanimated.ScrollView,
snapToOffsets,
...rest
},
ref,
) => {
const scrollViewAnimatedRef = useAnimatedRef<Reanimated.ScrollView>();
const scrollViewRef = React.useRef<ScrollView>(null);
const onRef = useCombinedRef(scrollViewAnimatedRef, scrollViewRef);
const scrollViewTarget = useSharedValue<number | null>(null);
const scrollPosition = useSharedValue(0);
const {
offset: position,
layout: scrollViewLayout,
size: scrollViewContentSize,
} = useScrollState(scrollViewAnimatedRef);
const currentKeyboardFrameHeight = useSharedValue(0);
const keyboardHeight = useSharedValue(0);
const keyboardWillAppear = useSharedValue(false);
const tag = useSharedValue(-1);
const initialKeyboardSize = useSharedValue(0);
const scrollBeforeKeyboardMovement = useSharedValue(0);
const { input, update } = useReanimatedFocusedInput();
const layout = useSharedValue<FocusedInputLayoutChangedEvent | null>(null);
const lastSelection =
useSharedValue<FocusedInputSelectionChangedEvent | null>(null);
const ghostViewSpace = useSharedValue(-1);
const pendingSelectionForFocus = useSharedValue(false);
const scrollViewPageY = useSharedValue(0);
const { height } = useWindowDimensions();
const onScrollViewLayout = useCallback(
async (e: LayoutChangeEvent) => {
const handle = findNodeHandle(scrollViewAnimatedRef.current);
scrollViewTarget.value = handle;
onLayout?.(e);
if (handle !== null) {
try {
const { y } = await KeyboardControllerNative.viewPositionInWindow(
handle,
);
scrollViewPageY.value = y;
} catch {
// ignore
}
}
},
[onLayout],
);
/**
* Function that will scroll a ScrollView as keyboard gets moving.
*/
const maybeScroll = useCallback(
(e: number, animated: boolean = false) => {
"worklet";
if (!enabled) {
return 0;
}
// input belongs to ScrollView
if (layout.value?.parentScrollViewTarget !== scrollViewTarget.value) {
return 0;
}
const visibleRect = height - keyboardHeight.value;
const absoluteY = layout.value?.layout.absoluteY || 0;
const inputHeight = layout.value?.layout.height || 0;
const point = absoluteY + inputHeight;
if (visibleRect - point <= bottomOffset) {
const relativeScrollTo =
keyboardHeight.value - (height - point) + bottomOffset;
const interpolatedScrollTo = interpolate(
e,
[initialKeyboardSize.value, keyboardHeight.value],
[
0,
scrollDistanceWithRespectToSnapPoints(
relativeScrollTo + scrollPosition.value,
snapToOffsets,
) - scrollPosition.value,
],
);
const targetScrollY =
Math.max(interpolatedScrollTo, 0) + scrollPosition.value;
scrollTo(scrollViewAnimatedRef, 0, targetScrollY, animated);
return interpolatedScrollTo;
}
if (point < scrollViewPageY.value) {
const positionOnScreen = visibleRect - bottomOffset;
const topOfScreen = scrollPosition.value + point;
scrollTo(
scrollViewAnimatedRef,
0,
topOfScreen - positionOnScreen,
animated,
);
}
return 0;
},
[bottomOffset, enabled, height, snapToOffsets],
);
const removeGhostPadding = useCallback((e: number) => {
"worklet";
// new `ScrollViewWithBottomPadding` behavior: if we hide keyboard and we are in the end of `ScrollView`
// then we always need to scroll back, because we apply a padding that doesn't change layout, so we will
// not have auto scroll back in this case
if (!keyboardWillAppear.value && ghostViewSpace.value > 0) {
scrollTo(
scrollViewAnimatedRef,
0,
scrollPosition.value -
interpolate(
e,
[initialKeyboardSize.value, keyboardHeight.value],
[ghostViewSpace.value, 0],
),
false,
);
return true;
}
return false;
}, []);
const performScrollWithPositionRestoration = useCallback(
(newPosition: number) => {
"worklet";
const prevScroll = scrollPosition.value;
// eslint-disable-next-line react-compiler/react-compiler
scrollPosition.value = newPosition;
maybeScroll(keyboardHeight.value, true);
scrollPosition.value = prevScroll;
},
[scrollPosition, keyboardHeight, maybeScroll],
);
const syncKeyboardFrame = useCallback(
(e: NativeEvent) => {
"worklet";
const keyboardFrame = interpolate(
e.height,
[0, keyboardHeight.value],
[0, keyboardHeight.value + extraKeyboardSpace],
);
currentKeyboardFrameHeight.value = keyboardFrame;
},
[extraKeyboardSpace],
);
const updateLayoutFromSelection = useCallback(() => {
"worklet";
const customHeight = lastSelection.value?.selection.end.y;
if (!input.value?.layout || !customHeight) {
return false;
}
layout.value = {
...input.value,
layout: {
...input.value.layout,
// when we have multiline input with limited amount of lines, then custom height can be very big
// so we clamp it to max input height
height: clamp(customHeight, 0, input.value.layout.height),
},
};
return true;
}, [input, lastSelection, layout]);
const scrollFromCurrentPosition = useCallback(() => {
"worklet";
const prevLayout = layout.value;
if (!updateLayoutFromSelection()) {
return;
}
performScrollWithPositionRestoration(position.value);
layout.value = prevLayout;
}, [performScrollWithPositionRestoration]);
const onChangeText = useCallback(() => {
"worklet";
scrollFromCurrentPosition();
}, [scrollFromCurrentPosition]);
const onChangeTextHandler = useMemo(
() => debounce(onChangeText, 200),
[onChangeText],
);
const onSelectionChange = useCallback(
(e: FocusedInputSelectionChangedEvent) => {
"worklet";
const lastTarget = lastSelection.value?.target;
const latestSelection = lastSelection.value?.selection;
lastSelection.value = e;
if (e.target !== lastTarget) {
if (pendingSelectionForFocus.value) {
// selection arrived after onStart - complete the deferred setup
pendingSelectionForFocus.value = false;
updateLayoutFromSelection();
// if keyboard was already visible (focus change, no onMove expected),
// perform the deferred scroll now
if (!keyboardWillAppear.value && keyboardHeight.value > 0) {
position.value += maybeScroll(keyboardHeight.value, true);
}
}
return;
}
// caret in the end + end coordinates has been changed -> we moved to a new line
// so input may grow
if (
e.selection.end.position === e.selection.start.position &&
latestSelection?.end.y !== e.selection.end.y
) {
return scrollFromCurrentPosition();
}
// selection has been changed
if (e.selection.start.position !== e.selection.end.position) {
return scrollFromCurrentPosition();
}
onChangeTextHandler();
},
[
scrollFromCurrentPosition,
onChangeTextHandler,
updateLayoutFromSelection,
maybeScroll,
],
);
useFocusedInputHandler(
{
onSelectionChange: onSelectionChange,
},
[onSelectionChange],
);
useSmoothKeyboardHandler(
{
onStart: (e) => {
"worklet";
const keyboardWillChangeSize =
keyboardHeight.value !== e.height && e.height > 0;
keyboardWillAppear.value = e.height > 0 && keyboardHeight.value === 0;
const keyboardWillHide = e.height === 0;
const focusWasChanged =
(tag.value !== e.target && e.target !== -1) ||
keyboardWillChangeSize;
if (keyboardWillChangeSize) {
initialKeyboardSize.value = keyboardHeight.value;
}
if (keyboardWillHide) {
// on back transition need to interpolate as [0, keyboardHeight]
initialKeyboardSize.value = 0;
scrollPosition.value = scrollBeforeKeyboardMovement.value;
pendingSelectionForFocus.value = false;
}
if (
keyboardWillAppear.value ||
keyboardWillChangeSize ||
focusWasChanged
) {
// persist scroll value
scrollPosition.value = position.value;
// just persist height - later will be used in interpolation
keyboardHeight.value = e.height;
}
// focus was changed
if (focusWasChanged) {
tag.value = e.target;
if (lastSelection.value?.target === e.target) {
// selection arrived before onStart - use it to update layout
updateLayoutFromSelection();
pendingSelectionForFocus.value = false;
} else {
// selection hasn't arrived yet for the new target.
// use input layout as-is; will be refined when selection arrives.
if (input.value) {
layout.value = input.value;
}
pendingSelectionForFocus.value = true;
}
// save current scroll position - when keyboard will hide we'll reuse
// this value to achieve smooth hide effect
scrollBeforeKeyboardMovement.value = position.value;
}
if (focusWasChanged && !keyboardWillAppear.value) {
if (!pendingSelectionForFocus.value) {
// update position on scroll value, so `onEnd` handler
// will pick up correct values
position.value += maybeScroll(e.height, true);
}
}
ghostViewSpace.value =
position.value +
scrollViewLayout.value.height -
scrollViewContentSize.value.height;
if (ghostViewSpace.value > 0) {
scrollPosition.value = position.value;
}
},
onMove: (e) => {
"worklet";
syncKeyboardFrame(e);
if (removeGhostPadding(e.height)) {
return;
}
// if the user has set disableScrollOnKeyboardHide, only auto-scroll when the keyboard opens
if (!disableScrollOnKeyboardHide || keyboardWillAppear.value) {
maybeScroll(e.height);
}
},
onEnd: (e) => {
"worklet";
removeGhostPadding(e.height);
keyboardHeight.value = e.height;
scrollPosition.value = position.value;
if (e.height === 0) {
lastSelection.value = null;
}
syncKeyboardFrame(e);
},
},
[
maybeScroll,
removeGhostPadding,
disableScrollOnKeyboardHide,
syncKeyboardFrame,
],
);
const synchronize = useCallback(async () => {
await update();
runOnUI(() => {
"worklet";
scrollFromCurrentPosition();
})();
}, [update, scrollFromCurrentPosition]);
useImperativeHandle(
ref,
() => {
const scrollView = scrollViewRef.current;
if (scrollView) {
const scrollViewWithMethods =
scrollView as KeyboardAwareScrollViewRef;
scrollViewWithMethods.assureFocusedInputVisible = () => {
synchronize();
};
return scrollViewWithMethods;
}
return {
assureFocusedInputVisible: () => {
synchronize();
},
} as KeyboardAwareScrollViewRef;
},
[synchronize],
);
useEffect(() => {
synchronize();
}, [bottomOffset]);
useAnimatedReaction(
() => input.value,
(current, previous) => {
if (
current?.target === previous?.target &&
current?.layout.height !== previous?.layout.height
) {
// input has changed layout - let's check if we need to scroll
// may happen when you paste text, then onSelectionChange will be
// fired earlier than text actually changes its layout
scrollFromCurrentPosition();
}
},
[],
);
// animations become choppy when scrolling to the end of the `ScrollView` (when the last input is focused)
// this happens because the layout recalculates on every frame. To avoid this we slightly increase padding
// by `+1`. In this way we assure, that `scrollTo` will never scroll to the end, because it uses interpolation
// from 0 to `keyboardHeight`, and here our padding is `keyboardHeight + 1`. It allows us not to re-run layout
// re-calculation on every animation frame and it helps to achieve smooth animation.
// see: https://github.com/kirillzyusko/react-native-keyboard-controller/pull/342
const padding = useDerivedValue(
() => (enabled ? currentKeyboardFrameHeight.value + 1 : 0),
[enabled],
);
return (
<ScrollViewWithBottomPadding
ref={onRef}
{...rest}
bottomPadding={padding}
scrollEventThrottle={16}
ScrollViewComponent={ScrollViewComponent}
onLayout={onScrollViewLayout}
>
{children}
</ScrollViewWithBottomPadding>
);
},
);
export default KeyboardAwareScrollView;