From 225e3b13d581a8dc2542adc4fad72a90fb10a965 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 27 Nov 2026 19:51:01 +0100 Subject: [PATCH 1/4] feat: add the remaining FlatList and LegendList ref methods and props scrollToItem, scrollToTop, scrollIndexIntoView and scrollItemIntoView return a Promise like the other scroll methods, and setNativeProps reaches the list's native view. The into-view methods scroll only when the row is not fully visible, to the edge it is past, as LegendList does. The list also takes the four keyboard event props, progressViewOffset and alignItemsAtEnd. --- .../main/java/me/sectiontn/flume/FlumeView.kt | 20 ++++ .../me/sectiontn/flume/FlumeViewManager.kt | 3 + .../java/me/sectiontn/flume/ScrollCommands.kt | 10 ++ .../me/sectiontn/flume/ScrollCommandsTest.kt | 19 +++ cpp/adapter/ScrollCommands.cpp | 11 ++ cpp/adapter/ScrollCommands.h | 5 + cpp/tests/scroll_commands_test.cpp | 15 +++ ios/FLMView.mm | 35 ++++++ src/Flume.tsx | 60 ++++++++-- src/__tests__/Flume.test.tsx | 111 +++++++++++++++++- src/__tests__/props.test.ts | 16 +++ src/foreign.ts | 6 + src/keyboard.ts | 17 +++ src/props.ts | 13 +- src/specs/FlumeViewNativeComponent.ts | 16 ++- src/types.ts | 31 +++++ 16 files changed, 365 insertions(+), 23 deletions(-) create mode 100644 src/keyboard.ts diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 46c1350..26365d8 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -444,6 +444,26 @@ class FlumeView(context: Context) : FrameLayout(context) { requestJump(JumpTarget.Index(index), animated, viewPosition, viewOffsetDp) } + // A row already fully in view ends the command where the list is. An index past the data lands at the end edge. + fun scrollIndexIntoView(id: Int, index: Int, animated: Boolean, viewOffsetDp: Double) { + commands.begin(id) + val target = JumpTarget.Index(index) + val position = target.position(rows) + val first = layoutManager.findFirstCompletelyVisibleItemPosition() + val last = layoutManager.findLastCompletelyVisibleItemPosition() + val viewPosition = when { + position == null || target.waitsForData(rows) -> 1f + else -> IntoView.target(position, minOf(first, last), maxOf(first, last)) + } + if (viewPosition == null) { + jumps.cancel()?.let { dropJump(it) } + forgetLanding() + landCommand() + return + } + requestJump(target, animated, viewPosition, viewOffsetDp) + } + // React rows paint a frame or more after their bind, so a jump first has the rows it will show rendered. private fun requestJump(target: JumpTarget, animated: Boolean, viewPosition: Float, viewOffsetDp: Double) { jumps.cancel()?.let { dropJump(it) } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt index 211a17f..e3c5317 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt @@ -328,6 +328,9 @@ class FlumeViewManager : ViewGroupManager(), FlumeViewManagerInterfac override fun scrollToEnd(view: FlumeView, requestId: Int, animated: Boolean) = view.scrollToEnd(requestId, animated) + override fun scrollIndexIntoView(view: FlumeView, requestId: Int, index: Int, animated: Boolean, viewOffset: Double) = + view.scrollIndexIntoView(requestId, index, animated, viewOffset) + override fun setNativeRefreshing(view: FlumeView, refreshing: Boolean) = view.setNativeRefreshing(refreshing) companion object { diff --git a/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt b/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt index a627926..2df423b 100644 --- a/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt +++ b/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt @@ -36,3 +36,13 @@ class ScrollCommands { landed = false } } + +// The viewPosition that brings a row into view: 0 before the fully visible rows, 1 after them, null when it is one. +object IntoView { + fun target(position: Int, firstFull: Int, lastFull: Int): Float? = when { + firstFull < 0 || lastFull < firstFull -> 0f + position < firstFull -> 0f + position > lastFull -> 1f + else -> null + } +} diff --git a/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt b/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt index a41e0c2..9f2ded9 100644 --- a/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt +++ b/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt @@ -1,6 +1,7 @@ package me.sectiontn.flume import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Test class ScrollCommandsTest { @@ -80,4 +81,22 @@ class ScrollCommandsTest { commands.begin(4) assertEquals(0, commands.settle(rest)) } + + @Test + fun intoViewEndsAtOnceForARowFullyInView() { + assertNull(IntoView.target(5, 3, 8)) + assertNull(IntoView.target(3, 3, 8)) + assertNull(IntoView.target(8, 3, 8)) + } + + @Test + fun intoViewScrollsWithViewPosition0BeforeTheVisibleRowsAnd1AfterThem() { + assertEquals(0f, IntoView.target(2, 3, 8)) + assertEquals(1f, IntoView.target(9, 3, 8)) + } + + @Test + fun intoViewPutsTheRowAtTheStartWhenNoRowIsFullyInView() { + assertEquals(0f, IntoView.target(4, -1, -1)) + } } diff --git a/cpp/adapter/ScrollCommands.cpp b/cpp/adapter/ScrollCommands.cpp index f298d56..63b766b 100644 --- a/cpp/adapter/ScrollCommands.cpp +++ b/cpp/adapter/ScrollCommands.cpp @@ -26,3 +26,14 @@ void ScrollCommands::reset() { } } // namespace flume + +namespace flume { + +std::optional intoViewPosition(int position, int firstFull, int lastFull) { + if (firstFull < 0 || lastFull < firstFull) return 0.f; + if (position < firstFull) return 0.f; + if (position > lastFull) return 1.f; + return std::nullopt; +} + +} // namespace flume diff --git a/cpp/adapter/ScrollCommands.h b/cpp/adapter/ScrollCommands.h index 3c4b5eb..4419b71 100644 --- a/cpp/adapter/ScrollCommands.h +++ b/cpp/adapter/ScrollCommands.h @@ -1,9 +1,14 @@ #pragma once #include +#include namespace flume { +// The viewPosition that brings a row into view: 0 before the fully visible rows, 1 after them, none when it is one. +// Positions count list rows. With no row fully in view, the row goes to the start. +std::optional intoViewPosition(int position, int firstFull, int lastFull); + // The scroll command in flight: its id is reported once, when it settles at rest or is interrupted. class ScrollCommands { public: diff --git a/cpp/tests/scroll_commands_test.cpp b/cpp/tests/scroll_commands_test.cpp index 8f8f6c3..f2a3b2e 100644 --- a/cpp/tests/scroll_commands_test.cpp +++ b/cpp/tests/scroll_commands_test.cpp @@ -76,3 +76,18 @@ TEST_CASE("ScrollCommands a newer command clears the landed mark") { commands.begin(4); CHECK(commands.settle(kRest) == 0); } + +TEST_CASE("IntoView ends at once for a row fully in view") { + CHECK_FALSE(intoViewPosition(5, 3, 8).has_value()); + CHECK_FALSE(intoViewPosition(3, 3, 8).has_value()); + CHECK_FALSE(intoViewPosition(8, 3, 8).has_value()); +} + +TEST_CASE("IntoView scrolls with viewPosition 0 before the visible rows and 1 after them") { + CHECK(intoViewPosition(2, 3, 8) == 0.f); + CHECK(intoViewPosition(9, 3, 8) == 1.f); +} + +TEST_CASE("IntoView puts the row at the start when no row is fully in view") { + CHECK(intoViewPosition(4, -1, -1) == 0.f); +} diff --git a/ios/FLMView.mm b/ios/FLMView.mm index 4ed6bbf..37e6881 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -1940,6 +1940,41 @@ - (void)scrollToEnd:(NSInteger)requestId animated:(BOOL)animated animated:animated]; } +// A row already fully in view ends the command where the list is. An index past the data lands at the end edge. +- (void)scrollIndexIntoView:(NSInteger)requestId + index:(NSInteger)index + animated:(BOOL)animated + viewOffset:(double)viewOffset +{ + [self beginCommand:requestId]; + if (!_attached) { + [self landCommand]; + return; + } + std::optional viewPosition = 1; + if (_rows.dataCount > 0 && index < _rows.dataCount) { + const FLMViewport viewport = [_layout viewportFor:_collectionView.bounds]; + int firstFull = INT_MAX; + int lastFull = -1; + for (const flume::ItemSpan &span : [_layout spansIn:viewport]) { + if (span.start >= -0.5f && span.end <= viewport.length + 0.5f) { + firstFull = std::min(firstFull, span.index); + lastFull = std::max(lastFull, span.index); + } + } + const int position = _rows.position(*flume::clampIndex(static_cast(index), _rows.dataCount)); + viewPosition = flume::intoViewPosition(position, lastFull < 0 ? -1 : firstFull, lastFull); + } + if (!viewPosition) { + [self dropJump]; + _pendingTarget.reset(); + [self landCommand]; + return; + } + [self scrollToTarget:FLMPendingTarget{FLMPendingTarget::Kind::Index, static_cast(index), *viewPosition, viewOffset} + animated:animated]; +} + - (void)setNativeRefreshing:(BOOL)refreshing { [_refresh setRefreshing:refreshing]; diff --git a/src/Flume.tsx b/src/Flume.tsx index 6dfc559..03cc3c0 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -23,6 +23,7 @@ import { createScrollCommands } from './commands'; import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data'; import { FlumeSlot } from './FlumeSlot'; import { hostProps } from './foreign'; +import { useKeyboardEvent } from './keyboard'; import { contentPadding, gapsOf, @@ -123,6 +124,10 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { onStartReached, keyboardShouldPersistTaps, } = props; + useKeyboardEvent('keyboardWillShow', props.onKeyboardWillShow); + useKeyboardEvent('keyboardWillHide', props.onKeyboardWillHide); + useKeyboardEvent('keyboardDidShow', props.onKeyboardDidShow); + useKeyboardEvent('keyboardDidHide', props.onKeyboardDidHide); const refresh = refreshOf(props); const { onRefresh } = refresh; const host = getHost(); @@ -477,7 +482,7 @@ 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 => { + (send: RecentCommand['send'], index?: number, method = 'scrollToIndex'): Promise => { const native = nativeRef.current; if (native === null) return Promise.resolve(); const { id, done } = commands.start(); @@ -488,7 +493,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { 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`); + warn(`${method}: index ${index} is out of range for ${count.current} items`); } }); return done; @@ -514,24 +519,53 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { ); // FlatList's defaults: animated, the item at the start edge; native clamps the index. - useImperativeHandle( - ref, - () => ({ + useImperativeHandle(ref, () => { + const toIndex = ( + index: number, + animated: boolean, + viewPosition: number, + viewOffset: number, + method?: string, + ) => + sendCommand( + (native, id) => + Commands.scrollToIndex(native, id, index, animated, viewPosition, viewOffset), + index, + method, + ); + const intoView = (index: number, animated: boolean, viewOffset: number, method: string) => + sendCommand( + (native, id) => Commands.scrollIndexIntoView(native, id, index, animated, viewOffset), + index, + method, + ); + // FlatList finds the item by identity in the data it rendered last. + const found = (item: unknown, scroll: (index: number) => Promise) => { + const index = dataRef.current.indexOf(item); + return index < 0 ? Promise.resolve() : scroll(index); + }; + return { scrollToIndex: ({ index, animated = true, viewPosition = 0, viewOffset = 0 }) => - sendCommand( - (native, id) => - Commands.scrollToIndex(native, id, index, animated, viewPosition, viewOffset), - index, - ), + toIndex(index, animated, viewPosition, viewOffset), 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)), + scrollToItem: ({ item, animated = true, viewPosition = 0, viewOffset = 0 }) => + found(item, (index) => toIndex(index, animated, viewPosition, viewOffset, 'scrollToItem')), + scrollToTop: (params) => + sendCommand((native, id) => + Commands.scrollToOffset(native, id, 0, params?.animated ?? true), + ), + scrollIndexIntoView: ({ index, animated = true, viewOffset = 0 }) => + intoView(index, animated, viewOffset, 'scrollIndexIntoView'), + scrollItemIntoView: ({ item, animated = true, viewOffset = 0 }) => + found(item, (index) => intoView(index, animated, viewOffset, 'scrollItemIntoView')), + setNativeProps: (nativeProps) => nativeRef.current?.setNativeProps(nativeProps), getScrollableNode: () => nativeRef.current, getAnimatableRef: () => nativeRef.current, - }), - [sendCommand], - ); + }; + }, [sendCommand]); const press = (handler: ((info: PressInfo) => void) | undefined) => handler === undefined diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index 3e563c9..a66be4e 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -29,12 +29,17 @@ vi.mock('../specs/FlumeViewNativeComponent', () => ({ scrollToIndex: vi.fn(), scrollToOffset: vi.fn(), scrollToEnd: vi.fn(), + scrollIndexIntoView: vi.fn(), setNativeRefreshing: vi.fn(), }, })); vi.mock('../specs/FlumeSlotViewNativeComponent', () => ({ default: 'FlumeSlotView' })); vi.mock('react-native', () => ({ - Keyboard: { isVisible: vi.fn(() => true), dismiss: vi.fn() }, + Keyboard: { + isVisible: vi.fn(() => true), + dismiss: vi.fn(), + addListener: vi.fn(() => ({ remove: vi.fn() })), + }, View: 'View', })); @@ -1019,6 +1024,64 @@ describe('Flume ref', () => { warn.mockRestore(); }); + it("scrollToItem scrolls to the item's index", async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const second = { id: 'b' }; + await mount(createElement(Flume, { ref, data: [item, second], renderCell })); + ref.current?.scrollToItem({ item: second, viewPosition: 0.5 }); + expect(Commands.scrollToIndex).toHaveBeenCalledWith(expect.anything(), 1, 1, true, 0.5, 0); + }); + + it('scrollToItem resolves at once for an item not in data', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + await mount(createElement(Flume, { ref, data: [item], renderCell })); + const state = track(ref.current?.scrollToItem({ item: { id: 'a' } })); + await flush(); + expect(state.resolved).toBe(true); + expect(Commands.scrollToIndex).not.toHaveBeenCalled(); + }); + + it('scrollToTop scrolls to offset 0', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + await mount(createElement(Flume, { ref, data: [item], renderCell })); + ref.current?.scrollToTop({ animated: false }); + expect(Commands.scrollToOffset).toHaveBeenCalledWith(expect.anything(), 1, 0, false); + }); + + it("scrollItemIntoView sends the item's index", async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const second = { id: 'b' }; + await mount(createElement(Flume, { ref, data: [item, second], renderCell })); + ref.current?.scrollItemIntoView({ item: second, viewOffset: 8 }); + expect(Commands.scrollIndexIntoView).toHaveBeenCalledWith(expect.anything(), 1, 1, true, 8); + }); + + it('setNativeProps forwards to the native view', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const ref = createRef(); + const setNativeProps = vi.fn(); + await act(async () => { + create(createElement(Flume, { ref, data: [item], renderCell }), { + createNodeMock: () => ({ setNativeProps }), + }); + }); + ref.current?.setNativeProps({ scrollEnabled: false }); + expect(setNativeProps).toHaveBeenCalledWith({ scrollEnabled: false }); + }); + it('sends the commands with FlatList defaults and a growing id', async () => { installHost(); const { Flume } = await import('../Flume'); @@ -1034,6 +1097,52 @@ describe('Flume ref', () => { }); }); +describe('Flume keyboard events', () => { + beforeEach(() => { + vi.resetModules(); + }); + + it.each([ + ['onKeyboardWillShow', 'keyboardWillShow'], + ['onKeyboardWillHide', 'keyboardWillHide'], + ['onKeyboardDidShow', 'keyboardDidShow'], + ['onKeyboardDidHide', 'keyboardDidHide'], + ] as const)('calls %s from the Keyboard event', async (prop, name) => { + installHost(); + const { Flume } = await import('../Flume'); + const { Keyboard } = await import('react-native'); + const handler = vi.fn(); + await mount(createElement(Flume, { data: [item], renderCell, [prop]: handler })); + const calls = vi.mocked(Keyboard.addListener).mock.calls; + expect(calls.map((call) => call[0])).toEqual([name]); + const event = { endCoordinates: { screenY: 300, height: 320 } }; + (calls[0] as unknown as [string, (event: unknown) => void])[1](event); + expect(handler).toHaveBeenCalledWith(event); + }); + + it('subscribes to no keyboard event without a handler', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Keyboard } = await import('react-native'); + await mount(createElement(Flume, { data: [item], renderCell })); + expect(Keyboard.addListener).not.toHaveBeenCalled(); + }); + + it('removes the keyboard subscription on unmount', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Keyboard } = await import('react-native'); + const tree = await mount( + createElement(Flume, { data: [item], renderCell, onKeyboardDidShow: () => {} }), + ); + const subscription = vi.mocked(Keyboard.addListener).mock.results[0]?.value as { + remove: () => void; + }; + await act(async () => tree.unmount()); + expect(subscription.remove).toHaveBeenCalled(); + }); +}); + describe('Flume stats', () => { beforeEach(() => { vi.resetModules(); diff --git a/src/__tests__/props.test.ts b/src/__tests__/props.test.ts index 66c401b..b355f3a 100644 --- a/src/__tests__/props.test.ts +++ b/src/__tests__/props.test.ts @@ -536,3 +536,19 @@ describe('flexGrow and justifyContent', () => { expect(warn).toHaveBeenCalledWith(expect.stringContaining('justifyContent')); }); }); + +describe('nativeProps wrapper props', () => { + it('passes progressViewOffset to the refresh control', () => { + const props = nativeProps({ data: [], onRefresh: () => {}, progressViewOffset: 30 }, vi.fn()); + expect(props.refreshProgressViewOffset).toBe(30); + }); + + it('alignItemsAtEnd places short content at the end', () => { + const warn = vi.fn(); + expect(nativeProps({ data: [], alignItemsAtEnd: true }, warn)).toMatchObject({ + contentJustify: 'end', + growFooter: false, + }); + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/src/foreign.ts b/src/foreign.ts index 047a6c2..a82ab50 100644 --- a/src/foreign.ts +++ b/src/foreign.ts @@ -166,6 +166,7 @@ export const OWN_KEYS = [ 'refreshing', 'onRefresh', 'refreshControl', + 'progressViewOffset', 'scrollEnabled', 'nestedScrollEnabled', 'overScrollMode', @@ -179,6 +180,11 @@ export const OWN_KEYS = [ 'alwaysBounceVertical', 'keyboardDismissMode', 'keyboardShouldPersistTaps', + 'onKeyboardWillShow', + 'onKeyboardWillHide', + 'onKeyboardDidShow', + 'onKeyboardDidHide', + 'alignItemsAtEnd', 'maintainVisibleContentPosition', 'onLayout', 'testID', diff --git a/src/keyboard.ts b/src/keyboard.ts new file mode 100644 index 0000000..76cc7cc --- /dev/null +++ b/src/keyboard.ts @@ -0,0 +1,17 @@ +import { useEffect, useRef } from 'react'; +import { Keyboard, type KeyboardEvent, type KeyboardEventName } from 'react-native'; + +// Subscribes only while a handler is given, and calls the latest one without subscribing again. +export function useKeyboardEvent( + name: KeyboardEventName, + handler: ((event: KeyboardEvent) => void) | null | undefined, +): void { + const latest = useRef(handler); + latest.current = handler; + const given = handler != null; + useEffect(() => { + if (!given) return undefined; + const subscription = Keyboard.addListener(name, (event) => latest.current?.(event)); + return () => subscription.remove(); + }, [name, given]); +} diff --git a/src/props.ts b/src/props.ts index 113a028..93499a3 100644 --- a/src/props.ts +++ b/src/props.ts @@ -324,7 +324,7 @@ export function refreshOf(props: FlumeProps): Refresh { refreshing: props.refreshing === true, colors: control?.colors, tintColor: control?.tintColor, - progressViewOffset: control?.progressViewOffset ?? 0, + progressViewOffset: props.progressViewOffset ?? control?.progressViewOffset ?? 0, enabled: true, }; } @@ -393,18 +393,15 @@ function contentGrowth( const content: Record = {}; flatten(props.contentContainerStyle, content); const grows = typeof content.flexGrow === 'number' && content.flexGrow > 0; - if (!grows) return { contentJustify: 'start', growFooter: false }; + // LegendList's alignItemsAtEnd places short content without growing it, so a footer keeps its length. + if (!grows) return { contentJustify: props.alignItemsAtEnd ? 'end' : 'start', growFooter: false }; const footer: Record = {}; flatten(props.ListFooterComponentStyle, footer); // Yoga takes an explicit flexGrow, 0 included, before the flex shorthand. const grow = typeof footer.flexGrow === 'number' ? footer.flexGrow : footer.flex; + const justify = content.justifyContent ?? (props.alignItemsAtEnd ? 'flex-end' : undefined); return { - contentJustify: - content.justifyContent === 'center' - ? 'center' - : content.justifyContent === 'flex-end' - ? 'end' - : 'start', + contentJustify: justify === 'center' ? 'center' : justify === 'flex-end' ? 'end' : 'start', growFooter: props.ListFooterComponent != null && typeof grow === 'number' && grow > 0, }; } diff --git a/src/specs/FlumeViewNativeComponent.ts b/src/specs/FlumeViewNativeComponent.ts index 0f45794..5676e9e 100644 --- a/src/specs/FlumeViewNativeComponent.ts +++ b/src/specs/FlumeViewNativeComponent.ts @@ -180,12 +180,26 @@ interface NativeCommands { requestId: CodegenTypes.Int32, animated: boolean, ) => void; + // Scrolls only when the row is not fully in view, to the edge it is past. + scrollIndexIntoView: ( + viewRef: React.ElementRef, + requestId: CodegenTypes.Int32, + index: CodegenTypes.Int32, + animated: boolean, + viewOffset: CodegenTypes.Double, + ) => void; // A pull starts refreshing natively; the wrapper sends the controlled prop back when it did not change. setNativeRefreshing: (viewRef: React.ElementRef, refreshing: boolean) => void; } export const Commands: NativeCommands = codegenNativeCommands({ - supportedCommands: ['scrollToIndex', 'scrollToOffset', 'scrollToEnd', 'setNativeRefreshing'], + supportedCommands: [ + 'scrollToIndex', + 'scrollToOffset', + 'scrollToEnd', + 'scrollIndexIntoView', + 'setNativeRefreshing', + ], }); export default codegenNativeComponent('FlumeView', { diff --git a/src/types.ts b/src/types.ts index ae16a2c..2aed4de 100644 --- a/src/types.ts +++ b/src/types.ts @@ -2,6 +2,7 @@ import type { ComponentType, ReactElement, ReactNode } from 'react'; import type { ColorValue, Insets, + KeyboardEvent, LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent, @@ -179,6 +180,27 @@ export type FlumeRef = { }): Promise; scrollToOffset(params: { offset: number; animated?: boolean }): Promise; scrollToEnd(params?: { animated?: boolean }): Promise; + // The item is found by identity in the current data. One that is not there resolves at once. + scrollToItem(params: { + item: unknown; + animated?: boolean; + viewOffset?: number; + viewPosition?: number; + }): Promise; + scrollToTop(params?: { animated?: boolean }): Promise; + // LegendList's: scrolls only when the row is not fully in view, to the edge it is past. + scrollIndexIntoView(params: { + index: number; + animated?: boolean; + viewOffset?: number; + }): Promise; + scrollItemIntoView(params: { + item: unknown; + animated?: boolean; + viewOffset?: number; + }): Promise; + // Reaches the list's own native props, such as scrollEnabled. + setNativeProps(props: object): void; getScrollableNode(): unknown; getAnimatableRef(): unknown; }; @@ -322,6 +344,8 @@ export type FlumeOwnProps = { | ReactElement | { tintColor?: ColorValue; colors?: ReadonlyArray; progressViewOffset?: number } | null; + // FlatList's: the spinner's offset for the refresh control onRefresh makes. + progressViewOffset?: number; scrollEnabled?: boolean; nestedScrollEnabled?: boolean; overScrollMode?: 'auto' | 'always' | 'never'; @@ -337,6 +361,13 @@ export type FlumeOwnProps = { // interactive is iOS only. keyboardDismissMode?: 'none' | 'on-drag' | 'interactive'; keyboardShouldPersistTaps?: 'always' | 'never' | 'handled'; + // As on ScrollView, from React Native's Keyboard events while a handler is given. + onKeyboardWillShow?: ((event: KeyboardEvent) => void) | null; + onKeyboardWillHide?: ((event: KeyboardEvent) => void) | null; + onKeyboardDidShow?: ((event: KeyboardEvent) => void) | null; + onKeyboardDidHide?: ((event: KeyboardEvent) => void) | null; + // LegendList's: content shorter than the list sits at its end, as justifyContent flex-end places it. + alignItemsAtEnd?: boolean; // false turns anchoring off. FlatList and LegendList objects map onto the same switch and top threshold. maintainVisibleContentPosition?: | boolean From 672adbfa3ba60cd2ef24db9c73d8c302d0fb861d Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 22:39:45 +0100 Subject: [PATCH 2/4] fix: align the near edge in scrollIndexIntoView when no row fits With no row fully in view, every target went to the start edge, so a row below the viewport scrolled past it: rows of 200, 50 and 50 at offset 50 in a 100 point viewport sent index 1 to offset 200 instead of 150. A row after the last one partly in view now aligns its end, as LegendList picks the edge by direction. --- android/src/main/java/me/sectiontn/flume/FlumeView.kt | 3 ++- android/src/main/java/me/sectiontn/flume/ScrollCommands.kt | 4 ++-- .../src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt | 7 +++++++ cpp/adapter/ScrollCommands.cpp | 4 ++-- cpp/adapter/ScrollCommands.h | 4 ++-- cpp/tests/scroll_commands_test.cpp | 6 ++++++ ios/FLMView.mm | 4 +++- 7 files changed, 24 insertions(+), 8 deletions(-) diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 26365d8..815c8a6 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -451,9 +451,10 @@ class FlumeView(context: Context) : FrameLayout(context) { val position = target.position(rows) val first = layoutManager.findFirstCompletelyVisibleItemPosition() val last = layoutManager.findLastCompletelyVisibleItemPosition() + val lastVisible = maxOf(layoutManager.findFirstVisibleItemPosition(), layoutManager.findLastVisibleItemPosition()) val viewPosition = when { position == null || target.waitsForData(rows) -> 1f - else -> IntoView.target(position, minOf(first, last), maxOf(first, last)) + else -> IntoView.target(position, minOf(first, last), maxOf(first, last), lastVisible) } if (viewPosition == null) { jumps.cancel()?.let { dropJump(it) } diff --git a/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt b/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt index 2df423b..59f449c 100644 --- a/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt +++ b/android/src/main/java/me/sectiontn/flume/ScrollCommands.kt @@ -39,8 +39,8 @@ class ScrollCommands { // The viewPosition that brings a row into view: 0 before the fully visible rows, 1 after them, null when it is one. object IntoView { - fun target(position: Int, firstFull: Int, lastFull: Int): Float? = when { - firstFull < 0 || lastFull < firstFull -> 0f + fun target(position: Int, firstFull: Int, lastFull: Int, lastVisible: Int = -1): Float? = when { + firstFull < 0 || lastFull < firstFull -> if (lastVisible >= 0 && position > lastVisible) 1f else 0f position < firstFull -> 0f position > lastFull -> 1f else -> null diff --git a/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt b/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt index 9f2ded9..095f64d 100644 --- a/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt +++ b/android/src/test/java/me/sectiontn/flume/ScrollCommandsTest.kt @@ -99,4 +99,11 @@ class ScrollCommandsTest { fun intoViewPutsTheRowAtTheStartWhenNoRowIsFullyInView() { assertEquals(0f, IntoView.target(4, -1, -1)) } + + @Test + fun intoViewAlignsTheEndOfARowBelowTheRowsPartlyInViewWhenNoneIsFullyInView() { + assertEquals(1f, IntoView.target(1, -1, -1, 0)) + assertEquals(0f, IntoView.target(0, -1, -1, 0)) + assertEquals(0f, IntoView.target(4, -1, -1, -1)) + } } diff --git a/cpp/adapter/ScrollCommands.cpp b/cpp/adapter/ScrollCommands.cpp index 63b766b..4b4d8a5 100644 --- a/cpp/adapter/ScrollCommands.cpp +++ b/cpp/adapter/ScrollCommands.cpp @@ -29,8 +29,8 @@ void ScrollCommands::reset() { namespace flume { -std::optional intoViewPosition(int position, int firstFull, int lastFull) { - if (firstFull < 0 || lastFull < firstFull) return 0.f; +std::optional intoViewPosition(int position, int firstFull, int lastFull, int lastVisible) { + if (firstFull < 0 || lastFull < firstFull) return lastVisible >= 0 && position > lastVisible ? 1.f : 0.f; if (position < firstFull) return 0.f; if (position > lastFull) return 1.f; return std::nullopt; diff --git a/cpp/adapter/ScrollCommands.h b/cpp/adapter/ScrollCommands.h index 4419b71..884e8b2 100644 --- a/cpp/adapter/ScrollCommands.h +++ b/cpp/adapter/ScrollCommands.h @@ -6,8 +6,8 @@ namespace flume { // The viewPosition that brings a row into view: 0 before the fully visible rows, 1 after them, none when it is one. -// Positions count list rows. With no row fully in view, the row goes to the start. -std::optional intoViewPosition(int position, int firstFull, int lastFull); +// Positions count list rows. With no row fully in view, a row after the last one partly in view goes to the end, others to the start. +std::optional intoViewPosition(int position, int firstFull, int lastFull, int lastVisible = -1); // The scroll command in flight: its id is reported once, when it settles at rest or is interrupted. class ScrollCommands { diff --git a/cpp/tests/scroll_commands_test.cpp b/cpp/tests/scroll_commands_test.cpp index f2a3b2e..8273079 100644 --- a/cpp/tests/scroll_commands_test.cpp +++ b/cpp/tests/scroll_commands_test.cpp @@ -91,3 +91,9 @@ TEST_CASE("IntoView scrolls with viewPosition 0 before the visible rows and 1 af TEST_CASE("IntoView puts the row at the start when no row is fully in view") { CHECK(intoViewPosition(4, -1, -1) == 0.f); } + +TEST_CASE("IntoView aligns the end of a row below the rows partly in view when none is fully in view") { + CHECK(intoViewPosition(1, -1, -1, 0) == 1.f); + CHECK(intoViewPosition(0, -1, -1, 0) == 0.f); + CHECK(intoViewPosition(4, -1, -1, -1) == 0.f); +} diff --git a/ios/FLMView.mm b/ios/FLMView.mm index 37e6881..bb13839 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -1956,14 +1956,16 @@ - (void)scrollIndexIntoView:(NSInteger)requestId const FLMViewport viewport = [_layout viewportFor:_collectionView.bounds]; int firstFull = INT_MAX; int lastFull = -1; + int lastVisible = -1; for (const flume::ItemSpan &span : [_layout spansIn:viewport]) { + lastVisible = std::max(lastVisible, span.index); if (span.start >= -0.5f && span.end <= viewport.length + 0.5f) { firstFull = std::min(firstFull, span.index); lastFull = std::max(lastFull, span.index); } } const int position = _rows.position(*flume::clampIndex(static_cast(index), _rows.dataCount)); - viewPosition = flume::intoViewPosition(position, lastFull < 0 ? -1 : firstFull, lastFull); + viewPosition = flume::intoViewPosition(position, lastFull < 0 ? -1 : firstFull, lastFull, lastVisible); } if (!viewPosition) { [self dropJump]; From 8587cf6350c469aa598d6c4f34980d5268e521a4 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 22:40:00 +0100 Subject: [PATCH 3/4] fix: read the committed data and keyboard handler, not a render's scrollToItem and scrollItemIntoView looked items up in the data of the latest render, and keyboard events called the latest render's handler. A render React throws away (a suspended transition) still wrote both, so with a, b on screen and b, a suspended, scrollToItem(b) scrolled to the row showing a. Both now update in a layout effect, when the render commits. --- src/Flume.tsx | 9 +++- src/__tests__/Flume.test.tsx | 79 ++++++++++++++++++++++++++++++++++++ src/keyboard.ts | 8 ++-- 3 files changed, 91 insertions(+), 5 deletions(-) diff --git a/src/Flume.tsx b/src/Flume.tsx index 03cc3c0..2a4a567 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -164,6 +164,11 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { count.current = data.length; const dataRef = useRef(data); dataRef.current = data; + // The data of the last commit, which native shows: a render React throws away never reaches it. + const shownData = useRef(data); + useLayoutEffect(() => { + shownData.current = data; + }, [data]); // The keys separators.highlight reads when called, so the row before is the latest one. const separatorKeys = useRef<{ keys: readonly string[]; index: ReadonlyMap }>({ keys: [], @@ -539,9 +544,9 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { index, method, ); - // FlatList finds the item by identity in the data it rendered last. + // FlatList finds the item by identity in the data it shows, its committed props. const found = (item: unknown, scroll: (index: number) => Promise) => { - const index = dataRef.current.indexOf(item); + const index = shownData.current.indexOf(item); return index < 0 ? Promise.resolve() : scroll(index); }; return { diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index a66be4e..4b9614c 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -1047,6 +1047,49 @@ describe('Flume ref', () => { expect(Commands.scrollToIndex).not.toHaveBeenCalled(); }); + it('scrollToItem finds the item in the data on screen while a newer render suspends', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const ref = createRef(); + const first = { id: 'a' }; + const second = { id: 'b' }; + const never = new Promise(() => {}); + const Gate = ({ open }: { open: boolean }) => { + if (!open) throw never; + return null; + }; + const element = (list: { id: string }[], open: boolean) => + createElement( + Suspense, + { fallback: null }, + createElement(Flume, { ref, data: list, renderCell }), + createElement(Gate, { open }), + ); + let tree: ReactTestRenderer | undefined; + await act(async () => { + tree = create(element([first, second], true), { + createNodeMock: () => ({}), + unstable_isConcurrent: true, + } as Parameters[1]); + }); + // React keeps a, b on screen and throws the render of b, a away. + await act(async () => { + startTransition(() => { + tree?.update(element([second, first], false)); + }); + }); + ref.current?.scrollToItem({ item: second }); + expect(Commands.scrollToIndex).toHaveBeenCalledWith( + expect.anything(), + expect.anything(), + 1, + true, + 0, + 0, + ); + }); + it('scrollToTop scrolls to offset 0', async () => { installHost(); const { Flume } = await import('../Flume'); @@ -1128,6 +1171,42 @@ describe('Flume keyboard events', () => { expect(Keyboard.addListener).not.toHaveBeenCalled(); }); + it('calls the keyboard handler on screen while a newer render suspends', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Keyboard } = await import('react-native'); + const shown = vi.fn(); + const thrownAway = vi.fn(); + const never = new Promise(() => {}); + const Gate = ({ open }: { open: boolean }) => { + if (!open) throw never; + return null; + }; + const element = (handler: () => void, open: boolean) => + createElement( + Suspense, + { fallback: null }, + createElement(Flume, { data: [item], renderCell, onKeyboardDidShow: handler }), + createElement(Gate, { open }), + ); + let tree: ReactTestRenderer | undefined; + await act(async () => { + tree = create(element(shown, true), { + createNodeMock: () => ({}), + unstable_isConcurrent: true, + } as Parameters[1]); + }); + await act(async () => { + startTransition(() => { + tree?.update(element(thrownAway, false)); + }); + }); + const calls = vi.mocked(Keyboard.addListener).mock.calls; + (calls[0] as unknown as [string, (event: unknown) => void])[1]({}); + expect(shown).toHaveBeenCalledTimes(1); + expect(thrownAway).not.toHaveBeenCalled(); + }); + it('removes the keyboard subscription on unmount', async () => { installHost(); const { Flume } = await import('../Flume'); diff --git a/src/keyboard.ts b/src/keyboard.ts index 76cc7cc..1d94da4 100644 --- a/src/keyboard.ts +++ b/src/keyboard.ts @@ -1,13 +1,15 @@ -import { useEffect, useRef } from 'react'; +import { useEffect, useLayoutEffect, useRef } from 'react'; import { Keyboard, type KeyboardEvent, type KeyboardEventName } from 'react-native'; -// Subscribes only while a handler is given, and calls the latest one without subscribing again. +// Subscribes only while a handler is given, and calls the latest committed one without subscribing again. export function useKeyboardEvent( name: KeyboardEventName, handler: ((event: KeyboardEvent) => void) | null | undefined, ): void { const latest = useRef(handler); - latest.current = handler; + useLayoutEffect(() => { + latest.current = handler; + }, [handler]); const given = handler != null; useEffect(() => { if (!given) return undefined; From c9794acde224d9cf87ad04f0b2d01430cef7365f Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 28 Nov 2026 22:45:41 +0100 Subject: [PATCH 4/4] fix: stop the earlier glide when scrollIndexIntoView needs no scroll A row already in view ended the command where the list was, but an earlier command kept going: a glide toward offset 4000 carried the row off screen, and on Android a pending realign could pull the list back to an older target. That path now stops the glide and drops the realign, as every other scroll command does first. --- android/src/main/java/me/sectiontn/flume/FlumeView.kt | 3 +++ ios/FLMView.mm | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 815c8a6..842f47f 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -457,8 +457,11 @@ class FlumeView(context: Context) : FrameLayout(context) { else -> IntoView.target(position, minOf(first, last), maxOf(first, last), lastVisible) } if (viewPosition == null) { + // As any new scroll does: an earlier command's realign or glide must not move the row back out. + pendingAlign = null jumps.cancel()?.let { dropJump(it) } forgetLanding() + recycler.stopScroll() landCommand() return } diff --git a/ios/FLMView.mm b/ios/FLMView.mm index bb13839..e8af3b6 100644 --- a/ios/FLMView.mm +++ b/ios/FLMView.mm @@ -1970,6 +1970,13 @@ - (void)scrollIndexIntoView:(NSInteger)requestId if (!viewPosition) { [self dropJump]; _pendingTarget.reset(); + // An earlier command's glide stops where it is, as on Android, so it cannot carry the row back out. + if (_gliding) { + _gliding = NO; + _replacingGlide = YES; + [_collectionView setContentOffset:_collectionView.contentOffset animated:NO]; + _replacingGlide = NO; + } [self landCommand]; return; }