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
40 changes: 0 additions & 40 deletions docs/backlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
78 changes: 60 additions & 18 deletions src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,19 @@ import { StyleSheet, ColorValue, View } from 'react-native';

import Animated, {
runOnJS,
runOnUI,
useAnimatedStyle,
useDerivedValue,
useSharedValue,
withSpring,
} 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';

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) => {
Expand All @@ -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);
Comment on lines +266 to +268

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and fixed in 70a3989 as suggested: the dots still report only on a new section, and FastScrollSectionFullList centers the active section when the list lays out (onLayout), with the same retry a second later that show() uses.

The touch that opens the list reports its section before the list is mounted, so that show() cannot scroll it. Before this PR the next frame's report did; with the deduplication the next report only comes on another dot or on lift.

Unit test. centers the section a touch opens the section list on, while the finger stays on its dot: list closed, finger touches Dairy, the list lays out, the finger moves 2 px without leaving Dairy's dot.

Code Result
this PR before 70a3989 fails: scrollTo is never called
this PR at 70a3989 passes: the list centers Dairy (scrollTo({ y: 55 }))

yarn test (104 passed, 1 todo), yarn typecheck and yarn lint pass.

On device. Android emulator (API 36), Expo Go for SDK 52, dev bundle, Categories screen. The same scripted gesture on both builds: scroll the list a little so the dots show, touch the dot of Necklaces / Silver Gold (low on the bar, far down the section list) with the section list closed, zigzag sideways over that dot for 3.6 s (1.5% of the screen wide, so it never leaves the dot), lift. Times from the touch down, read from the recordings at 5 fps:

Build Section list opens Section list centers Necklaces / Silver Gold Finger lifts
before 70a3989 +0.2 s, at its top +4.4 s, after the lift +3.7 s
at 70a3989 +0.2 s, at its top +1.2 s, with the finger still down +3.7 s

At 70a3989 the first scroll, on layout, hits a row the list has not measured yet, and the retry a second later centers it. That is the same timing show() had when the list was already open.

Before 70a3989 At 70a3989
The section list stays on Bracelets / Earrings while the finger is on the dot, and scrolls to Necklaces / Silver Gold after the lift. The section list scrolls to Necklaces / Silver Gold, highlighted, while the finger is still on the dot.

Frames at +0.6, +1.4, +2.4, +3.4 and +4.6 s after the touch down (top: before, bottom: after). The grey circle at the bottom of the dots is the finger:

Full resolution: before.mp4, after.mp4.

}
};

return (
Expand All @@ -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
Expand All @@ -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)();
})
Expand All @@ -300,6 +317,7 @@ const FastScrollSectionDotsBar = React.forwardRef(
dotMargin,
dotPositionsValue,
dotSize,
draggedSectionIndex,
enableExternalScrollEvents,
fingerDown,
fingerUp,
Expand All @@ -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(
Expand Down
59 changes: 39 additions & 20 deletions src/FastScrollSectionDots/FastScrollSectionFullList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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<SectionFullData | null>(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;
Expand Down Expand Up @@ -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
}}
Expand Down
44 changes: 44 additions & 0 deletions src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -732,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]);
Expand Down
16 changes: 14 additions & 2 deletions src/FastScrollSectionDots/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<SectionDataWithDimensions, 'y'>
>(
positionY: number,
sections: SectionDataWithDimensions[]
sections: T[]
) => {
'worklet';
const snapPoints = sections.map((section) => section.y);
Expand Down
Loading