diff --git a/CLAUDE.md b/CLAUDE.md index 3844289..5f7e39a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/docs/backlog.md b/docs/backlog.md index 7278cca..60bdb57 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -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. @@ -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 @@ -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): diff --git a/docs/unit-testing.md b/docs/unit-testing.md index b382c8d..cf949dc 100644 --- a/docs/unit-testing.md +++ b/docs/unit-testing.md @@ -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 @@ -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 @@ -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. diff --git a/example/src/ExamplesScreen.tsx b/example/src/ExamplesScreen.tsx index 5e2b1f9..8463168 100644 --- a/example/src/ExamplesScreen.tsx +++ b/example/src/ExamplesScreen.tsx @@ -28,6 +28,7 @@ export const ExamplesScreen = () => { { title: 'ReplaceSections', destination: 'ReplaceSections' }, { title: 'IndicatorCost', destination: 'IndicatorCost' }, { title: 'IndicatorBounce', destination: 'IndicatorBounce' }, + { title: 'IndicatorGrab', destination: 'IndicatorGrab' }, ]; return ( <> diff --git a/example/src/NavigationTree.tsx b/example/src/NavigationTree.tsx index fb5da19..985dcd2 100644 --- a/example/src/NavigationTree.tsx +++ b/example/src/NavigationTree.tsx @@ -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(); @@ -29,6 +30,7 @@ const NavigationTree = () => { + diff --git a/example/src/indicatorGrab/IndicatorGrab.tsx b/example/src/indicatorGrab/IndicatorGrab.tsx new file mode 100644 index 0000000..e3027a2 --- /dev/null +++ b/example/src/indicatorGrab/IndicatorGrab.tsx @@ -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>(null); + const listRef = useRef>(null); + const scrollableHeight = useRef(0); + + const onScroll = useCallback( + (event: NativeSyntheticEvent) => { + 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 ( + + + + 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. + + + + ( + + Row {item + 1} + + )} + /> + + + + + + ); +}; + +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; diff --git a/example/src/screens.ts b/example/src/screens.ts index 5703df2..cd7492f 100644 --- a/example/src/screens.ts +++ b/example/src/screens.ts @@ -9,4 +9,5 @@ export type RootStackParamList = { ReplaceSections: undefined; IndicatorCost: undefined; IndicatorBounce: undefined; + IndicatorGrab: undefined; }; diff --git a/src/FastScrollIndicator/FastScrollIndicator.tsx b/src/FastScrollIndicator/FastScrollIndicator.tsx index 49ac7b5..33771f5 100644 --- a/src/FastScrollIndicator/FastScrollIndicator.tsx +++ b/src/FastScrollIndicator/FastScrollIndicator.tsx @@ -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, @@ -112,14 +113,21 @@ export const FastScrollIndicator = React.forwardRef( const translateFastScrollBarXTimer = useRef(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; @@ -127,7 +135,6 @@ export const FastScrollIndicator = React.forwardRef( const onTrackLayout = useCallback( (event: LayoutChangeEvent) => { viewLayout.value = event.nativeEvent.layout; - trackHeight.current = event.nativeEvent.layout.height; }, [viewLayout] ); @@ -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); }) @@ -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, @@ -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 => ({ @@ -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(); }, diff --git a/src/FastScrollIndicator/__tests__/FastScrollIndicator.test.tsx b/src/FastScrollIndicator/__tests__/FastScrollIndicator.test.tsx index ae90fbb..07372aa 100644 --- a/src/FastScrollIndicator/__tests__/FastScrollIndicator.test.tsx +++ b/src/FastScrollIndicator/__tests__/FastScrollIndicator.test.tsx @@ -7,8 +7,13 @@ import { layoutPanArea, touchDown, } from '../../__fixtures__/gestures'; +import { whileJsThreadIsBusy } from '../../__fixtures__/jsThread'; import { getThumbPosition } from '../../__fixtures__/positions'; +jest.mock('react-native-reanimated', () => + require('../../__fixtures__/jsThread').reanimatedWithJsThread() +); + // A 50px thumb on a 550px track: its center travels from y=25 to y=525. const THUMB = { width: 7, height: 50, borderRadius: 7 }; const TRACK_HEIGHT = 550; @@ -207,6 +212,43 @@ describe('FastScrollIndicator', () => { expect(isScrollBarShown()).toBe(false); }); + // On a device the pan tells the JS thread that a finger is down through + // runOnJS, behind the list's scroll events already in line there, as when + // the finger catches a list that is still flinging. + it('keeps the thumb under the finger when the list reports its old offset as the finger lands', () => { + const { scrollListTo } = renderIndicator({ + hideFastScrollIndicatorTimeout: 1000, + }); + scrollListTo(0.1); + + whileJsThreadIsBusy(() => { + touchDown(275); + scrollListTo(0.2); + }); + act(() => jest.advanceTimersByTime(5000)); + + expect(getThumbPosition()).toBe(250); + expect(isScrollBarShown()).toBe(true); + }); + + // The other end of the touch: the pan tells the JS thread that the finger + // lifted behind the list's scroll events of the drag, which report where the + // finger was a few frames before. + it('keeps the thumb where the finger lifts when the list reports an earlier offset of the drag', () => { + const { scrollListTo } = renderIndicator(); + scrollListTo(0.1); + const finger = touchDown(275); + finger.moveTo(400); + + whileJsThreadIsBusy(() => { + finger.lift(); + scrollListTo(0.5); + }); + + // The thumb's top at the finger: 400 - 25. + expect(getThumbPosition()).toBe(375); + }); + it('follows the list again once the finger lifts', () => { const { scrollListTo } = renderIndicator(); scrollListTo(0.1); diff --git a/src/__fixtures__/jsThread.ts b/src/__fixtures__/jsThread.ts new file mode 100644 index 0000000..085f5f5 --- /dev/null +++ b/src/__fixtures__/jsThread.ts @@ -0,0 +1,57 @@ +import { act } from '@testing-library/react-native'; + +type Reanimated = typeof import('react-native-reanimated'); + +/** The runOnJS calls waiting for the JS thread, while it is busy. */ +let waitingCalls: (() => void)[] | null = null; + +/** + * On a device a pan's worklets run on the UI thread, and `runOnJS(fn)(...)` does + * not call `fn`: it puts the call in line on the JS thread, behind the work + * already waiting there, such as the list's scroll events. Under Jest both + * threads are one and `runOnJS` calls `fn` at once, so that wait never happens. + * + * This is Reanimated with a `runOnJS` that can wait. A suite opts in at the top + * of its file: + * + * ```ts + * jest.mock('react-native-reanimated', () => + * require('../../__fixtures__/jsThread').reanimatedWithJsThread() + * ); + * ``` + * + * Everything else is the real Reanimated, and `runOnJS` still calls `fn` at + * once outside `whileJsThreadIsBusy`. + */ +export const reanimatedWithJsThread = (): Reanimated => { + const actual = jest.requireActual('react-native-reanimated'); + const runOnJS = ((fn: Parameters[0]) => { + const call = actual.runOnJS(fn) as (...args: unknown[]) => void; + return (...args: unknown[]) => { + if (waitingCalls) { + waitingCalls.push(() => call(...args)); + } else { + call(...args); + } + }; + }) as Reanimated['runOnJS']; + return { ...actual, runOnJS, __esModule: true } as Reanimated; +}; + +/** + * Runs `work` while the JS thread is busy: the calls worklets make with + * `runOnJS` meanwhile wait in line, so what `work` itself does on the JS thread + * (calling a handle, as an app does from a list event that was already in + * line) runs before them. Then the JS thread catches up and runs them in + * order. Needs `reanimatedWithJsThread`. + */ +export const whileJsThreadIsBusy = (work: () => void) => { + const calls: (() => void)[] = []; + waitingCalls = calls; + try { + work(); + } finally { + waitingCalls = null; + } + act(() => calls.forEach((call) => call())); +};