From f65895b8d1eaaa552d77f8551bde2bf8e82e387a Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 27 Nov 2026 19:10:27 +0100 Subject: [PATCH 1/4] feat: return a Promise from the scroll methods scrollToIndex, scrollToOffset and scrollToEnd now return a Promise that resolves once the list rests after the scroll, or when a drag, a newer scroll or an unmount ends it first. A scroll sent in the same frame as new data is sent again after that data reaches native, under a new id the Promise follows, so setData and scrollToIndex from one handler land on the new rows. On iOS the first one could stop 1.5 rows past the index. The out-of-range warning now checks the index against the data at the end of that frame. --- src/Flume.tsx | 86 +++++++++++++------ src/__tests__/Flume.test.tsx | 150 +++++++++++++++++++++++++++++++++ src/__tests__/commands.test.ts | 105 +++++++++++++++++++++++ src/commands.ts | 36 ++++++++ src/types.ts | 7 +- 5 files changed, 353 insertions(+), 31 deletions(-) create mode 100644 src/__tests__/commands.test.ts create mode 100644 src/commands.ts diff --git a/src/Flume.tsx b/src/Flume.tsx index 0b99684..dd6e4db 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -19,6 +19,7 @@ import { import { type StyleProp, View, type ViewStyle } from 'react-native'; import { createSerializable } from 'react-native-worklets'; import { cellKinds, itemComponentCell, type ResolvedCell, resolveCell } from './cells'; +import { createScrollCommands } from './commands'; import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data'; import { FlumeSlot } from './FlumeSlot'; import { hostProps } from './foreign'; @@ -60,6 +61,9 @@ import type { ViewToken, } from './types'; +type NativeView = ComponentRef; +type RecentCommand = { send: (native: NativeView, id: number) => void; index?: number }; + // FlatList's rule for the list components: an element renders as given, a component through createElement. // A given style wraps it in a View, as FlatList and FlashList do. function componentElement( @@ -125,9 +129,11 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { const released = useRef(false); const prev = useRef<{ storeId: number; signature?: string; state?: DataState }>({ storeId }); const warned = useRef({ duplicates: false, messages: new Set() }); - const nativeRef = useRef>(null); - // Native reports the end of a scroll command by this id, which only grows. - const commandId = useRef(0); + const nativeRef = useRef(null); + // Native reports the end of each scroll command by its id, which settles the command's Promise. + const [commands] = useState(createScrollCommands); + // The last scroll command until the next frame, sent again after data committed meanwhile. + const recent = useRef(null); // React Native's RefreshControl rule: a pull starts native refreshing, so an unchanged prop is sent back. const wantsRefreshing = refresh.refreshing; const nativeRefreshing = useRef(wantsRefreshing); @@ -289,7 +295,11 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { commit.diffMs, performance.now() - start, ); - }, [host, storeId, commit, report]); + // A scroll from this frame reached native before this data, so it goes again to land in the new rows. + const command = recent.current; + const native = nativeRef.current; + if (command !== null && native !== null) command.send(native, commands.move()); + }, [host, storeId, commit, report, commands]); useLayoutEffect(() => { const sent = sentSticky.current; @@ -456,38 +466,57 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { ); }); + // The index is checked once the frame ends, against the data a handler committed with the scroll. + const sendCommand = useCallback( + (send: RecentCommand['send'], index?: number): Promise => { + const native = nativeRef.current; + if (native === null) return Promise.resolve(); + const { id, done } = commands.start(); + send(native, id); + const command: RecentCommand = { send, index }; + recent.current = command; + requestAnimationFrame(() => { + if (recent.current !== command) return; + recent.current = null; + if (index !== undefined && (index < 0 || index >= count.current)) { + warn(`scrollToIndex: index ${index} is out of range for ${count.current} items`); + } + }); + return done; + }, + [commands, warn], + ); + const endCommand = useCallback( + (event: { nativeEvent: { id: number } }) => commands.endThrough(event.nativeEvent.id), + [commands], + ); + // StrictMode replays this effect, so the tracker keeps working after endAll. + useEffect( + () => () => { + recent.current = null; + commands.endAll(); + }, + [commands], + ); + // FlatList's defaults: animated, the item at the start edge; native clamps the index. useImperativeHandle( ref, () => ({ - scrollToIndex: ({ index, animated = true, viewPosition = 0, viewOffset = 0 }) => { - const native = nativeRef.current; - if (native === null) return; - if (index < 0 || index >= count.current) { - warn(`scrollToIndex: index ${index} is out of range for ${count.current} items`); - } - Commands.scrollToIndex( - native, - ++commandId.current, + scrollToIndex: ({ index, animated = true, viewPosition = 0, viewOffset = 0 }) => + sendCommand( + (native, id) => + Commands.scrollToIndex(native, id, index, animated, viewPosition, viewOffset), index, - animated, - viewPosition, - viewOffset, - ); - }, - scrollToOffset: ({ offset, animated = true }) => { - const native = nativeRef.current; - if (native !== null) Commands.scrollToOffset(native, ++commandId.current, offset, animated); - }, - scrollToEnd: (params) => { - const native = nativeRef.current; - if (native !== null) - Commands.scrollToEnd(native, ++commandId.current, params?.animated ?? true); - }, + ), + scrollToOffset: ({ offset, animated = true }) => + sendCommand((native, id) => Commands.scrollToOffset(native, id, offset, animated)), + scrollToEnd: (params) => + sendCommand((native, id) => Commands.scrollToEnd(native, id, params?.animated ?? true)), getScrollableNode: () => nativeRef.current, getAnimatableRef: () => nativeRef.current, }), - [warn], + [sendCommand], ); const press = (handler: ((info: PressInfo) => void) | undefined) => @@ -520,6 +549,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { {...hostProps(given)} {...nativeProps(props, warn)} ref={nativeRef} + onScrollCommandEnd={endCommand} storeId={storeId} itemAnimations={itemAnimations} onCellPress={press(onPress)} diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index 0db4653..0c6d6a3 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -836,8 +836,158 @@ describe('Flume edges', () => { }); describe('Flume ref', () => { + const frames: Array<() => void> = []; + const nextFrame = () => { + for (const run of frames.splice(0)) run(); + }; + const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + const track = (done: Promise | undefined) => { + const state = { resolved: false }; + void done?.then(() => { + state.resolved = true; + }); + return state; + }; + const endCommand = (tree: ReactTestRenderer, id: number) => + act(() => { + tree.root + .find((node) => String(node.type) === 'FlumeView') + .props.onScrollCommandEnd({ nativeEvent: { id } }); + }); + beforeEach(() => { vi.resetModules(); + frames.length = 0; + vi.stubGlobal('requestAnimationFrame', (run: () => void) => frames.push(run)); + }); + + it('scrollToIndex resolves when native reports its end', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + const state = track(ref.current?.scrollToIndex({ index: 0 })); + await flush(); + expect(state.resolved).toBe(false); + await endCommand(tree, 1); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('resolves at once without a native view', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + await act(async () => { + create(createElement(Flume, { ref, data: [item], renderCell }), { + createNodeMock: () => null, + }); + }); + const state = track(ref.current?.scrollToOffset({ offset: 10 })); + await flush(); + expect(state.resolved).toBe(true); + expect(Commands.scrollToOffset).not.toHaveBeenCalled(); + }); + + it('resolves pending scrolls on unmount', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + const state = track(ref.current?.scrollToEnd()); + await act(async () => tree.unmount()); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('sends a command again under a new id after data of the same frame', async () => { + const host = installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + vi.mocked(Commands.scrollToIndex).mockImplementation((_view, id) => { + host.log.push(`index ${id}`); + }); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToIndex({ index: 1, animated: false }); + await act(async () => + tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })), + ); + expect(host.log.slice(-3)).toEqual(['index 1', 'data [1]', 'index 2']); + expect(Commands.scrollToIndex).toHaveBeenLastCalledWith(expect.anything(), 2, 1, false, 0, 0); + }); + + it('keeps a scroll sent again pending until its new id ends', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + const state = track(ref.current?.scrollToIndex({ index: 1 })); + await act(async () => + tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })), + ); + await endCommand(tree, 1); + await flush(); + expect(state.resolved).toBe(false); + await endCommand(tree, 2); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('does not send a scroll again once its frame passed', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToEnd(); + nextFrame(); + await act(async () => + tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })), + ); + expect(Commands.scrollToEnd).toHaveBeenCalledTimes(1); + }); + + it('does not send a scroll again when native data is unchanged', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToOffset({ offset: 10 }); + await act(async () => tree.update(createElement(Flume, { ref, data: [item], renderCell }))); + expect(Commands.scrollToOffset).toHaveBeenCalledTimes(1); + }); + + it('checks an index against the data of the same frame', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToIndex({ index: 1 }); + await act(async () => + tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })), + ); + nextFrame(); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it('warns about an index past the data once its frame passes', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const ref = createRef(); + await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToIndex({ index: 5 }); + expect(warn).not.toHaveBeenCalled(); + nextFrame(); + expect(warn).toHaveBeenCalledWith( + 'react-native-flume: scrollToIndex: index 5 is out of range for 1 items', + ); + warn.mockRestore(); }); it('sends the commands with FlatList defaults and a growing id', async () => { diff --git a/src/__tests__/commands.test.ts b/src/__tests__/commands.test.ts new file mode 100644 index 0000000..cf90ecd --- /dev/null +++ b/src/__tests__/commands.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from 'vitest'; +import { createScrollCommands } from '../commands'; + +// Settles a Promise's callbacks queued so far, so a test can read whether it resolved. +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +function track(done: Promise) { + const state = { resolved: false, rejected: false }; + done.then( + () => { + state.resolved = true; + }, + () => { + state.rejected = true; + }, + ); + return state; +} + +describe('createScrollCommands', () => { + it('resolves a command when its end arrives', async () => { + const commands = createScrollCommands(); + const { id, done } = commands.start(); + const state = track(done); + await flush(); + expect(state.resolved).toBe(false); + commands.endThrough(id); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('resolves the older command when a newer one starts', async () => { + const commands = createScrollCommands(); + const first = track(commands.start().done); + const second = track(commands.start().done); + await flush(); + expect(first.resolved).toBe(true); + expect(second.resolved).toBe(false); + }); + + it('keeps the newer command pending when an older end arrives late', async () => { + const commands = createScrollCommands(); + const first = commands.start(); + const second = track(commands.start().done); + commands.endThrough(first.id); + await flush(); + expect(second.resolved).toBe(false); + }); + + it('resolves everything on endAll', async () => { + const commands = createScrollCommands(); + const state = track(commands.start().done); + commands.endAll(); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('never rejects', async () => { + const commands = createScrollCommands(); + const states = [track(commands.start().done), track(commands.start().done)]; + commands.endThrough(99); + commands.endAll(); + await flush(); + expect(states.every((state) => state.resolved && !state.rejected)).toBe(true); + }); + + it('keeps a moved command pending when its old id ends', async () => { + const commands = createScrollCommands(); + const { id, done } = commands.start(); + const state = track(done); + const moved = commands.move(); + commands.endThrough(id); + await flush(); + expect(moved).toBeGreaterThan(id); + expect(state.resolved).toBe(false); + }); + + it('resolves a moved command when its new id ends', async () => { + const commands = createScrollCommands(); + const state = track(commands.start().done); + commands.endThrough(commands.move()); + await flush(); + expect(state.resolved).toBe(true); + }); + + it('gives a fresh id when nothing is pending', () => { + const commands = createScrollCommands(); + const { id } = commands.start(); + commands.endThrough(id); + const moved = commands.move(); + const next = commands.start(); + expect(moved).toBeGreaterThan(id); + expect(next.id).toBeGreaterThan(moved); + }); + + it('keeps working after endAll', async () => { + const commands = createScrollCommands(); + commands.endAll(); + const { id, done } = commands.start(); + const state = track(done); + commands.endThrough(id); + await flush(); + expect(state.resolved).toBe(true); + }); +}); diff --git a/src/commands.ts b/src/commands.ts new file mode 100644 index 0000000..f0cc668 --- /dev/null +++ b/src/commands.ts @@ -0,0 +1,36 @@ +export type ScrollCommands = { + start(): { id: number; done: Promise }; + // A command sent again takes a new id and keeps its Promise; with none pending the id is just fresh. + move(): number; + endThrough(id: number): void; + endAll(): void; +}; + +// Native ends commands in order and a newer one interrupts the one before, so one Promise is pending at most. +export function createScrollCommands(): ScrollCommands { + let last = 0; + let pending: { id: number; resolve: () => void } | null = null; + const endPending = () => { + pending?.resolve(); + pending = null; + }; + return { + start() { + endPending(); + const id = ++last; + const done = new Promise((resolve) => { + pending = { id, resolve }; + }); + return { id, done }; + }, + move() { + last += 1; + if (pending !== null) pending.id = last; + return last; + }, + endThrough(id) { + if (pending !== null && pending.id <= id) endPending(); + }, + endAll: endPending, + }; +} diff --git a/src/types.ts b/src/types.ts index fa56571..ae16a2c 100644 --- a/src/types.ts +++ b/src/types.ts @@ -169,15 +169,16 @@ export type ViewabilityConfig = { }; // scrollToIndex is exact for worklet rows; the last two members serve Animated and Reanimated, which read them by name. +// A scroll resolves once the list rests after it, or when a drag, a newer scroll or an unmount ends it first. export type FlumeRef = { scrollToIndex(params: { index: number; animated?: boolean; viewPosition?: number; viewOffset?: number; - }): void; - scrollToOffset(params: { offset: number; animated?: boolean }): void; - scrollToEnd(params?: { animated?: boolean }): void; + }): Promise; + scrollToOffset(params: { offset: number; animated?: boolean }): Promise; + scrollToEnd(params?: { animated?: boolean }): Promise; getScrollableNode(): unknown; getAnimatableRef(): unknown; }; From 37571e3a26648554dcb30d2648e7ef5b511a6439 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 27 Nov 2026 19:50:22 +0100 Subject: [PATCH 2/4] fix(ios): end a scroll that lands while a finger holds the list A scroll command sent while a finger held the list, from a timer or an onScroll handler, landed under the finger and waited for the list to rest. After a release without momentum no layout runs, so nothing ended it, and its Promise stayed pending until the next command (24 s in one run). The end of a drag without momentum now ends it. --- ios/FLMView.mm | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ios/FLMView.mm b/ios/FLMView.mm index 576f169..69a04f3 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -1396,6 +1396,8 @@ - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL _scrollEvents.didEndDragging(decelerate); if (!decelerate) { [self writeShadowOrigins]; + // A command that landed under the finger ends here, since no layout follows a release without momentum. + [self settleCommand]; } } From 136c20e41c56e41dae96e1fb06732cd3b02b957e Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 21:19:57 +0100 Subject: [PATCH 3/4] fix: do not send again a scroll that native already ended A scroll from a handler goes to native a second time when data from the same frame commits after it, so it lands in the new rows. If native had ended it in between (a drag took the list), the second copy ran again under the finger with no Promise behind it. The wrapper now skips a scroll whose end event arrived. --- src/Flume.tsx | 22 ++++++++++++++++++---- src/__tests__/Flume.test.tsx | 29 +++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/src/Flume.tsx b/src/Flume.tsx index dd6e4db..6dfc559 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -62,7 +62,13 @@ import type { } from './types'; type NativeView = ComponentRef; -type RecentCommand = { send: (native: NativeView, id: number) => void; index?: number }; +type RecentCommand = { + send: (native: NativeView, id: number) => void; + index?: number; + id: number; + // Native ended it (a drag, a newer command), so data of the same frame no longer sends it again. + ended: boolean; +}; // FlatList's rule for the list components: an element renders as given, a component through createElement. // A given style wraps it in a View, as FlatList and FlashList do. @@ -298,7 +304,10 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { // A scroll from this frame reached native before this data, so it goes again to land in the new rows. const command = recent.current; const native = nativeRef.current; - if (command !== null && native !== null) command.send(native, commands.move()); + if (command !== null && native !== null && !command.ended) { + command.id = commands.move(); + command.send(native, command.id); + } }, [host, storeId, commit, report, commands]); useLayoutEffect(() => { @@ -473,7 +482,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { if (native === null) return Promise.resolve(); const { id, done } = commands.start(); send(native, id); - const command: RecentCommand = { send, index }; + const command: RecentCommand = { send, index, id, ended: false }; recent.current = command; requestAnimationFrame(() => { if (recent.current !== command) return; @@ -487,7 +496,12 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { [commands, warn], ); const endCommand = useCallback( - (event: { nativeEvent: { id: number } }) => commands.endThrough(event.nativeEvent.id), + (event: { nativeEvent: { id: number } }) => { + const { id } = event.nativeEvent; + const command = recent.current; + if (command !== null && command.id <= id) command.ended = true; + commands.endThrough(id); + }, [commands], ); // StrictMode replays this effect, so the tracker keeps working after endAll. diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index 0c6d6a3..3e563c9 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -935,6 +935,35 @@ describe('Flume ref', () => { expect(state.resolved).toBe(true); }); + it('does not send a scroll again once native ended it', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToEnd(); + await endCommand(tree, 1); + await act(async () => + tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })), + ); + expect(Commands.scrollToEnd).toHaveBeenCalledTimes(1); + }); + + it('sends a scroll again when only an older command ended', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const tree = await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToOffset({ offset: 10 }); + ref.current?.scrollToEnd(); + await endCommand(tree, 1); + await act(async () => + tree.update(createElement(Flume, { ref, data: [item, { id: 'b' }], renderCell })), + ); + expect(Commands.scrollToEnd).toHaveBeenCalledTimes(2); + }); + it('does not send a scroll again once its frame passed', async () => { installHost(); const { Flume } = await import('../Flume'); From dbfac2386ea683d1b8254816ae913696e2fb4575 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 21:22:02 +0100 Subject: [PATCH 4/4] fix(ios): settle a scroll when a fling under the finger ends A scroll sent while a finger held the list, then released with a fling, waited for the list to rest. No layout follows the end of momentum, so its Promise never settled (still pending 30 s later). The end of momentum now resumes a pending realign and settles the command, as Android does when the list goes idle. A release also drops the realign, as a drag does on Android, so it never pulls the list back to a jump's target after the finger moved it. --- ios/FLMView.mm | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ios/FLMView.mm b/ios/FLMView.mm index 69a04f3..4ed6bbf 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -1394,6 +1394,8 @@ - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { _scrollEvents.didEndDragging(decelerate); + // The finger had the list, so no realign pulls it back to a jump's target, as a drag drops it on Android. + _realign.reset(); if (!decelerate) { [self writeShadowOrigins]; // A command that landed under the finger ends here, since no layout follows a release without momentum. @@ -1410,6 +1412,9 @@ - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { [self emitScrollEvents:_scrollEvents.didEndDecelerating() velocity:CGPointZero]; [self writeShadowOrigins]; + // No layout follows the end of momentum, so a realign resumes and the command in flight ends here, as on Android. + [self realignIfIdle]; + [self settleCommand]; } // Rows measured during the glide can move the target, so an animated command lands on it again.