From 6bbc1b2368914aeb75422518b8223eadd03b6f58 Mon Sep 17 00:00:00 2001 From: Gabriel Parelli Francischini Date: Wed, 11 Nov 2026 11:43:43 -0300 Subject: [PATCH 1/2] docs: list the findings of the 0.3.4..main review and fix stale docs - backlog: the next release's checklist, five bugs, a cleanup list and a proposal found reviewing main since 0.3.4; line numbers moved to c56ff00 and a resolved item dropped. - CLAUDE.md: the list wrapper never calls the indicator's handle, the app does not clamp the offset, and handles avoid JS reads of shared values. - README: the install command, the peer dependencies, and an indicator example that works with FlashList v2. - CONTRIBUTING: yarn bootstrap, the Expo Go example, and no git hooks. - unit-testing: yarn typecheck runs twice. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 18 ++- CONTRIBUTING.md | 15 ++- README.md | 62 +++++++---- docs/backlog.md | 257 +++++++++++++++++++++++++++++++++++++------ docs/unit-testing.md | 9 +- 5 files changed, 290 insertions(+), 71 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 58228fd..3844289 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,13 +28,19 @@ grouped by category, with both components layered over it: default). `scrollToOffsetPercentage` maps 0..1 to FlashList `scrollToOffset` over the scrollable height (content height minus viewport height). - **Handle calls.** Every `onScroll` frame calls `onScrollToOffsetPercentage` on - both components, so that path has to stay cheap. `onViewableIndexChanged` is - called with the first viewable index, debounced 500 ms by the app. + both components, so that path has to stay cheap. The value is not clamped: + the app divides the offset by the scrollable height, floored at 1 px, so an + iOS bounce reports values below 0 and above 1, and far outside that range on + a list shorter than its viewport. `onViewableIndexChanged` is called with the + first viewable index, debounced 500 ms by the app. - Both use `hideFastScrollIndicatorTimeout` 2000. Sections can be collapsed, which keeps header indices stable but hides the rows between them. **Generic list wrapper** - a shared FlashList wrapper renders a right-side -`FastScrollIndicator` over every list in the app, wired the same way. +`FastScrollIndicator` over every list in the app but never calls its handle, +so the thumb never shows there. The wrapper keeps the scroll offset in state +and passes an inline `scrollToOffsetPercentage`, so the indicator re-renders +on every scroll frame of every list: its render has to stay cheap. **Sectioned list with a tab bar** - one screen of the app puts a `FastScrollSectionTab` above a FlashList of rows grouped by category, with a @@ -114,7 +120,11 @@ only fits one side's typings fails there. full-list item taps scroll to `startIndex`. - **Imperative handles are the integration point.** Apps call `onViewableIndexChanged` / `onScrollToOffsetPercentage` on a ref from their - list's callbacks. Treat handle names and signatures as public API. + 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`). - **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/CONTRIBUTING.md b/CONTRIBUTING.md index 43c933c..3901832 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,15 +6,15 @@ We want this community to be friendly and respectful to each other. Please follo ## Development workflow -To get started with the project, run `yarn` in the root directory to install the required dependencies for each package: +To get started with the project, use the Node version in `.nvmrc` and run `yarn bootstrap` in the root directory. It installs the dependencies of the example app, then those of the library. `yarn typecheck` needs both. ```sh -yarn +yarn bootstrap ``` > While it's possible to use [`npm`](https://github.com/npm/cli), the tooling is built around [`yarn`](https://classic.yarnpkg.com/), so you'll have an easier time if you use `yarn` for development. -While developing, you can run the [example app](/example/) to test your changes. Any changes you make in your library's JavaScript code will be reflected in the example app without a rebuild. If you change any native code, then you'll need to rebuild the example app. +While developing, you can run the [example app](/example/) to test your changes. It runs in Expo Go (SDK 52) and uses the library's source directly, so any change you make in the library shows up without a rebuild. The library has no native code. To start the packager: @@ -71,15 +71,15 @@ We follow the [conventional commits specification](https://www.conventionalcommi - `test`: adding or updating tests, e.g. add integration tests using detox. - `chore`: tooling changes, e.g. change CI config. -Our pre-commit hooks verify that your commit message matches this format when committing. +No git hook checks the format: the hooks in `lefthook.yml` are disabled. ### Linting and tests [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) -We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing. +We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing. [docs/unit-testing.md](docs/unit-testing.md) has the rules for writing tests. -Our pre-commit hooks verify that the linter and tests pass when committing. +CI runs the linter, the type check, the tests and the build on every pull request. No git hook runs them when committing, so run them before you push. ### Publishing to npm @@ -95,7 +95,7 @@ yarn release The `package.json` file contains various scripts for common tasks: -- `yarn bootstrap`: setup project by installing all dependencies and pods. +- `yarn bootstrap`: setup project by installing the dependencies of the example app and of the library. - `yarn typecheck`: type-check files with TypeScript. - `yarn lint`: lint files with ESLint. - `yarn test`: run unit tests with Jest. @@ -112,5 +112,4 @@ When you're sending a pull request: - Prefer small pull requests focused on one change. - Verify that linters and tests are passing. - Review the documentation to make sure it looks good. -- Follow the pull request template when opening a pull request. - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. diff --git a/README.md b/README.md index a072bf3..f6e3729 100644 --- a/README.md +++ b/README.md @@ -7,53 +7,69 @@ Fast Scroll implementation over Flashlist for react native ## Installation ```sh -yarn install react-native-fast-scroll +yarn add react-native-fast-scroll ``` ## Requirements -1. React Native Gesture Handler -2. React Native Reanimated >= 2 +The package's peer dependencies: + +1. `react-native-gesture-handler` >= 2.8 +2. `react-native-reanimated` >= 2.12 +3. `react-native-redash` +4. `@shopify/flash-list` ## Usage of the FastScroll Indicator +The indicator works with offsets from 0 (the top of the list) to 1 (its end), +over the height the list can scroll: its content minus its own height. + ```js import { FastScrollIndicator } from 'react-native-fast-scroll'; // ... +const contentHeight = useRef(0); +const listHeight = useRef(0); +const scrollableHeight = () => + Math.max(0, contentHeight.current - listHeight.current); + +// The thumb was dragged: scroll the list. const scrollToOffsetPercentage = (offsetPercentage: number) => { - const flashListHeight = - flashListRef.current?.recyclerlistview_unsafe?.getContentDimension() - .height ?? 1; - const offset = offsetPercentage * flashListHeight; - flashListRef.current?.scrollToOffset({ - offset, - }); -} + flashListRef.current?.scrollToOffset({ + offset: offsetPercentage * scrollableHeight(), + animated: false, + }); +}; +// The list scrolled: move the thumb. const onScroll = (event: NativeSyntheticEvent) => { - const flashListHeight = - flashListRef.current?.recyclerlistview_unsafe?.getContentDimension() - .height ?? 1; + const scrollable = scrollableHeight(); const offsetPercentage = - event.nativeEvent.contentOffset.y / flashListHeight; + scrollable > 0 ? event.nativeEvent.contentOffset.y / scrollable : 0; fastScrollIndicatorRef.current?.onScrollToOffsetPercentage( offsetPercentage ); fastScrollSectionDotsRef.current?.onScrollToOffsetPercentage( offsetPercentage ); -} - +}; + + (contentHeight.current = height)} + onLayout={(event) => (listHeight.current = event.nativeEvent.layout.height)} + // ... +/> ``` diff --git a/docs/backlog.md b/docs/backlog.md index dbf1b19..15b2399 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -2,26 +2,162 @@ Known issues found by reading the code, not yet fixed. None has a failing test yet; write one first when picking an item up (see -[unit-testing.md](unit-testing.md)). Line numbers are as of commit `4f89236`. +[unit-testing.md](unit-testing.md)). Line numbers are as of commit `c56ff00`. ## Before the next release -### Release the fixes made since 0.3.3 +### Release the fixes made since 0.3.4 -npm has 0.3.3, which predates the fixes for the stale `onScrollToIndex` after a -drag on the dots, the drag area of the dots bar, the tab bar re-renders, the -section label types, and the pan gestures that kept every render of the app's -screen in memory (rebuilt on each render, they handed Reanimated new JS -functions to hold from native code). The production app still runs a patched 0.3.2. When it -upgrades it should drop the whole patch (see `CLAUDE.md`). +npm has 0.3.4. On top of it, `main` has these changes: -Before that release, check on a device that the active tab of -`FastScrollSectionTab` still follows the list as it scrolls: production uses the -tab bar display only, driven by `onViewableIndexChanged`, and the tab bar -re-render change touches that path. +- The section list centers on the touched section when it opens, and stays + open while a finger rests on the dots. +- 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. +- 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. +- The section list's rows no longer log a Gesture Handler error on the New + Architecture. + +The production app still runs a patched 0.3.2. When it upgrades it should drop +the whole patch (see `CLAUDE.md`). + +Before that release: + +- Fix "The section list can center a section that no longer exists" below: it + can throw. It is rare, but the fix is a bounds check and clearing one ref. +- 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. +- 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 + device that the active tab of `FastScrollSectionTab` still follows the list + as it scrolls. Production uses the tab bar display only, driven by + `onViewableIndexChanged`, and the tab bar re-render change in 0.3.4 touches + that path. ## Bugs +### The section list can center a section that no longer exists + +The section list can scroll to a `sectionIndex` it kept from before the app +passed new sections. When that index is past the new last row, `scrollToIndex` +throws `scrollToIndex out of range` from a timer or an event handler. The +throw is an `invariant`, which also throws in release builds, and no error +boundary catches it there, so it is a fatal JS error. When the index is still +in range, the list scrolls by itself to the row that now has it. + +It takes the app passing fewer sections while the section list is open, and +there are two ways in: + +- **The retry a second after `show()`** + ([FastScrollSectionFullList.tsx:232-236](../src/FastScrollSectionDots/FastScrollSectionFullList.tsx#L232-L236)) + keeps the section it was scheduled with, so the sections have to change + within that second. 0.3.2 and 0.3.4 have this one too. +- **The pending section**, new since 0.3.4, open for as long as the list stays + open (3 s after the lift). + - `sectionToCenter` is cleared only when `centerPendingSection` + ([lines 169-181](../src/FastScrollSectionDots/FastScrollSectionFullList.tsx#L169-L181)) + centers its row, which it tries on each content size change. Neither the + 1 s retry nor closing the list clears it. + - A `FlatList` without `getItemLayout` sizes its tail spacer only up to the + rows it has measured. So its content size changes once per batch of rows it + renders, up to 10 rows a batch, and the batch that ends the list causes the + last change. + - The New Architecture emits a view's layout event before its children's + (`YogaLayoutableShadowNode::layout`), so the list reports each batch's size + before those rows are measured. When the touched row is in the batch that + ends the list, and that batch is not the first, its centering misses on the + last change and the section stays pending. + - The next content size change, which new sections cause, then centers the + old index. + +Reproduced under Jest in a throwaway test, with the events fired in that order: +30 sections, a quick tap on the dot of section 25, then 25 sections, and +`scrollToIndex` throws. A tap on section 15, in a middle batch, ends clean. The +event order was read in React Native's source, not observed on a device. + +An app that unmounts the dots while its data reloads, for example behind a +loading view, takes neither path: the dots start over with the new sections. + +Possible fix: clear `sectionToCenter` in the 1 s retry and when the list +closes, and skip a `sectionIndex` that is not below `sections.length` in +`centerSection`. "Center the section list without a virtualized list" under +Proposals removes the pending state altogether. + +### 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): +offsets outside 0..1 used to return early. Now they are clamped, which was the +point (the thumb used to stop short of the end on a bounce), but they also call +`showFastScrollBar()`. On iOS: + +- The bar shows while a list is pulled past its top, as in a pull-to-refresh. +- On a list shorter than its viewport, an app that floors the scrollable height + at 1 px, as the production app does, reports a pull upwards as offsets far + above 1. The thumb goes to the end of the track of a list that cannot scroll. + +Android reports no offsets past the ends. `NaN` (0 / 0) still reaches +`translateY`, as before. + +Possible fix: clamp the thumb, but show the bar only for offsets inside 0..1, +and drop `NaN`. + +### The open section list jumps instead of gliding while the finger crosses dots + +[FastScrollSectionFullList.tsx:221-226](../src/FastScrollSectionDots/FastScrollSectionFullList.tsx#L221-L226): +every `show()` centers through `centerPendingSection`, which scrolls with +`animated: false`. The touch that opens the list needs that: on Android, an +animated scroll started while the list lays out its rows does not move it. But +it also applies while the finger drags across dots with the list open and laid +out, where the list used to glide from row to row. The suite asserts the jump +(`scrolls the open section list to center the section under the finger, and +again a second later`). How it looks is not confirmed on a device. + +Possible fix: animate when the list was already open and the row is laid out, +and keep the jump for the opening touch. + +### The dots' thumb can sit below the last dot when the sections change while the bar shows + +[FastScrollSectionDotsBar.tsx:115-119](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L115-L119): +`initialSectionIndex` only places the thumb when the bar mounts. When the app +passes fewer sections while the bar is visible, the thumb stays at its old y, +below the shorter strip, until the next `onViewableIndexChanged`. 0.3.4 behaves +the same; the fix for sections replaced while the bar is hidden does not cover +it. + +Possible fix: when the sections change, move the thumb to the dot of the list +index the dots remember. + ### Sections built from `stickyHeaderIndices` all read "1" [utils.ts:232](../src/utils.ts#L232): `createFullSectionData` gives each section @@ -52,11 +188,11 @@ Apps call `onScrollToOffsetPercentage` on every `onScroll` frame, on both components: - `FastScrollIndicator` - ([line 258](../src/FastScrollIndicator/FastScrollIndicator.tsx#L258)) runs + ([line 287](../src/FastScrollIndicator/FastScrollIndicator.tsx#L287)) runs `showFastScrollBar()`, which calls `setVisible(true)` and clears and sets a `setTimeout`. - `useHideFlatBar`, used by the dots - ([utils.ts:116-125](../src/utils.ts#L116-L125)), skips the `setVisible` and + ([utils.ts:110-119](../src/utils.ts#L110-L119)), skips the `setVisible` and the spring when the bar is already visible, but still calls `scheduleHideFastScrollbar()` first, so it also clears and sets a timer every frame. @@ -64,60 +200,115 @@ components: Possible fix for both: one timer with a deadline. Each scroll only sets `hideAt = now + timeout`. When the timer fires before `hideAt`, it re-arms for the remaining time. The same applies to the section list's `onScroll` -([FastScrollSectionFullList.tsx:158-160](../src/FastScrollSectionDots/FastScrollSectionFullList.tsx#L158-L160)). +([FastScrollSectionFullList.tsx:278-280](../src/FastScrollSectionDots/FastScrollSectionFullList.tsx#L278-L280)). ### The dots bar remounts every time it shows -[FastScrollSectionDots.tsx:230](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L230): +[FastScrollSectionDots.tsx:257](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L257): each show mounts the bar again: the `GestureDetector`, its worklets, one view per dot, and a `measure` call. Meanwhile `useHideFlatBar` springs -`translateFastScrollBarX` ([utils.ts:82](../src/utils.ts#L82)) on every show and +`translateFastScrollBarX` ([utils.ts:76](../src/utils.ts#L76)) on every show and hide, but nothing reads it. Possible fix: keep the bar mounted and slide it with `translateFastScrollBarX` (or drop that shared value). The thumb no longer depends on it: the dots keep the last active section and the bar starts on it when it mounts. -### Unstable props rebuild the gestures +### Unstable props rebuild styles and gestures -- The indicator's `pan` depends on `scrollToOffsetPercentage` - ([FastScrollIndicator.tsx:154-221](../src/FastScrollIndicator/FastScrollIndicator.tsx#L154-L221)). - A production list wrapper passes an inline function and re-renders on every - scroll frame, so the `React.memo` is defeated and the Pan gesture, with its - worklets, is rebuilt and sent to the UI runtime on every frame. Read the - callback through a ref, as the dots already do for `onScrollToIndex`. - The default `thumbSize` is an object literal in the parameter list ([FastScrollIndicator.tsx:95-99](../src/FastScrollIndicator/FastScrollIndicator.tsx#L95-L99)), - so `styles` ([line 281](../src/FastScrollIndicator/FastScrollIndicator.tsx#L281)) - and `pointStyle` are rebuilt on every render. Hoist the default to a constant - and depend on `width` / `height` / `borderRadius`. + so `styles` ([line 292](../src/FastScrollIndicator/FastScrollIndicator.tsx#L292)) + and `pointStyle` ([line 255](../src/FastScrollIndicator/FastScrollIndicator.tsx#L255)) + are rebuilt on every render. A production list wrapper re-renders on every + scroll frame and passes a new `scrollToOffsetPercentage` each time, which + defeats the `React.memo`, so there they are rebuilt on every frame. Hoist the + default to a constant and depend on `width` / `height` / `borderRadius`. - `onScrollToIndex` of the dots reaches `FastScrollSectionFullList` through `fastScrollFullListOnScrollToIndex` - ([FastScrollSectionDots.tsx:208-219](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L208-L219)), + ([FastScrollSectionDots.tsx:229-240](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L229-L240)), so a new callback re-renders every row and rebuilds its `Gesture.Tap()`. ### Small ones - The indicator's `pointStyle` - ([FastScrollIndicator.tsx:223-237](../src/FastScrollIndicator/FastScrollIndicator.tsx#L223-L237)) + ([FastScrollIndicator.tsx:255-269](../src/FastScrollIndicator/FastScrollIndicator.tsx#L255-L269)) starts two new `withSpring` (translateX, scale) on every `translateY` change, that is every scroll frame, even when their target has not moved. Same for the scale in `FastScrollSectionDotsBar`'s `pointStyle`. -- `findNearestActiveSection` ([utils.ts:24-33](../src/utils.ts#L24-L33)) copies +- `findNearestActiveSection` ([utils.ts:20-29](../src/utils.ts#L20-L29)) copies and reverses the sections on every call. The tab bar calls it on every viewability change. Sections are sorted by `index`, so a reverse loop or a binary search needs no allocation. - `entering` / `exiting` animations are rebuilt on every render - ([FastScrollIndicator.tsx:284-290](../src/FastScrollIndicator/FastScrollIndicator.tsx#L284-L290), - [FastScrollSectionDots.tsx:156-162](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L156-L162)), + ([FastScrollIndicator.tsx:313-319](../src/FastScrollIndicator/FastScrollIndicator.tsx#L313-L319), + [FastScrollSectionDots.tsx:166-172](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L166-L172)), and `FastScrollSectionFullListItem` calls `StyleSheet.create` per row and `isActive`. Cheap, but they can be module constants. +## Cleanup + +- The dots' pan finds the section twice per section change: on the UI thread, + to report only a new section + ([FastScrollSectionDotsBar.tsx:262-269](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L262-L269)), + then again on JS from the y it sent + ([lines 225-230](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L225-L230)). + The two read different copies of the sections (the shared value is updated in + an effect), so they can disagree for a frame after the sections change. Send + `sectionIndex` through `runOnJS` and read `sectionsRef.current[sectionIndex]`. +- The `y` in the `sections` memo + ([line 127](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L127)) + and `newTranslate + dotSize / 2` in `onFinalize` + ([line 303](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L303)) + repeat the formula of `thumbYOnDot`. +- `leaves no hide timer running once it unmounts` + ([utils.test.ts:146-156](../src/__tests__/utils.test.ts#L146-L156)) asserts + `jest.getTimerCount()` and advances 16 ms to let a Reanimated frame pass. + [unit-testing.md](unit-testing.md) says a hook test never asserts on timer + handles; a timer count is close to that, and it ties the test to Reanimated's + own timers. `useTimer`'s `never times out once unmounted` asserts on the + callback instead, but `useHideFlatBar` has no callback to observe after it + unmounts. +- The example's `IndicatorCost` screen + ([IndicatorCost.tsx:81-107](../example/src/indicatorCost/IndicatorCost.tsx#L81-L107)) + maps the thumb to an offset over `ROWS.length * ROW_HEIGHT`, but the offset + back to the thumb over `contentSize - layoutMeasurement`. The thumb moves + under the finger on release and the end of the track maps past the end of the + list, on the screen meant to measure the indicator. It also never removes + `global.__indicatorCost` + ([lines 136-142](../example/src/indicatorCost/IndicatorCost.tsx#L136-L142)). +- Two documented defaults of public props disagree with the code. The dots' + `thumbColor` says `'rgba(255, 255, 255, 0.9)'` + ([FastScrollSectionDots.tsx:55](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L55)) + and is `0.8` + ([line 113](../src/FastScrollSectionDots/FastScrollSectionDots.tsx#L113)). + The indicator's `thumbSize` says `15` + ([FastScrollIndicator.tsx:39](../src/FastScrollIndicator/FastScrollIndicator.tsx#L39)) + and is `{ borderRadius: 7, height: 50, width: 7 }` + ([lines 95-99](../src/FastScrollIndicator/FastScrollIndicator.tsx#L95-L99)). + ## Proposals +### Center the section list without a virtualized list + +[FastScrollSectionFullList.tsx:132-216](../src/FastScrollSectionDots/FastScrollSectionFullList.tsx#L132-L216) +centers a row through four mechanisms: `onContentSizeChange`, a 50 ms poll +while no row is measured, a jump to an estimated offset, and a retry after 1 s. +`centerMiss` ties them together, and only works because `FlatList` calls +`onScrollToIndexFailed` synchronously inside `scrollToIndex`. All of it works +around virtualization, for a list of one short row per section, and "The +section list can center a section that no longer exists" above comes from the +state it keeps. + +A `ScrollView` that records each row's y from `onLayout` can center with one +exact `scrollTo` once the row is laid out. That drops `sectionToCenter`, +`centerMiss`, `centerRetryTimeout`, `listHeight` and `onScrollToIndexFailed`. +Every row then mounts when the list opens, so measure it with a few hundred +sections first. + ### Asymmetric hitSlop on the dots bar -[FastScrollSectionDotsBar.tsx:25](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L25) +[FastScrollSectionDotsBar.tsx:30](../src/FastScrollSectionDots/FastScrollSectionDotsBar.tsx#L30) uses `{ horizontal: 20 }`. The bar always sits on the left of a row with the section list to its right, whatever `side` is (`side` only picks the slide animation), so `side` is not what the hitSlop should depend on: diff --git a/docs/unit-testing.md b/docs/unit-testing.md index 35d2f66..b382c8d 100644 --- a/docs/unit-testing.md +++ b/docs/unit-testing.md @@ -134,9 +134,12 @@ for a required prop). Unlike many app repos, **test files are covered by both static gates here**: -- **`yarn typecheck`** (`tsc --noEmit`) uses the root `tsconfig.json`, which - only excludes `example/`, so every `*.test.ts(x)` is type-checked. Jest - globals (`describe`, `it`, `expect`, `jest`) are typed by `@types/jest`. +- **`yarn typecheck`** runs `tsc --noEmit` twice. The first pass uses the root + `tsconfig.json`, which only excludes `example/`, so every `*.test.ts(x)` is + type-checked, against the dev dependencies. Jest globals (`describe`, `it`, + `expect`, `jest`) are typed by `@types/jest`. The second pass (`-p example`) + checks the example app and the `src/` files it imports against the example's + peers (Reanimated 3); it does not reach the test files. - **`yarn lint`** lints `**/*.{js,ts,tsx}`, which includes test files and the `jest/` setup directory. From 32aab441baf3c009f8bb0e345dfbfd89aaedb8a6 Mon Sep 17 00:00:00 2001 From: Gabriel Parelli Francischini Date: Wed, 11 Nov 2026 11:43:56 -0300 Subject: [PATCH 2/2] fix(dots): stop the section list centering a section the app removed The section list centers the touched section again after show(): a second later, and on each content size change while the section is pending. Both kept the section from show(), so after the app passed fewer sections, scrollToIndex got an index past the last row and threw "scrollToIndex out of range" from a timer or an event handler, a fatal JS error. The pending one can last as long as the list is open: on the New Architecture the list reports each batch's size before laying its rows out, so a section in the last batch misses its last chance to be centered. A kept section is now centered only while the row at its position still has its list index. Co-Authored-By: Claude Opus 5.5 --- docs/backlog.md | 54 +--------------- .../FastScrollSectionFullList.tsx | 13 ++++ .../__tests__/FastScrollSectionDots.test.tsx | 63 +++++++++++++++++++ 3 files changed, 78 insertions(+), 52 deletions(-) diff --git a/docs/backlog.md b/docs/backlog.md index 15b2399..7278cca 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -26,8 +26,6 @@ the whole patch (see `CLAUDE.md`). Before that release: -- Fix "The section list can center a section that no longer exists" below: it - can throw. It is rare, but the fix is a bounds check and clearing one ref. - 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 @@ -42,53 +40,6 @@ Before that release: ## Bugs -### The section list can center a section that no longer exists - -The section list can scroll to a `sectionIndex` it kept from before the app -passed new sections. When that index is past the new last row, `scrollToIndex` -throws `scrollToIndex out of range` from a timer or an event handler. The -throw is an `invariant`, which also throws in release builds, and no error -boundary catches it there, so it is a fatal JS error. When the index is still -in range, the list scrolls by itself to the row that now has it. - -It takes the app passing fewer sections while the section list is open, and -there are two ways in: - -- **The retry a second after `show()`** - ([FastScrollSectionFullList.tsx:232-236](../src/FastScrollSectionDots/FastScrollSectionFullList.tsx#L232-L236)) - keeps the section it was scheduled with, so the sections have to change - within that second. 0.3.2 and 0.3.4 have this one too. -- **The pending section**, new since 0.3.4, open for as long as the list stays - open (3 s after the lift). - - `sectionToCenter` is cleared only when `centerPendingSection` - ([lines 169-181](../src/FastScrollSectionDots/FastScrollSectionFullList.tsx#L169-L181)) - centers its row, which it tries on each content size change. Neither the - 1 s retry nor closing the list clears it. - - A `FlatList` without `getItemLayout` sizes its tail spacer only up to the - rows it has measured. So its content size changes once per batch of rows it - renders, up to 10 rows a batch, and the batch that ends the list causes the - last change. - - The New Architecture emits a view's layout event before its children's - (`YogaLayoutableShadowNode::layout`), so the list reports each batch's size - before those rows are measured. When the touched row is in the batch that - ends the list, and that batch is not the first, its centering misses on the - last change and the section stays pending. - - The next content size change, which new sections cause, then centers the - old index. - -Reproduced under Jest in a throwaway test, with the events fired in that order: -30 sections, a quick tap on the dot of section 25, then 25 sections, and -`scrollToIndex` throws. A tap on section 15, in a middle batch, ends clean. The -event order was read in React Native's source, not observed on a device. - -An app that unmounts the dots while its data reloads, for example behind a -loading view, takes neither path: the dots start over with the new sections. - -Possible fix: clear `sectionToCenter` in the 1 s retry and when the list -closes, and skip a `sectionIndex` that is not below `sections.length` in -`centerSection`. "Center the section list without a virtualized list" under -Proposals removes the pending state altogether. - ### 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): @@ -296,9 +247,8 @@ centers a row through four mechanisms: `onContentSizeChange`, a 50 ms poll while no row is measured, a jump to an estimated offset, and a retry after 1 s. `centerMiss` ties them together, and only works because `FlatList` calls `onScrollToIndexFailed` synchronously inside `scrollToIndex`. All of it works -around virtualization, for a list of one short row per section, and "The -section list can center a section that no longer exists" above comes from the -state it keeps. +around virtualization, for a list of one short row per section, and the state +it keeps once let the list center a section the app had removed. A `ScrollView` that records each row's y from `onLayout` can center with one exact `scrollTo` once the row is laid out. That drops `sectionToCenter`, diff --git a/src/FastScrollSectionDots/FastScrollSectionFullList.tsx b/src/FastScrollSectionDots/FastScrollSectionFullList.tsx index ae527d9..9c489ef 100644 --- a/src/FastScrollSectionDots/FastScrollSectionFullList.tsx +++ b/src/FastScrollSectionDots/FastScrollSectionFullList.tsx @@ -129,9 +129,22 @@ const FastScrollSectionFullList = React.forwardRef( [] ); + // The retries below run after show(), by when the app may have passed other + // sections. A section kept from before then is centered only if it is + // still there: the row at its position has the same list index. Otherwise + // the list would scroll to whatever row now has that position, and past + // the last row scrollToIndex throws. + const sectionsRef = useRef(sections); + sectionsRef.current = sections; + /** Centers the row of `section` in the list, when the list is on screen. */ const centerSection = useCallback( (section: SectionFullData, animated?: boolean) => { + if ( + sectionsRef.current[section.sectionIndex]?.index !== section.index + ) { + return; + } flatListRef.current?.scrollToIndex({ index: section.sectionIndex, viewPosition: 0.5, diff --git a/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx b/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx index 2970fa2..27fd36f 100644 --- a/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx +++ b/src/FastScrollSectionDots/__tests__/FastScrollSectionDots.test.tsx @@ -869,4 +869,67 @@ describe('FastScrollSectionDots', () => { [{ y: 55 }], ]); }); + + it('does not scroll the section list to a section the app removed before the retry a second later', () => { + const { replaceSections } = renderDots({ + hideFastScrollIndicatorTimeout: 0, + }); + drag([FINGER_ON.dairy]); + layoutSectionList({ visibleHeight: 40, rowHeight: 30 }); + const scrollTo: jest.Mock = getSectionListScrollView().instance.scrollTo; + scrollTo.mockClear(); + + // Within the second, a filter leaves only Fruits and Vegetables. + replaceSections(SECTIONS.slice(0, 2)); + + expect(() => act(() => jest.advanceTimersByTime(1000))).not.toThrow(); + expect(scrollTo).not.toHaveBeenCalled(); + }); + + // The section list sizes its content only up to the rows it has measured, so + // it grows with each batch of rows it renders. On the New Architecture it + // reports each new size before the layout of the rows that caused it, so a + // section in the last batch is still waiting to be centered once every row + // is laid out. + it('does not scroll the section list to a section the app removed while it waited to center it', () => { + const aisles = (count: number): Section[] => + Array.from({ length: count }, (_, i) => ({ + index: i * 10, + text: `Aisle ${i}`, + })); + const { replaceSections } = renderDots({ + hideFastScrollIndicatorTimeout: 0, + sections: aisles(30), + }); + + // A quick tap on Aisle 25's dot, which starts at 12 * 26 + 10 * 25 = 562. + drag([565]); + const scrollView = getSectionListScrollView(); + const layout = (y: number, height: number) => ({ + nativeEvent: { layout: { x: 0, y, width: 100, height } }, + }); + fireEvent(scrollView, 'layout', layout(0, 100)); + /** The list renders a batch of 10 rows, reports its size, then lays them out. */ + const layoutBatch = (first: number) => { + act(() => jest.advanceTimersByTime(100)); + fireEvent(scrollView, 'contentSizeChange', 100, (first + 10) * 30); + Array.from({ length: 10 }, (_, i) => first + i).forEach((i) => + fireEvent(screen.getByText(`Aisle ${i}`), 'layout', layout(i * 30, 30)) + ); + }; + layoutBatch(0); + layoutBatch(10); + layoutBatch(20); + act(() => jest.advanceTimersByTime(1000)); + const scrollTo: jest.Mock = scrollView.instance.scrollTo; + scrollTo.mockClear(); + + // The list is still open when a filter leaves 25 aisles: Aisle 25 is gone. + replaceSections(aisles(25)); + + expect(() => + fireEvent(scrollView, 'contentSizeChange', 100, 25 * 30) + ).not.toThrow(); + expect(scrollTo).not.toHaveBeenCalled(); + }); });