Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,13 @@ only fits one side's typings fails there.
list's callbacks. Treat handle names and signatures as public API. A handle
runs on the JS thread, as often as every scroll frame, and on Reanimated 3 a
shared value read from JS blocks until the UI thread answers. So a handle
reads JS copies kept in refs (`FastScrollIndicator`) or sends the work to the
UI thread with `runOnUI` (`FastScrollSectionDotsBar`).
reads JS copies kept in refs or sends the work to the UI thread with
`runOnUI`. While a finger on a bar leads, the handle sends the thumb's move to
the UI thread, and the worklet drops it there if the pan has set its "finger
down" flag, so a report already in line when the finger lands cannot move the
thumb. `FastScrollIndicator` also checks a JS copy of the flag first: its list
follows the drag, so scroll events from the drag keep arriving after the
finger lifts.
- **Two version targets.** Code must run on the minimum peers this repo
develops against (`react-native-reanimated` 2.12, `react-native-gesture-handler`
2.8, the dev dependencies) and on the versions production runs
Expand Down
34 changes: 5 additions & 29 deletions docs/backlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ npm has 0.3.4. On top of it, `main` has these changes:
- The dots' thumb starts on the current section each time the bar shows.
- The hide and retry timers are cleared on unmount.
- The indicator keeps its thumb at the end while the list overscrolls.
- The indicator's thumb stays under a finger that lands while the list is
still reporting its scroll.
- Neither component reads a shared value from JS on the scroll or drag path
(on Reanimated 3 that read blocks the JS thread), and a drag on the dots
crosses to JS only when the section changes.
Expand All @@ -26,10 +28,9 @@ the whole patch (see `CLAUDE.md`).

Before that release:

- Check two items on a device, with the example app (Reanimated 3): "The
indicator's thumb can leave the finger when it is grabbed while the list
moves" and "The open section list jumps instead of gliding while the finger
crosses dots" below. Neither can show under Jest.
- Check on a device, with the example app (Reanimated 3), "The open section
list jumps instead of gliding while the finger crosses dots" below. It
cannot show under Jest.
- Decide whether "The indicator shows itself while the list overscrolls" below
is wanted.
- Carried over from the 0.3.4 release, in case it was not done then: check on a
Expand All @@ -40,31 +41,6 @@ Before that release:

## Bugs

### The indicator's thumb can leave the finger when it is grabbed while the list moves

[FastScrollIndicator.tsx:224-229](../src/FastScrollIndicator/FastScrollIndicator.tsx#L224-L229):
the "finger on the track" flag reaches JS through `runOnJS`. Scroll events
already queued on the JS thread when the finger lands still pass the check in
`onScrollToOffsetPercentage`
([line 275](../src/FastScrollIndicator/FastScrollIndicator.tsx#L275)) and write
the list's old position to `translateY`, after the pan's `onBegin` wrote the
finger's. The thumb then stays there until the finger moves far enough to
activate the pan, or lifts.

Before, the flag was a shared value set on the UI thread at touch down and read
synchronously from JS, which rejected those events. It had the mirror problem
on lift (late scroll events moved the thumb back), which the JS flag fixes.

Not confirmed on a device. It needs a busy JS thread, such as a fling through a
long list, and it cannot show under Jest, where `runOnJS` is synchronous.

Possible fix: write the thumb the way the dots bar does
([FastScrollSectionDotsBar.tsx:347-370](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L347-L370)):
send the offset to the UI thread with `runOnUI` and check a shared flag there.
A write to a shared value from JS already crosses to the UI thread, so it costs
the same. Keep the JS flag for the hide timer only. That also leaves one
pattern for "a finger leads, the list's reports are ignored" instead of two.

### The indicator shows itself while the list overscrolls

[FastScrollIndicator.tsx:283-287](../src/FastScrollIndicator/FastScrollIndicator.tsx#L283-L287):
Expand Down
32 changes: 30 additions & 2 deletions docs/unit-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,8 @@ that restores the native `Promise`. Keep it until RN is upgraded to 0.71+.
`react-native-reanimated` is **not** mocked. Under Jest it switches to its JS
implementation, so shared values, `useAnimatedStyle`, `withSpring`, `runOnJS`
and the `entering`/`exiting` layout animations all execute. `runOnJS(fn)` calls
`fn` synchronously there.
`fn` synchronously there; a test that needs the call to wait uses [A busy JS
thread](#a-busy-js-thread).

Its frame clock reads `global.ReanimatedDataMock.now()`, which `jest/setup.js`
backs with `Date.now()`. Consequence: animations follow Jest's clock - with fake
Expand Down Expand Up @@ -218,6 +219,31 @@ expect(getThumbPosition()).toBe(39); // the middle of the second dot
Everything else animated (scale, slide-in) is decoration: assert on what is
rendered and which callbacks fired.

### A busy JS thread

On a device a pan runs on the UI thread, and its `runOnJS(fn)(...)` puts the
call in line on the JS thread, behind the work already there, such as the
list events an app forwards to a handle. Under Jest `fn` runs at once, so a
handle call never lands between a gesture and the calls it sent to JS. A suite
that tests that order mocks Reanimated with `reanimatedWithJsThread` from
`src/__fixtures__/jsThread.ts` and wraps the overlap in `whileJsThreadIsBusy`:

```tsx
jest.mock('react-native-reanimated', () =>
require('../../__fixtures__/jsThread').reanimatedWithJsThread()
);

whileJsThreadIsBusy(() => {
touchDown(275); // the pan runs; its runOnJS calls wait in line
scrollListTo(0.2); // a list event that was in line before them
}); // then the waiting calls run, in order
```

It is the real Reanimated with a `runOnJS` that waits only inside
`whileJsThreadIsBusy`, so the rest of the suite runs as everywhere else.
`runOnUI` still runs at once, in order with the gesture callbacks, as the UI
thread runs it on a device.

### Gestures

`react-native-gesture-handler` is set up with its official `jestSetup`. Every
Expand Down Expand Up @@ -443,7 +469,9 @@ queries, `@testing-library/jest-native`) do not match this setup.
covers.
- Reanimated, gesture-handler, redash and `throttle-debounce` run for real.
Never mock them to make a test pass; if one fails to load, fix the global
setup in `jest/` instead of the test.
setup in `jest/` instead of the test. The one partial mock,
`reanimatedWithJsThread`, adds the thread hop Jest leaves out ([A busy JS
thread](#a-busy-js-thread)).
- Mock at module boundaries with `jest.mock('module')` at the top of the file.
Type mock access with `jest.mocked(fn)`; build partial expectations with
`expect.objectContaining` rather than exhaustive literals.
Expand Down
1 change: 1 addition & 0 deletions example/src/ExamplesScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export const ExamplesScreen = () => {
{ title: 'ReplaceSections', destination: 'ReplaceSections' },
{ title: 'IndicatorCost', destination: 'IndicatorCost' },
{ title: 'IndicatorBounce', destination: 'IndicatorBounce' },
{ title: 'IndicatorGrab', destination: 'IndicatorGrab' },
];
return (
<>
Expand Down
2 changes: 2 additions & 0 deletions example/src/NavigationTree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import MemoryLeak from './memoryLeak/MemoryLeak';
import ReplaceSections from './replaceSections/ReplaceSections';
import IndicatorCost from './indicatorCost/IndicatorCost';
import IndicatorBounce from './indicatorBounce/IndicatorBounce';
import IndicatorGrab from './indicatorGrab/IndicatorGrab';

const Stack = createStackNavigator<RootStackParamList>();

Expand All @@ -29,6 +30,7 @@ const NavigationTree = () => {
<Stack.Screen name="ReplaceSections" component={ReplaceSections} />
<Stack.Screen name="IndicatorCost" component={IndicatorCost} />
<Stack.Screen name="IndicatorBounce" component={IndicatorBounce} />
<Stack.Screen name="IndicatorGrab" component={IndicatorGrab} />
</Stack.Group>

<Stack.Group screenOptions={{ presentation: 'modal' }}>
Expand Down
118 changes: 118 additions & 0 deletions example/src/indicatorGrab/IndicatorGrab.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import React, { useCallback, useRef } from 'react';
import {
NativeScrollEvent,
NativeSyntheticEvent,
StyleSheet,
Text,
View,
} from 'react-native';
import { FlashList } from '@shopify/flash-list';
import { FastScrollIndicator } from 'react-native-fast-scroll';

/**
* Grabs `FastScrollIndicator`'s thumb while the JS thread is busy, as on a
* heavy screen. Every `onScroll` frame calls the handle and then keeps the JS
* thread busy for `BUSY_MS`, so while the list flings its scroll events pile
* up there.
*
* Fling the list, then rest a finger on the track without moving it. The pan
* runs on the UI thread and puts the thumb under the finger at once, but its
* "finger down" message reaches the JS thread behind those scroll events. The
* thumb must stay under the finger while they are handled.
*/

const ROWS = Array.from({ length: 2000 }, (_, i) => i);
const ROW_HEIGHT = 44;
const BUSY_MS = 40;
const THUMB = { width: 10, height: 60, borderRadius: 5 };

const busyFor = (ms: number) => {
const until = Date.now() + ms;
while (Date.now() < until) {
// The work a heavy screen does on each scroll frame.
}
};

const IndicatorGrab = () => {
const indicatorRef =
useRef<React.ElementRef<typeof FastScrollIndicator>>(null);
const listRef = useRef<FlashList<number>>(null);
const scrollableHeight = useRef(0);

const onScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
const { contentOffset, contentSize, layoutMeasurement } =
event.nativeEvent;
scrollableHeight.current = Math.max(
0,
contentSize.height - layoutMeasurement.height
);
const offsetPercentage =
scrollableHeight.current > 0
? contentOffset.y / scrollableHeight.current
: 0;
indicatorRef.current?.onScrollToOffsetPercentage(offsetPercentage);
busyFor(BUSY_MS);
},
[]
);

const scrollToOffsetPercentage = useCallback((offsetPercentage: number) => {
listRef.current?.scrollToOffset({
offset: offsetPercentage * scrollableHeight.current,
animated: false,
});
}, []);

return (
<View style={styles.container}>
<View style={styles.panel}>
<Text style={styles.report}>
Each scroll frame keeps the JS thread busy for {BUSY_MS} ms. Fling the
list, then rest a finger on the track: the thumb stays under it.
</Text>
</View>
<View style={styles.listContainer}>
<FlashList
ref={listRef}
data={ROWS}
estimatedItemSize={ROW_HEIGHT}
onScroll={onScroll}
scrollEventThrottle={16}
renderItem={({ item }) => (
<View style={styles.row}>
<Text>Row {item + 1}</Text>
</View>
)}
/>
<View style={styles.indicator}>
<FastScrollIndicator
ref={indicatorRef}
scrollToOffsetPercentage={scrollToOffsetPercentage}
thumbSize={THUMB}
thumbColor={'#1F3A5F'}
scrollBarColor={'rgba(31, 58, 95, 0.12)'}
hideFastScrollIndicatorTimeout={0}
/>
</View>
</View>
</View>
);
};

const styles = StyleSheet.create({
container: { flex: 1 },
panel: { padding: 12, backgroundColor: '#1F3A5F' },
report: { color: 'white', fontSize: 14 },
listContainer: { flex: 1 },
row: {
height: ROW_HEIGHT,
justifyContent: 'center',
paddingHorizontal: 16,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#ddd',
},
indicator: { position: 'absolute', top: 0, bottom: 0, right: 1 },
});

export default IndicatorGrab;
1 change: 1 addition & 0 deletions example/src/screens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ export type RootStackParamList = {
ReplaceSections: undefined;
IndicatorCost: undefined;
IndicatorBounce: undefined;
IndicatorGrab: undefined;
};
48 changes: 35 additions & 13 deletions src/FastScrollIndicator/FastScrollIndicator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { StyleSheet, ColorValue, LayoutChangeEvent } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, {
runOnJS,
runOnUI,
SlideInLeft,
SlideInRight,
SlideOutLeft,
Expand Down Expand Up @@ -112,22 +113,28 @@ export const FastScrollIndicator = React.forwardRef(
const translateFastScrollBarXTimer = useRef<NodeJS.Timeout | null>(null);
const viewLayout = useSharedValue({ x: 0, y: 0, height: 0, width: 0 });

// Apps call onScrollToOffsetPercentage on every scroll frame. On
// Reanimated 3, reading a shared value from JS takes the UI runtime's
// lock, so the JS thread waits while the UI thread runs worklets, which
// it does on every frame of a scroll (this thumb's springs, at least).
// So that handle reads JS copies instead: the track's height, kept from
// onLayout, and whether a finger is on the track, set from the pan's
// onBegin and onFinalize.
const trackHeight = useRef(0);
// While a finger is on the track it leads, and the list's reports through
// onScrollToOffsetPercentage are ignored. Those reports trail the finger
// at both ends of the touch, so the pan keeps two copies of the flag:
// - On the UI thread, set the moment the finger lands. The handle sends
// the thumb's new position there and the check runs there, so a report
// that was already in line on the JS thread when the finger landed can
// no longer pull the thumb from under it.
// - On the JS thread, set through runOnJS, behind the list's scroll events
// already in line there. The handle checks it first: when the finger
// lifts, those events report where the finger was a few frames before.
// It also keeps them from restarting the hide timer under the finger.
// The handle never reads a shared value: apps call it on every scroll
// frame, and on Reanimated 3 that read blocks the JS thread until the UI
// thread answers.
const fingerOnTrackOnUI = useSharedValue(false);
const fingerOnTrack = useRef(false);
const setFingerOnTrack = useCallback((isOnTrack: boolean) => {
fingerOnTrack.current = isOnTrack;
}, []);
const onTrackLayout = useCallback(
(event: LayoutChangeEvent) => {
viewLayout.value = event.nativeEvent.layout;
trackHeight.current = event.nativeEvent.layout.height;
},
[viewLayout]
);
Expand Down Expand Up @@ -223,7 +230,8 @@ export const FastScrollIndicator = React.forwardRef(
// The finger touches the track
.onBegin((event) => {
scale.value = thumbScaleOnPress;
// Before the list scrolls: its scroll events are ignored from now on.
// Before the list scrolls: its reports are ignored from now on.
fingerOnTrackOnUI.value = true;
runOnJS(setFingerOnTrack)(true);
followFinger(event.y);
})
Expand All @@ -236,12 +244,14 @@ export const FastScrollIndicator = React.forwardRef(
processScroll(yPercentage);
translateY.value = yPosition;
scale.value = 1;
fingerOnTrackOnUI.value = false;
runOnJS(setFingerOnTrack)(false);
runOnJS(scheduleHideFastScrollbar)();
})
);
}, [
clearTimeoutFastScrollBar,
fingerOnTrackOnUI,
processScrollJSThread,
scale,
scheduleHideFastScrollbar,
Expand All @@ -268,6 +278,20 @@ export const FastScrollIndicator = React.forwardRef(
};
});

/** Moves the thumb to where the list is, unless a finger is on the track. */
const followListOnUI = useMemo(
() =>
runOnUI((offsetPercentage: number) => {
'worklet';
if (fingerOnTrackOnUI.value) {
return;
}
translateY.value =
offsetPercentage * (viewLayout.value.height - thumbHeight);
}),
[fingerOnTrackOnUI, thumbHeight, translateY, viewLayout]
);

React.useImperativeHandle(
forwardedRef,
(): FastScrollIndicatorHandle => ({
Expand All @@ -280,9 +304,7 @@ export const FastScrollIndicator = React.forwardRef(
// A list that bounces past either end (iOS) reports offsets below 0
// and above 1, and can come to rest just past 1. The thumb stays at
// that end of the track.
const clampedOffset = Math.min(1, Math.max(0, offsetPercentage));
translateY.value =
clampedOffset * (trackHeight.current - thumbSize.height);
followListOnUI(Math.min(1, Math.max(0, offsetPercentage)));

showFastScrollBar();
},
Expand Down
Loading
Loading