diff --git a/ios/FLMView.mm b/ios/FLMView.mm index 576f169..4ed6bbf 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -1394,8 +1394,12 @@ - (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. + [self settleCommand]; } } @@ -1408,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. diff --git a/src/Flume.tsx b/src/Flume.tsx index 0b99684..6dfc559 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,15 @@ import type { ViewToken, } from './types'; +type NativeView = ComponentRef; +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. function componentElement( @@ -125,9 +135,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 +301,14 @@ 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.ended) { + command.id = commands.move(); + command.send(native, command.id); + } + }, [host, storeId, commit, report, commands]); useLayoutEffect(() => { const sent = sentSticky.current; @@ -456,38 +475,62 @@ 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, id, ended: false }; + 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 } }) => { + 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. + 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 +563,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..3e563c9 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -836,8 +836,187 @@ 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 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'); + 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; };