From 333527302888b19187d4728a6cb41f1070e8461e Mon Sep 17 00:00:00 2001 From: Gabriel Parelli Francischini Date: Tue, 10 Nov 2026 15:59:43 -0300 Subject: [PATCH 1/2] perf(dots): stop reading shared values from JS and crossing to JS on every drag frame The bar's onSectionChange handle, which apps reach from onViewableIndexChanged, read two shared values on the JS thread. On Reanimated 3 such a read takes the UI runtime's lock, so the JS thread waited while the UI thread ran worklets. The handle now sends the section to the UI thread with runOnUI, and the reads happen there. The pan called runOnJS on every frame the finger moved. Each call went through onSectionChange, which restarts the onScrollToIndex debounce, re-locks the bar's visibility, and calls show() on the section list (state updates, an animated scrollToIndex, the retry and hide timers). The pan now finds the section in the worklet and only crosses to JS when it changes, plus once when a touch begins and once on lift. Visible change: while the finger moves within one section, the debounce is no longer restarted, so the list scrolls to that section a second after the finger reached its dot, as it already did for a finger that rests on it. Co-Authored-By: Claude Opus 5.5 --- docs/backlog.md | 40 ---------- .../FastScrollSectionDotsBar.tsx | 78 ++++++++++++++----- .../__tests__/FastScrollSectionDots.test.tsx | 29 +++++++ src/FastScrollSectionDots/utils.ts | 16 +++- 4 files changed, 103 insertions(+), 60 deletions(-) diff --git a/docs/backlog.md b/docs/backlog.md index d1ded7f..97b0aeb 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -65,46 +65,6 @@ list; the other four worked. Check it again before treating it as a bug. None of these grows memory over time: they cost CPU and short-lived garbage. -### The dots bar reads shared values synchronously on viewability changes - -[FastScrollSectionDotsBar.tsx:266-271](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L266-L271): -the bar's `onSectionChange` handle, reached from `onViewableIndexChanged`, reads -`enableExternalScrollEvents.value` and `containerScrollY.value` on the JS -thread. On Reanimated 3 (native), reading `.value` from JS goes through -`executeOnUIRuntimeSync` (`react-native-reanimated` `src/mutables.ts`), which -takes the UI runtime's lock and runs the read on the JS thread: the JS thread -waits while the UI thread runs worklets. On the example's IndicatorCost screen, -two such reads during a scroll took 0.44-0.79 ms at the median and 12-17 ms at -p95 (Android emulator, production bundle). On Reanimated 2.12, which this repo -develops against, the read is cheap, so tests do not show it. - -It runs on viewability changes, not on every frame, so it costs far less than -the same reads did in `FastScrollIndicator`, which now keeps JS copies (the -track height from `onLayout`, a finger-on-track flag set with `runOnJS` from -the pan's `onBegin` / `onFinalize`). The same approach applies here. - -### Dragging the dots does work on every frame, even without a section change - -[FastScrollSectionDotsBar.tsx:189-201](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L189-L201): -every pan update calls `runOnJS(onThumbPositionChange)`. On the JS thread that -maps and searches the sections, then calls `onSectionChange` -([FastScrollSectionDots.tsx:195-206](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L195-L206)). -That call restarts the debounce, calls `lockScrollBarVisibility(true)`, and -calls `show()` -([FastScrollSectionFullList.tsx:103-124](../src/FastScrollSectionDots/FastScrollSectionFullList.tsx#L103-L124)), -which: - -- starts an animated `scrollToIndex` on the section list; -- resets the 1 s rescroll timer and the 3 s hide timer. - -That is about four `clearTimeout` / `setTimeout` pairs and a restarted scroll -animation per frame, even while the finger stays on one section. - -Possible fix: find the section in the worklet (`findSectionOnPosition` already -is one), keep the last `sectionIndex` in a shared value, and only cross to JS -when it changes. The finger already holds the list open from `onBegin` to -`onFinalize`, so `show()` would not need to touch its hide timer at all. - ### Both components restart the hide timer on every scroll frame Apps call `onScrollToOffsetPercentage` on every `onScroll` frame, on both diff --git a/src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx b/src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx index fb3a075..463b83b 100644 --- a/src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx +++ b/src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx @@ -5,6 +5,7 @@ import { StyleSheet, ColorValue, View } from 'react-native'; import Animated, { runOnJS, + runOnUI, useAnimatedStyle, useDerivedValue, useSharedValue, @@ -12,7 +13,11 @@ import Animated, { } from 'react-native-reanimated'; import { springConfig, useComponentSize } from '../utils'; import { Gesture, GestureDetector } from 'react-native-gesture-handler'; -import { calculateYPosition, findSectionOnPosition } from './utils'; +import { + calculateYPosition, + findSectionOnPosition, + thumbYOnDot, +} from './utils'; import { snapPoint } from 'react-native-redash'; import type { SectionDataWithDimensions } from '../types'; @@ -81,13 +86,6 @@ export type Props = { initialSectionIndex?: number; }; -/** Where the thumb sits when it rests on the dot of `sectionIndex`: its middle. */ -const thumbYOnDot = ( - sectionIndex: number, - dotSize: number, - dotMargin: number -) => dotMargin * (sectionIndex + 1) + dotSize * sectionIndex + dotSize / 2; - export type FastScrollSectionDotsBarHandle = { /** * Call this method when viewable indicies changes @@ -242,6 +240,12 @@ const FastScrollSectionDotsBar = React.forwardRef( dotPositionsValue.value = dotPositions; }, [dotPositions, dotPositionsValue]); + // The section the finger last reported, reset when a touch begins. The pan + // updates on every frame the finger moves, but JS only needs to hear about + // a new section: each onSectionChange restarts the debounce of + // onScrollToIndex and the section list's timers, and scrolls that list. + const draggedSectionIndex = useSharedValue(-1); + const pan = useMemo(() => { /** The thumb follows the finger while it is down. */ const followFinger = (y: number) => { @@ -255,7 +259,14 @@ const FastScrollSectionDotsBar = React.forwardRef( pointStylePositionY.value = yPosition; containerYOnPointStylePositionY.value = containerScrollY.value; - runOnJS(onThumbPositionChange)(pointStylePositionY.value); + const section = findSectionOnPosition( + yPosition, + dotPositionsValue.value + ); + if (section && section.sectionIndex !== draggedSectionIndex.value) { + draggedSectionIndex.value = section.sectionIndex; + runOnJS(onThumbPositionChange)(yPosition); + } }; return ( @@ -268,6 +279,9 @@ const FastScrollSectionDotsBar = React.forwardRef( enableExternalScrollEvents.value = false; scale.value = thumbScaleOnPress; runOnJS(fingerDown)(); + // A new touch always reports its section, even the one the last + // drag ended on: it opens the section list again. + draggedSectionIndex.value = -1; followFinger(event.y); }) // The finger has moved far enough to activate the pan, then moves on @@ -290,6 +304,9 @@ const FastScrollSectionDotsBar = React.forwardRef( containerYOnPointStylePositionY.value = containerScrollY.value; scale.value = 1; + // Always reported, even when the section did not change: the + // list scrolls to the section the thumb snaps to once the + // debounce settles after the lift. runOnJS(onThumbPositionChange)(pointStylePositionY.value); runOnJS(fingerUp)(); }) @@ -300,6 +317,7 @@ const FastScrollSectionDotsBar = React.forwardRef( dotMargin, dotPositionsValue, dotSize, + draggedSectionIndex, enableExternalScrollEvents, fingerDown, fingerUp, @@ -321,20 +339,44 @@ const FastScrollSectionDotsBar = React.forwardRef( }; }); + // Apps call the handle from JS on every viewability change. 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. The handle only sends the section + // to the UI thread, which does the reads there. + const followListOnUI = useMemo( + () => + runOnUI((sectionIndex: number) => { + 'worklet'; + // A finger on the dots leads: the list's reports trail behind it. + if (!enableExternalScrollEvents.value) { + return; + } + pointStylePositionY.value = thumbYOnDot( + sectionIndex, + dotSize, + dotMargin + ); + containerYOnPointStylePositionY.value = containerScrollY.value; + }), + [ + containerScrollY, + containerYOnPointStylePositionY, + dotMargin, + dotSize, + enableExternalScrollEvents, + pointStylePositionY, + ] + ); + React.useImperativeHandle( forwardedRef, (): FastScrollSectionDotsBarHandle => ({ onSectionChange: (section: SectionFullData) => { - if (enableExternalScrollEvents.value) { - pointStylePositionY.value = thumbYOnDot( - section.sectionIndex, - dotSize, - dotMargin - ); - containerYOnPointStylePositionY.value = containerScrollY.value; - } + followListOnUI(section.sectionIndex); }, - }) + }), + [followListOnUI] ); const styles = useMemo( diff --git a/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx b/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx index 803eac7..9e98e9d 100644 --- a/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx +++ b/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx @@ -445,6 +445,35 @@ describe('FastScrollSectionDots', () => { expect(onScrollToIndex.mock.calls).toEqual([[9]]); }); + it('scrolls the list to the dragged section a second after the finger reaches its dot, even while the finger keeps moving over it', () => { + const { onScrollToIndex } = renderDots({ + hideFastScrollIndicatorTimeout: 0, + }); + const finger = touchDown(FINGER_ON.fruits); + finger.moveTo(FINGER_ON.vegetables); + act(() => jest.advanceTimersByTime(600)); + + // A few pixels further down, still nearest to Vegetables' dot. + finger.moveTo(FINGER_ON.vegetables + 3); + act(() => jest.advanceTimersByTime(399)); + expect(onScrollToIndex).not.toHaveBeenCalled(); + + act(() => jest.advanceTimersByTime(1)); + expect(onScrollToIndex.mock.calls).toEqual([[5]]); + }); + + it('opens the section list again when a new touch lands on the dot the last drag ended on', () => { + renderDots({ hideFastScrollIndicatorTimeout: 0 }); + drag([FINGER_ON.fruits, FINGER_ON.vegetables]); + // The section list closes 3 s after the finger lifts. + act(() => jest.advanceTimersByTime(3000)); + expect(screen.queryByText('Vegetables')).not.toBeOnTheScreen(); + + touchDown(FINGER_ON.vegetables); + + expect(screen.getByText('Vegetables')).toBeOnTheScreen(); + }); + // Apps rebuild onScrollToIndex when what it reads changes, e.g. the height of // a header drawn over the list that it passes as viewOffset. it('scrolls with the onScrollToIndex of the latest render once the drag settles', () => { diff --git a/src/FastScrollSectionDots/utils.ts b/src/FastScrollSectionDots/utils.ts index a3cc44f..9aef3f6 100644 --- a/src/FastScrollSectionDots/utils.ts +++ b/src/FastScrollSectionDots/utils.ts @@ -26,9 +26,21 @@ export const calculateYPosition = ({ }; }; -export const findSectionOnPosition = ( +/** Where the thumb sits when it rests on the dot of `sectionIndex`: its middle. */ +export const thumbYOnDot = ( + sectionIndex: number, + dotSize: number, + dotMargin: number +) => { + 'worklet'; + return dotMargin * (sectionIndex + 1) + dotSize * sectionIndex + dotSize / 2; +}; + +export const findSectionOnPosition = < + T extends Pick +>( positionY: number, - sections: SectionDataWithDimensions[] + sections: T[] ) => { 'worklet'; const snapPoints = sections.map((section) => section.y); From 70a398959db7cfa5284c5ccbf568fe5d15690760 Mon Sep 17 00:00:00 2001 From: Gabriel Parelli Francischini Date: Tue, 10 Nov 2026 18:07:08 -0300 Subject: [PATCH 2/2] fix(dots): center the section list on the touched section once it opens The touch that opens the section list reports its section before the list is mounted, so show() could not scroll it. Before the dots stopped reporting every frame, the next frame's report scrolled it; now the next report only comes on another dot or on lift, so a finger that stays on a low dot left the list at its top, with the active row out of view. The list now centers the active section when it lays out, with the same retry a second later that show() uses. Co-Authored-By: Claude Opus 5.5 --- .../FastScrollSectionFullList.tsx | 59 ++++++++++++------- .../__tests__/FastScrollSectionDots.test.tsx | 15 +++++ 2 files changed, 54 insertions(+), 20 deletions(-) diff --git a/src/FastScrollSectionDots/FastScrollSectionFullList.tsx b/src/FastScrollSectionDots/FastScrollSectionFullList.tsx index 4a775bd..6852963 100644 --- a/src/FastScrollSectionDots/FastScrollSectionFullList.tsx +++ b/src/FastScrollSectionDots/FastScrollSectionFullList.tsx @@ -98,8 +98,8 @@ const FastScrollSectionFullList = React.forwardRef( ); // The list closes a while after the last show() or scroll. show() only - // runs while the finger moves on the dots, so a finger resting on them - // holds the list open instead. + // runs when the finger touches, reaches another dot or lifts, so a finger + // on the dots holds the list open instead. const held = useRef(false); const startShowActiveIndexVisibleTimer = useCallback(() => { startHideTimer(); @@ -128,31 +128,49 @@ const FastScrollSectionFullList = React.forwardRef( [] ); + // Read when the list lays out, which can be before the state update that + // set the active section has rendered. + const activeSectionRef = useRef(null); + + /** + * Centers the active section's row, then again a second later: rows the + * list had not measured yet cannot be scrolled to on the first attempt. + */ + const centerActiveSection = useCallback(() => { + const section = activeSectionRef.current; + if (!flatListRef.current || !section) { + return; + } + flatListRef.current.scrollToIndex({ + index: section.sectionIndex, + viewPosition: 0.5, + }); + if (rescrollTimeout.current) { + clearTimeout(rescrollTimeout.current); + rescrollTimeout.current = null; + } + rescrollTimeout.current = setTimeout(() => { + if (flatListRef.current) { + flatListRef.current.scrollToIndex({ + index: section.sectionIndex, + viewPosition: 0.5, + }); + } + }, 1000); + }, []); + React.useImperativeHandle( forwardedRef, (): FastScrollSectionFullListHandle => ({ show(section: SectionFullData) { setActiveIndexVisible(true); setActiveSection(section); + activeSectionRef.current = section; startShowActiveIndexVisibleTimer(); - if (flatListRef.current) { - flatListRef.current.scrollToIndex({ - index: section.sectionIndex, - viewPosition: 0.5, - }); - if (rescrollTimeout.current) { - clearTimeout(rescrollTimeout.current); - rescrollTimeout.current = null; - } - rescrollTimeout.current = setTimeout(() => { - if (flatListRef.current) { - flatListRef.current.scrollToIndex({ - index: section.sectionIndex, - viewPosition: 0.5, - }); - } - }, 1000); - } + // When show() opens the list, it is not mounted yet: it centers the + // section once it lays out (onLayout below). The dots only call + // show() again when the finger reaches another dot. + centerActiveSection(); }, hold(isHeld: boolean) { held.current = isHeld; @@ -191,6 +209,7 @@ const FastScrollSectionFullList = React.forwardRef( ref={setFlatListRef} style={styles.list} contentContainerStyle={styles.listContainer} + onLayout={centerActiveSection} onScrollToIndexFailed={() => { // just ignore to avoid errors/crashes }} diff --git a/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx b/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx index 9e98e9d..9de5914 100644 --- a/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx +++ b/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx @@ -761,6 +761,21 @@ describe('FastScrollSectionDots', () => { expect(isAnythingShown()).toBe(false); }); + // The touch opens the list, so it is not there yet to scroll when the touch + // reports its section, and the finger only reports again on another dot. + it('centers the section a touch opens the section list on, while the finger stays on its dot', () => { + renderDots({ hideFastScrollIndicatorTimeout: 0 }); + const finger = touchDown(FINGER_ON.dairy); + layoutSectionList({ visibleHeight: 40, rowHeight: 30 }); + const scrollTo: jest.Mock = getSectionListScrollView().instance.scrollTo; + + finger.moveTo(FINGER_ON.dairy + 2); + act(() => jest.advanceTimersByTime(1000)); + + // Dairy's row spans 60..90; centered in a 40px list, the list shows 55..95. + expect(scrollTo.mock.calls).toEqual([[{ y: 55 }]]); + }); + it('scrolls the open section list to center the section under the finger, and again a second later', () => { renderDots({ hideFastScrollIndicatorTimeout: 0 }); drag([FINGER_ON.fruits]);