From 03f79a7033c2d634c067c02e1beba3ac2d0623ab Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 20 Nov 2026 23:24:58 +0100 Subject: [PATCH 01/14] fix: accept null data and null callbacks --- src/Flume.tsx | 5 +++-- src/__tests__/Flume.test.tsx | 35 ++++++++++++++++++++++++++++++ src/__tests__/props.test.ts | 7 ++++++ src/cells.ts | 7 +++--- src/props.ts | 41 +++++++++++++++++++++++++++++++++++- src/types.ts | 39 +++++++++++++++++----------------- 6 files changed, 108 insertions(+), 26 deletions(-) diff --git a/src/Flume.tsx b/src/Flume.tsx index a3dd56e..2f49df5 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -19,7 +19,7 @@ import { createSerializable } from 'react-native-worklets'; import { cellKinds, type ResolvedCell, resolveCell } from './cells'; import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data'; import { FlumeSlot } from './FlumeSlot'; -import { contentPadding, nativeProps, stickyIndicesOf } from './props'; +import { contentPadding, nativeProps, stickyIndicesOf, withoutNulls } from './props'; import { applySnapshot, gridCellWidth, @@ -48,7 +48,8 @@ function componentElement( return isValidElement(component) ? component : createElement(component); } -function FlumeInner(props: FlumeProps, ref: Ref): ReactElement { +function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { + const props = withoutNulls(given); const { data, renderCell, diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index d93eed0..e82a003 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -261,6 +261,41 @@ describe('Flume props', () => { expect(calls).toHaveLength(1); }); + it('renders an empty list for null and undefined data', async () => { + const host = installHost(); + const { Flume } = await import('../Flume'); + const renderItem = () => null; + const tree = await mount(createElement(Flume, { data: null, renderItem })); + for (const data of [undefined, [item], null]) { + await act(async () => { + tree.update(createElement(Flume, { data, renderItem })); + }); + } + expect(host.data.at(-1)?.keys).toEqual([]); + expect(host.data.some((call) => call.keys.includes('a'))).toBe(true); + expect(new Set(host.data.map((call) => call.storeId)).size).toBe(1); + }); + + it('treats null callbacks as not given', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const tree = await mount( + createElement(Flume, { + data: [item], + renderCell, + onEndReached: null, + onRefresh: null, + onViewableItemsChanged: null, + onPress: null, + }), + ); + const native = tree.root.find((node) => String(node.type) === 'FlumeView'); + expect(native.props.onEndReached).toBeUndefined(); + expect(native.props.onRefresh).toBeUndefined(); + expect(native.props.onViewableItemsChanged).toBeUndefined(); + expect(native.props.onCellPress).toBeUndefined(); + }); + it('registers a reporter in development', async () => { const host = installHost(); const error = vi.spyOn(console, 'error').mockImplementation(() => {}); diff --git a/src/__tests__/props.test.ts b/src/__tests__/props.test.ts index b11e141..b0fa921 100644 --- a/src/__tests__/props.test.ts +++ b/src/__tests__/props.test.ts @@ -120,6 +120,13 @@ describe('nativeProps viewability', () => { }); describe('nativeProps refresh', () => { + it('treats null data and null callbacks as not given', () => { + expect(nativeProps({ data: null, onRefresh: null, onScroll: null }, vi.fn())).toMatchObject({ + refreshEnabled: false, + emitScrollEvents: false, + }); + }); + it('enables refresh only with onRefresh', () => { const warn = vi.fn(); expect(nativeProps({ data: [], refreshing: true }, warn).refreshEnabled).toBe(false); diff --git a/src/cells.ts b/src/cells.ts index aac62c5..370ecdc 100644 --- a/src/cells.ts +++ b/src/cells.ts @@ -1,4 +1,5 @@ -import type { FlumeProps, ReactCell } from './types'; +import type { SettledProps } from './props'; +import type { ReactCell } from './types'; export type ResolvedCell = | { kind: 'worklet' } @@ -7,7 +8,7 @@ export type ResolvedCell = export type CellKinds = { reactByDefault: boolean; reactTypes: string[]; signature: string }; -type Renderers = Pick, 'renderCell' | 'renderItem' | 'reactCells'>; +type Renderers = Pick, 'renderCell' | 'renderItem' | 'reactCells'>; function reactCellFor(reactCells: Renderers['reactCells'], type: string) { return reactCells !== undefined && Object.hasOwn(reactCells, type) ? reactCells[type] : undefined; @@ -23,7 +24,7 @@ export function resolveCell(type: string, props: Renderers): ResolvedCell< } // What native needs to give each type a holder of the right kind; the signature keys memos on it. -export function cellKinds(props: Pick, 'renderCell' | 'reactCells'>): CellKinds { +export function cellKinds(props: Pick, 'renderCell' | 'reactCells'>): CellKinds { const reactCells = props.reactCells ?? {}; const reactTypes = Object.keys(reactCells) .filter((type) => reactCells[type] !== undefined) diff --git a/src/props.ts b/src/props.ts index 20797fe..0579887 100644 --- a/src/props.ts +++ b/src/props.ts @@ -151,7 +151,46 @@ export function stickyIndicesOf(indices: readonly number[] | undefined): number[ return [...new Set(indices ?? [])].filter((index) => index >= 0).sort((a, b) => a - b); } -export function nativeProps(props: FlumeProps, warn: Warn): FlatProps { +// FlashList and LegendList type these as nullable, where null means not given. +const NULLABLE = [ + 'renderCell', + 'renderItem', + 'keyExtractor', + 'getItemType', + 'onPress', + 'onLongPress', + 'onScroll', + 'onScrollBeginDrag', + 'onScrollEndDrag', + 'onMomentumScrollBegin', + 'onMomentumScrollEnd', + 'onViewableItemsChanged', + 'onEndReached', + 'onStartReached', + 'onRefresh', + 'onLayout', +] as const; + +type Nullable = (typeof NULLABLE)[number]; + +export type SettledProps = Omit, 'data' | Nullable> & { + data: readonly T[]; +} & { [K in Nullable]?: NonNullable[K]> }; + +const EMPTY: readonly never[] = []; + +// The props with data defaulted and null callbacks removed, the same object when nothing is null. +export function withoutNulls(props: FlumeProps): SettledProps { + if (props.data != null && NULLABLE.every((key) => props[key] !== null)) { + return props as SettledProps; + } + const settled: Record = { ...props, data: props.data ?? EMPTY }; + for (const key of NULLABLE) if (settled[key] === null) delete settled[key]; + return settled as SettledProps; +} + +export function nativeProps(given: FlumeProps, warn: Warn): FlatProps { + const props = withoutNulls(given); const horizontal = props.horizontal === true; let numColumns = props.numColumns ?? 1; if (horizontal && numColumns > 1) { diff --git a/src/types.ts b/src/types.ts index 70c874d..0be2746 100644 --- a/src/types.ts +++ b/src/types.ts @@ -200,18 +200,18 @@ export type CellInfo = { export type ReactCell = (info: CellInfo) => ReactElement | null; export type FlumeProps = { - data: readonly T[]; - renderCell?: (item: T, index: number) => CellNode; + data: readonly T[] | null | undefined; + renderCell?: ((item: T, index: number) => CellNode) | null; // The React renderer for every type without a worklet cell or a reactCells entry. - renderItem?: ReactCell; + renderItem?: ReactCell | null; // React renderers by item type; they take precedence over renderCell. reactCells?: Record>; - keyExtractor?: (item: T, index: number) => string; - getItemType?: (item: T, index: number) => string; + keyExtractor?: ((item: T, index: number) => string) | null; + getItemType?: ((item: T, index: number) => string) | null; extraData?: unknown; itemAnimations?: boolean; - onPress?: (info: PressInfo) => void; - onLongPress?: (info: PressInfo) => void; + onPress?: ((info: PressInfo) => void) | null; + onLongPress?: ((info: PressInfo) => void) | null; style?: StyleProp; horizontal?: boolean; numColumns?: number; @@ -232,23 +232,22 @@ export type FlumeProps = { ListFooterComponent?: ComponentType | ReactElement | null; ListEmptyComponent?: ComponentType | ReactElement | null; // The ScrollView events with the ScrollView payload; contentOffset counts from the content start. - onScroll?: ScrollHandler; - onScrollBeginDrag?: ScrollHandler; - onScrollEndDrag?: ScrollHandler; - onMomentumScrollBegin?: ScrollHandler; - onMomentumScrollEnd?: ScrollHandler; + onScroll?: ScrollHandler | null; + onScrollBeginDrag?: ScrollHandler | null; + onScrollEndDrag?: ScrollHandler | null; + onMomentumScrollBegin?: ScrollHandler | null; + onMomentumScrollEnd?: ScrollHandler | null; scrollEventThrottle?: number; - onViewableItemsChanged?: (info: { - viewableItems: ViewToken[]; - changed: ViewToken[]; - }) => void; + onViewableItemsChanged?: + | ((info: { viewableItems: ViewToken[]; changed: ViewToken[] }) => void) + | null; viewabilityConfig?: ViewabilityConfig; - onEndReached?: (info: { distanceFromEnd: number }) => void; + onEndReached?: ((info: { distanceFromEnd: number }) => void) | null; onEndReachedThreshold?: number; - onStartReached?: (info: { distanceFromStart: number }) => void; + onStartReached?: ((info: { distanceFromStart: number }) => void) | null; onStartReachedThreshold?: number; refreshing?: boolean; - onRefresh?: () => void; + onRefresh?: (() => void) | null; // tintColor is iOS, colors are Android; progressViewOffset moves the spinner on both. refreshControl?: { tintColor?: string; colors?: string[]; progressViewOffset?: number }; scrollEnabled?: boolean; @@ -267,7 +266,7 @@ export type FlumeProps = { keyboardDismissMode?: 'none' | 'on-drag' | 'interactive'; keyboardShouldPersistTaps?: 'always' | 'never' | 'handled'; maintainVisibleContentPosition?: MaintainVisibleContentPosition; - onLayout?: (event: LayoutChangeEvent) => void; + onLayout?: ((event: LayoutChangeEvent) => void) | null; testID?: string; accessibilityLabel?: string; }; From 4297516bf6fd77779d1c05282c0648b2bdfcc7c4 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 20 Nov 2026 23:25:51 +0100 Subject: [PATCH 02/14] fix: accept numeric item types --- src/__tests__/data.test.ts | 11 +++++++++++ src/data.ts | 5 +++-- src/types.ts | 2 +- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/__tests__/data.test.ts b/src/__tests__/data.test.ts index 9fd838e..3f59940 100644 --- a/src/__tests__/data.test.ts +++ b/src/__tests__/data.test.ts @@ -141,6 +141,17 @@ describe('diffData types for native', () => { expect([...d.typeIds]).toEqual([0, 1, 0]); expect(d.typeIds).toBeInstanceOf(Int32Array); }); + + it('turns numeric item types into strings', () => { + const items = [ + { id: 'a', t: 1 }, + { id: 'b', t: '1' }, + { id: 'c', t: undefined }, + ]; + const d = diffData(undefined, items, undefined, (i) => i.t); + expect(d.typeTable).toEqual(['1', 'default']); + expect([...d.typeIds]).toEqual([0, 0, 1]); + }); }); describe('diffData with many types', () => { diff --git a/src/data.ts b/src/data.ts index cf5c743..ebe4b6e 100644 --- a/src/data.ts +++ b/src/data.ts @@ -1,5 +1,5 @@ export type KeyExtractor = (item: T, index: number) => string; -export type TypeExtractor = (item: T, index: number) => string; +export type TypeExtractor = (item: T, index: number) => string | number | undefined; // Index-aligned arrays plus one key-to-index map; look up by key through itemOf and typeOf. export type DataState = { @@ -116,7 +116,8 @@ function scan( } index.set(key, i); keys[i] = key; - const type = getItemType?.(item, i) ?? 'default'; + const raw = getItemType?.(item, i); + const type = raw === undefined ? 'default' : typeof raw === 'string' ? raw : String(raw); types[i] = type; // Lists switch type often and have few types: a short table is searched in place, a long one through the map. if (type !== idType) { diff --git a/src/types.ts b/src/types.ts index 0be2746..85a3901 100644 --- a/src/types.ts +++ b/src/types.ts @@ -207,7 +207,7 @@ export type FlumeProps = { // React renderers by item type; they take precedence over renderCell. reactCells?: Record>; keyExtractor?: ((item: T, index: number) => string) | null; - getItemType?: ((item: T, index: number) => string) | null; + getItemType?: ((item: T, index: number) => string | number | undefined) | null; extraData?: unknown; itemAnimations?: boolean; onPress?: ((info: PressInfo) => void) | null; From f1b93aa1a77e343a48acc44734eefdb5a4888b9e Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 20 Nov 2026 23:28:17 +0100 Subject: [PATCH 03/14] feat: accept a RefreshControl element in refreshControl --- src/Flume.tsx | 7 +++--- src/__tests__/Flume.test.tsx | 34 ++++++++++++++++++++++++++++ src/__tests__/props.test.ts | 32 ++++++++++++++++++++++++++- src/props.ts | 43 +++++++++++++++++++++++++++++++----- src/types.ts | 9 ++++++-- 5 files changed, 113 insertions(+), 12 deletions(-) diff --git a/src/Flume.tsx b/src/Flume.tsx index 2f49df5..75c253a 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -19,7 +19,7 @@ import { createSerializable } from 'react-native-worklets'; import { cellKinds, type ResolvedCell, resolveCell } from './cells'; import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data'; import { FlumeSlot } from './FlumeSlot'; -import { contentPadding, nativeProps, stickyIndicesOf, withoutNulls } from './props'; +import { contentPadding, nativeProps, refreshOf, stickyIndicesOf, withoutNulls } from './props'; import { applySnapshot, gridCellWidth, @@ -80,9 +80,10 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { onViewableItemsChanged, onEndReached, onStartReached, - onRefresh, keyboardShouldPersistTaps, } = props; + const refresh = refreshOf(props); + const { onRefresh } = refresh; const host = getHost(); // StrictMode calls a state initializer twice and drops one result, so the first store is reused. const firstStore = useRef(null); @@ -95,7 +96,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { const warned = useRef({ duplicates: false, messages: new Set() }); const nativeRef = useRef>(null); // React Native's RefreshControl rule: a pull starts native refreshing, so an unchanged prop is sent back. - const wantsRefreshing = props.refreshing === true; + const wantsRefreshing = refresh.refreshing; const nativeRefreshing = useRef(wantsRefreshing); const lastRefreshing = useRef(wantsRefreshing); const [, afterRefresh] = useReducer((n: number) => n + 1, 0); diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index e82a003..ead2709 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -115,6 +115,8 @@ function installHost() { const item = { id: 'a' }; const renderCell = () => ({ type: 'view' as const }); +// Stands in for React Native's RefreshControl, which the react-native mock does not provide. +const RefreshControlStub = (_props: { refreshing: boolean; onRefresh?: () => void }) => null; // Host refs resolve to a stub, as a native view would, so the ref commands have a target. async function mount(element: Parameters[0]): Promise { @@ -843,6 +845,38 @@ describe('Flume refresh', () => { expect(Commands.setNativeRefreshing).toHaveBeenCalledWith(expect.anything(), false); }); + it('drives refresh from a RefreshControl element', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Commands } = await import('../specs/FlumeViewNativeComponent'); + const fromElement = vi.fn(); + const fromProp = vi.fn(); + const control = (refreshing: boolean) => + createElement(RefreshControlStub, { refreshing, onRefresh: fromElement }); + const tree = await mount( + createElement(Flume, { + data: [item], + renderCell, + onRefresh: fromProp, + refreshControl: control(true), + }), + ); + const native = () => tree.root.find((node) => String(node.type) === 'FlumeView'); + expect(native().props).toMatchObject({ refreshEnabled: true, refreshing: true }); + await act(async () => { + tree.update( + createElement(Flume, { data: [item], renderCell, refreshControl: control(false) }), + ); + }); + expect(native().props.refreshing).toBe(false); + await act(async () => { + native().props.onRefresh(); + }); + expect(fromElement).toHaveBeenCalledTimes(1); + expect(fromProp).not.toHaveBeenCalled(); + expect(Commands.setNativeRefreshing).toHaveBeenCalledWith(expect.anything(), false); + }); + it('sends nothing when onRefresh sets refreshing', async () => { installHost(); const { Flume } = await import('../Flume'); diff --git a/src/__tests__/props.test.ts b/src/__tests__/props.test.ts index b0fa921..ef7e7d3 100644 --- a/src/__tests__/props.test.ts +++ b/src/__tests__/props.test.ts @@ -1,5 +1,10 @@ +import { createElement } from 'react'; +import type { RefreshControlProps } from 'react-native'; import { describe, expect, it, vi } from 'vitest'; -import { contentPadding, nativeProps, stickyIndicesOf } from '../props'; +import { contentPadding, nativeProps, refreshOf, stickyIndicesOf } from '../props'; + +// Stands in for React Native's RefreshControl. +const RefreshControlStub = (_props: RefreshControlProps) => null; describe('contentPadding', () => { it('resolves the padding shorthands like React Native', () => { @@ -127,6 +132,31 @@ describe('nativeProps refresh', () => { }); }); + it('reads refresh from a RefreshControl element, which wins over onRefresh', () => { + const fromElement = () => {}; + const element = createElement(RefreshControlStub, { + refreshing: true, + onRefresh: fromElement, + colors: ['red'], + tintColor: 'blue', + progressViewOffset: 20, + }); + expect(refreshOf({ data: [], onRefresh: () => {}, refreshControl: element })).toEqual({ + onRefresh: fromElement, + refreshing: true, + colors: ['red'], + tintColor: 'blue', + progressViewOffset: 20, + }); + }); + + it('reads the config object of 0.1 with the top-level props', () => { + const onRefresh = () => {}; + expect( + refreshOf({ data: [], onRefresh, refreshing: false, refreshControl: { colors: ['red'] } }), + ).toEqual({ onRefresh, refreshing: false, colors: ['red'], progressViewOffset: 0 }); + }); + it('enables refresh only with onRefresh', () => { const warn = vi.fn(); expect(nativeProps({ data: [], refreshing: true }, warn).refreshEnabled).toBe(false); diff --git a/src/props.ts b/src/props.ts index 0579887..be53d11 100644 --- a/src/props.ts +++ b/src/props.ts @@ -1,4 +1,5 @@ -import type { StyleProp, ViewStyle } from 'react-native'; +import { isValidElement } from 'react'; +import type { ColorValue, RefreshControlProps, StyleProp, ViewStyle } from 'react-native'; import type { NativeProps } from './specs/FlumeViewNativeComponent'; import type { FlumeProps, ViewabilityConfig } from './types'; @@ -151,6 +152,35 @@ export function stickyIndicesOf(indices: readonly number[] | undefined): number[ return [...new Set(indices ?? [])].filter((index) => index >= 0).sort((a, b) => a - b); } +export type Refresh = { + onRefresh?: () => void; + refreshing: boolean; + colors?: ReadonlyArray; + tintColor?: ColorValue; + progressViewOffset: number; +}; + +// As in VirtualizedList, a RefreshControl element replaces the list's own, so its props win. +export function refreshOf(props: FlumeProps): Refresh { + const control = props.refreshControl; + if (isValidElement(control)) { + const given = control.props; + return { + onRefresh: given.onRefresh ?? undefined, + refreshing: given.refreshing === true, + colors: given.colors, + tintColor: given.tintColor, + progressViewOffset: given.progressViewOffset ?? 0, + }; + } + return { + onRefresh: props.onRefresh ?? undefined, + refreshing: props.refreshing === true, + colors: control?.colors, + tintColor: control?.tintColor, + progressViewOffset: control?.progressViewOffset ?? 0, + }; +} // FlashList and LegendList type these as nullable, where null means not given. const NULLABLE = [ 'renderCell', @@ -191,6 +221,7 @@ export function withoutNulls(props: FlumeProps): SettledProps { export function nativeProps(given: FlumeProps, warn: Warn): FlatProps { const props = withoutNulls(given); + const refresh = refreshOf(props); const horizontal = props.horizontal === true; let numColumns = props.numColumns ?? 1; if (horizontal && numColumns > 1) { @@ -236,10 +267,10 @@ export function nativeProps(given: FlumeProps, warn: Warn): FlatProps { viewabilityConfig: viewability(props.viewabilityConfig, warn), endReachedThreshold: props.onEndReachedThreshold ?? 2, startReachedThreshold: props.onStartReachedThreshold ?? 2, - refreshEnabled: props.onRefresh !== undefined, - refreshing: props.refreshing === true, - refreshColors: props.refreshControl?.colors, - refreshProgressViewOffset: props.refreshControl?.progressViewOffset ?? 0, + refreshEnabled: refresh.onRefresh !== undefined, + refreshing: refresh.refreshing, + refreshColors: refresh.colors, + refreshProgressViewOffset: refresh.progressViewOffset, scrollEnabled: props.scrollEnabled !== false, nestedScrollEnabled: props.nestedScrollEnabled === true, overScrollMode: props.overScrollMode ?? 'auto', @@ -251,7 +282,7 @@ export function nativeProps(given: FlumeProps, warn: Warn): FlatProps { contentInsetAdjustmentBehavior: props.contentInsetAdjustmentBehavior ?? 'never', bounces: props.bounces !== false, alwaysBounceVertical: props.alwaysBounceVertical ?? !horizontal, - refreshTintColor: props.refreshControl?.tintColor, + refreshTintColor: refresh.tintColor, keyboardDismissMode: props.keyboardDismissMode ?? 'none', keyboardShouldPersistTaps: props.keyboardShouldPersistTaps ?? 'never', rowsPressable: props.onPress !== undefined || props.onLongPress !== undefined, diff --git a/src/types.ts b/src/types.ts index 85a3901..9c965eb 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,9 +1,11 @@ import type { ComponentType, ReactElement } from 'react'; import type { + ColorValue, Insets, LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent, + RefreshControlProps, StyleProp, ViewStyle, } from 'react-native'; @@ -248,8 +250,11 @@ export type FlumeProps = { onStartReachedThreshold?: number; refreshing?: boolean; onRefresh?: (() => void) | null; - // tintColor is iOS, colors are Android; progressViewOffset moves the spinner on both. - refreshControl?: { tintColor?: string; colors?: string[]; progressViewOffset?: number }; + // A RefreshControl element, or the spinner style alone (tintColor on iOS, colors on Android). + refreshControl?: + | ReactElement + | { tintColor?: ColorValue; colors?: ReadonlyArray; progressViewOffset?: number } + | null; scrollEnabled?: boolean; nestedScrollEnabled?: boolean; overScrollMode?: 'auto' | 'always' | 'never'; From b554fe0f1744036ea574deecf2706ac1b3c68694 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 20 Nov 2026 23:32:11 +0100 Subject: [PATCH 04/14] feat!: read autoscrollToTopThreshold in points and accept every anchoring shape autoscrollToTopThreshold was read in viewports, so a FlatList or FlashList value of 100 asked for 100 screens. It is now in points, as in both of them. maintainVisibleContentPosition also takes false to turn anchoring off, and the FlatList and LegendList objects. --- README.md | 4 +-- .../java/me/sectiontn/flume/ContentAnchor.kt | 8 ++--- .../me/sectiontn/flume/FlumeViewManager.kt | 3 +- .../me/sectiontn/flume/AnchorPolicyTest.kt | 12 +++++-- cpp/adapter/ContentAnchor.cpp | 2 +- cpp/adapter/ContentAnchor.h | 4 +-- cpp/tests/content_anchor_test.cpp | 12 +++++-- src/__tests__/Flume.test.tsx | 24 ++++++++++++++ src/__tests__/props.test.ts | 20 ++++++++++++ src/props.ts | 31 ++++++++++++++----- src/types.ts | 23 ++++++++++++-- 11 files changed, 119 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 9c98a5d..ea9bfd1 100644 --- a/README.md +++ b/README.md @@ -114,14 +114,14 @@ Layout: | `estimatedItemSize` | `number` | The mean of the item's type, at least 50 | Sets the length in dp that a React row takes until it's measured. | | `drawDistance` | `number` | One screen | Sets how far past the screen edges, in dp, rows are prepared ahead of scrolling. | | `initialScrollIndex` | `number` | | Opens the list at this item. | -| `maintainVisibleContentPosition` | `MaintainVisibleContentPosition` | On | Keeps the visible rows in place when items are added above them. | +| `maintainVisibleContentPosition` | `boolean \| MaintainVisibleContentPosition` | On | Keeps the visible rows in place when items are added above them. Pass `false` to turn it off. | `maintainVisibleContentPosition` takes these options: | Prop | Type | Default | Description | | --- | --- | --- | --- | | `disabled` | `boolean` | `false` | Turns the behavior off. | -| `autoscrollToTopThreshold` | `number` | | Scrolls to new items at the top when the list is this many screens from the top. | +| `autoscrollToTopThreshold` | `number` | | Scrolls to new items at the top when the list is within this many points of the top. | | `autoscrollToBottomThreshold` | `number` | | Scrolls to new items at the bottom when the list is this many screens from the bottom. | | `animateAutoScrollToBottom` | `boolean` | `true` | Animates the scroll to new items at the bottom. | | `startRenderingFromBottom` | `boolean` | `false` | Opens the list at its last item. | diff --git a/android/src/main/java/me/sectiontn/flume/ContentAnchor.kt b/android/src/main/java/me/sectiontn/flume/ContentAnchor.kt index 37c0cad..fa44f63 100644 --- a/android/src/main/java/me/sectiontn/flume/ContentAnchor.kt +++ b/android/src/main/java/me/sectiontn/flume/ContentAnchor.kt @@ -1,9 +1,9 @@ package me.sectiontn.flume -// FlashList's shape: thresholds are fractions of the viewport, measured at the visual edges. +// FlashList's shape, measured at the visual edges: the top threshold in pixels, the bottom one in viewports. data class AnchorConfig( val disabled: Boolean = false, - val autoscrollToTopThreshold: Double? = null, + val autoscrollToTopThresholdPx: Double? = null, val autoscrollToBottomThreshold: Double? = null, val animateAutoScrollToBottom: Boolean = true, val startRenderingFromBottom: Boolean = false, @@ -43,8 +43,8 @@ object AnchorPolicy { return AnchorDecision(restore = kept, scrollTo = VisualEdge.BOTTOM, animated = config.animateAutoScrollToBottom) } // React Native's ScrollView always animates to the top. - val top = config.autoscrollToTopThreshold - if (top != null && insertedAtVisualTop && before.distanceToVisualTopPx <= top * before.viewportPx) { + val top = config.autoscrollToTopThresholdPx + if (top != null && insertedAtVisualTop && before.distanceToVisualTopPx <= top) { return AnchorDecision(restore = kept, scrollTo = VisualEdge.TOP, animated = true) } return if (anchorLost) restore else AnchorDecision() diff --git a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt index d29a9c5..ddaf121 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt @@ -4,6 +4,7 @@ import android.view.View import com.facebook.react.bridge.ReadableArray import com.facebook.react.bridge.ReadableMap import com.facebook.react.module.annotations.ReactModule +import com.facebook.react.uimanager.PixelUtil import com.facebook.react.uimanager.ReactStylesDiffMap import com.facebook.react.uimanager.StateWrapper import com.facebook.react.uimanager.ThemedReactContext @@ -173,7 +174,7 @@ class FlumeViewManager : ViewGroupManager(), FlumeViewManagerInterfac override fun setMaintainVisibleContentPosition(view: FlumeView, value: ReadableMap?) { view.anchorConfig = AnchorConfig( disabled = value.boolOr("disabled", false), - autoscrollToTopThreshold = value.doubleOrNull("autoscrollToTopThreshold"), + autoscrollToTopThresholdPx = value.doubleOrNull("autoscrollToTopThreshold")?.let { PixelUtil.toPixelFromDIP(it).toDouble() }, autoscrollToBottomThreshold = value.doubleOrNull("autoscrollToBottomThreshold"), animateAutoScrollToBottom = value.boolOr("animateAutoScrollToBottom", true), startRenderingFromBottom = value.boolOr("startRenderingFromBottom", false), diff --git a/android/src/test/java/me/sectiontn/flume/AnchorPolicyTest.kt b/android/src/test/java/me/sectiontn/flume/AnchorPolicyTest.kt index 8a6aa86..bdb5a0c 100644 --- a/android/src/test/java/me/sectiontn/flume/AnchorPolicyTest.kt +++ b/android/src/test/java/me/sectiontn/flume/AnchorPolicyTest.kt @@ -20,10 +20,18 @@ class AnchorPolicyTest { } @Test fun anInsertAtTheTopWithinTheThresholdScrollsThereAlwaysAnimated() { - val config = AnchorConfig(autoscrollToTopThreshold = 1.0, animateAutoScrollToBottom = false) + val config = AnchorConfig(autoscrollToTopThresholdPx = 900.0, animateAutoScrollToBottom = false) assertEquals(AnchorDecision(scrollTo = VisualEdge.TOP, animated = true), AnchorPolicy.decide(config, before, true, false)) } + @Test fun aTopThresholdIsInPixels() { + assertEquals( + AnchorDecision(scrollTo = VisualEdge.TOP, animated = true), + AnchorPolicy.decide(AnchorConfig(autoscrollToTopThresholdPx = 900.0), before, true, false), + ) + assertEquals(AnchorDecision(), AnchorPolicy.decide(AnchorConfig(autoscrollToTopThresholdPx = 899.0), before, true, false)) + } + @Test fun aChangeThatRemovesEveryLaidOutRowKeepsThePosition() { assertEquals(AnchorDecision(restore = 3 to -12), AnchorPolicy.decide(AnchorConfig(), before, true, false, anchorLost = true)) } @@ -34,7 +42,7 @@ class AnchorPolicyTest { AnchorDecision(restore = 3 to -12, scrollTo = VisualEdge.BOTTOM, animated = true), AnchorPolicy.decide(bottom, before, false, true, anchorLost = true), ) - val top = AnchorConfig(autoscrollToTopThreshold = 1.0) + val top = AnchorConfig(autoscrollToTopThresholdPx = 900.0) assertEquals( AnchorDecision(restore = 3 to -12, scrollTo = VisualEdge.TOP, animated = true), AnchorPolicy.decide(top, before, true, false, anchorLost = true), diff --git a/cpp/adapter/ContentAnchor.cpp b/cpp/adapter/ContentAnchor.cpp index 5ae6620..23a1cf2 100644 --- a/cpp/adapter/ContentAnchor.cpp +++ b/cpp/adapter/ContentAnchor.cpp @@ -11,7 +11,7 @@ AnchorDecision decideAnchor(const AnchorConfig& config, const AnchorState& befor } // React Native's iOS ScrollView always animates to the top. const double top = config.autoscrollToTopThreshold; - if (top >= 0 && insertedAtVisualTop && before.distanceToVisualTop <= top * before.viewportLength) { + if (top >= 0 && insertedAtVisualTop && before.distanceToVisualTop <= top) { return {AnchorOutcome::ScrollToEdge, VisualEdge::Top, true}; } return {AnchorOutcome::KeepAnchor}; diff --git a/cpp/adapter/ContentAnchor.h b/cpp/adapter/ContentAnchor.h index 662bea0..5b57c4e 100644 --- a/cpp/adapter/ContentAnchor.h +++ b/cpp/adapter/ContentAnchor.h @@ -10,8 +10,8 @@ namespace flume { // maintainVisibleContentPosition, sent complete by the wrapper. struct AnchorConfig { bool disabled = false; - double autoscrollToTopThreshold = -1; // in viewports; negative for none - double autoscrollToBottomThreshold = -1; + double autoscrollToTopThreshold = -1; // in points, negative for none + double autoscrollToBottomThreshold = -1; // in viewports, negative for none bool animateAutoScrollToBottom = true; }; diff --git a/cpp/tests/content_anchor_test.cpp b/cpp/tests/content_anchor_test.cpp index c2b3c7b..93e69b7 100644 --- a/cpp/tests/content_anchor_test.cpp +++ b/cpp/tests/content_anchor_test.cpp @@ -40,7 +40,7 @@ TEST_CASE("an insert at the bottom within the threshold scrolls there") { TEST_CASE("an insert at the top within the threshold scrolls there, always animated") { AnchorConfig config; - config.autoscrollToTopThreshold = 0.2; + config.autoscrollToTopThreshold = 100; config.animateAutoScrollToBottom = false; const AnchorDecision decision = decideAnchor(config, at(100, 500), true, false); CHECK(decision.outcome == AnchorOutcome::ScrollToEdge); @@ -50,7 +50,7 @@ TEST_CASE("an insert at the top within the threshold scrolls there, always anima TEST_CASE("the bottom wins when both edges qualify") { AnchorConfig config; - config.autoscrollToTopThreshold = 0.2; + config.autoscrollToTopThreshold = 100; config.autoscrollToBottomThreshold = 0.2; const AnchorDecision decision = decideAnchor(config, at(0, 0), true, true); CHECK(decision.outcome == AnchorOutcome::ScrollToEdge); @@ -89,3 +89,11 @@ TEST_CASE("edge inserts follow content order") { CHECK(insertedAtEdges(atEnd, 10, false).visualBottom); CHECK_FALSE(insertedAtEdges(atEnd, 10, false).visualTop); } + +TEST_CASE("the top threshold is in points") { + AnchorConfig config; + config.autoscrollToTopThreshold = 100; + CHECK(decideAnchor(config, at(100, 500), true, false).outcome == AnchorOutcome::ScrollToEdge); + config.autoscrollToTopThreshold = 99; + CHECK(decideAnchor(config, at(100, 500), true, false).outcome == AnchorOutcome::KeepAnchor); +} diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index ead2709..8c0f6c8 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -278,6 +278,30 @@ describe('Flume props', () => { expect(new Set(host.data.map((call) => call.storeId)).size).toBe(1); }); + it('turns anchoring off and on again without a remount', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const tree = await mount( + createElement(Flume, { data: [item], renderCell, maintainVisibleContentPosition: {} }), + ); + const disabled = () => + tree.root.find((node) => String(node.type) === 'FlumeView').props + .maintainVisibleContentPosition.disabled; + const id = renderedStoreId(tree); + for (const [value, expected] of [ + [false, true], + [{ autoscrollToBottomThreshold: 0.2 }, false], + ] as const) { + await act(async () => { + tree.update( + createElement(Flume, { data: [item], renderCell, maintainVisibleContentPosition: value }), + ); + }); + expect(disabled()).toBe(expected); + } + expect(renderedStoreId(tree)).toBe(id); + }); + it('treats null callbacks as not given', async () => { installHost(); const { Flume } = await import('../Flume'); diff --git a/src/__tests__/props.test.ts b/src/__tests__/props.test.ts index ef7e7d3..d6ed5c8 100644 --- a/src/__tests__/props.test.ts +++ b/src/__tests__/props.test.ts @@ -2,6 +2,7 @@ import { createElement } from 'react'; import type { RefreshControlProps } from 'react-native'; import { describe, expect, it, vi } from 'vitest'; import { contentPadding, nativeProps, refreshOf, stickyIndicesOf } from '../props'; +import type { FlumeProps } from '../types'; // Stands in for React Native's RefreshControl. const RefreshControlStub = (_props: RefreshControlProps) => null; @@ -235,6 +236,25 @@ describe('nativeProps anchoring', () => { ).maintainVisibleContentPosition?.autoscrollToBottomThreshold, ).toBe(0); }); + + it('accepts the anchoring shapes of FlatList and LegendList', () => { + const anchoring = (value: FlumeProps['maintainVisibleContentPosition']) => + nativeProps({ data: [], maintainVisibleContentPosition: value }, vi.fn()) + .maintainVisibleContentPosition; + expect(anchoring(false)?.disabled).toBe(true); + expect(anchoring({ data: false, size: false })?.disabled).toBe(true); + expect(anchoring({ data: true })?.disabled).toBe(false); + expect(anchoring(true)).toEqual(anchoring(undefined)); + expect(anchoring(null)).toEqual(anchoring(undefined)); + expect(anchoring({ minIndexForVisible: 0, autoscrollToTopThreshold: 10 })).toMatchObject({ + disabled: false, + autoscrollToTopThreshold: 10, + }); + expect( + anchoring({ minIndexForVisible: 0, autoscrollToTopThreshold: null }) + ?.autoscrollToTopThreshold, + ).toBe(-1); + }); }); describe('nativeProps estimates', () => { diff --git a/src/props.ts b/src/props.ts index be53d11..eb2c26e 100644 --- a/src/props.ts +++ b/src/props.ts @@ -127,16 +127,31 @@ function viewability( return rest; } -// Codegen structs read an unset member as 0 on iOS, so every field goes out; -1 is no threshold. -function anchoring( - config: FlumeProps['maintainVisibleContentPosition'], +// Every field the three anchoring shapes can carry. The others are ignored. +type AnchoringFields = { + disabled?: boolean; + autoscrollToTopThreshold?: number | null; + autoscrollToBottomThreshold?: number; + animateAutoScrollToBottom?: boolean; + startRenderingFromBottom?: boolean; + data?: boolean; + size?: boolean; +}; + +// Codegen structs read an unset member as 0 on iOS, so every field goes out, and -1 means no threshold. +function anchoring( + given: FlumeProps['maintainVisibleContentPosition'], ): NonNullable { + const config: AnchoringFields = typeof given === 'object' && given !== null ? given : {}; return { - disabled: config?.disabled === true, - autoscrollToTopThreshold: config?.autoscrollToTopThreshold ?? -1, - autoscrollToBottomThreshold: config?.autoscrollToBottomThreshold ?? -1, - animateAutoScrollToBottom: config?.animateAutoScrollToBottom !== false, - startRenderingFromBottom: config?.startRenderingFromBottom === true, + disabled: + given === false || + config.disabled === true || + (config.data === false && config.size === false), + autoscrollToTopThreshold: config.autoscrollToTopThreshold ?? -1, + autoscrollToBottomThreshold: config.autoscrollToBottomThreshold ?? -1, + animateAutoScrollToBottom: config.animateAutoScrollToBottom !== false, + startRenderingFromBottom: config.startRenderingFromBottom === true, }; } diff --git a/src/types.ts b/src/types.ts index 9c965eb..5be26ff 100644 --- a/src/types.ts +++ b/src/types.ts @@ -180,7 +180,7 @@ export type FlumeRef = { getAnimatableRef(): unknown; }; -// FlashList v2 shape: thresholds are fractions of the viewport at the visual edges; enabled by default. +// FlashList v2 shape, on by default. The top threshold is in points, the bottom one in viewports. export type MaintainVisibleContentPosition = { disabled?: boolean; autoscrollToTopThreshold?: number; @@ -189,6 +189,19 @@ export type MaintainVisibleContentPosition = { startRenderingFromBottom?: boolean; }; +// FlatList's shape. Flume anchors on the first visible row whatever minIndexForVisible says. +export type FlatListAnchoring = { + minIndexForVisible: number; + autoscrollToTopThreshold?: number | null; +}; + +// LegendList's shape. Flume has one switch for both, and does not call shouldRestorePosition. +export type LegendListAnchoring = { + data?: boolean; + size?: boolean; + shouldRestorePosition?: (item: T, index: number, data: readonly T[]) => boolean; +}; + export type ScrollHandler = (event: NativeSyntheticEvent) => void; // FlashList's render info; a pinned copy of a sticky row renders with the StickyHeader target. @@ -270,7 +283,13 @@ export type FlumeProps = { // interactive is iOS only. keyboardDismissMode?: 'none' | 'on-drag' | 'interactive'; keyboardShouldPersistTaps?: 'always' | 'never' | 'handled'; - maintainVisibleContentPosition?: MaintainVisibleContentPosition; + // false turns anchoring off. FlatList and LegendList objects map onto the same switch and top threshold. + maintainVisibleContentPosition?: + | boolean + | MaintainVisibleContentPosition + | FlatListAnchoring + | LegendListAnchoring + | null; onLayout?: ((event: LayoutChangeEvent) => void) | null; testID?: string; accessibilityLabel?: string; From 12a0a84cc7cdf6371daa82e7d2b405cf7406362c Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 20 Nov 2026 23:34:09 +0100 Subject: [PATCH 05/14] feat: pass data and the item type to renderItem --- src/Flume.tsx | 4 ++++ src/FlumeSlot.tsx | 7 ++++++ src/__tests__/Flume.test.tsx | 45 ++++++++++++++++++++++++++++++++++-- src/types.ts | 7 ++++-- 4 files changed, 59 insertions(+), 4 deletions(-) diff --git a/src/Flume.tsx b/src/Flume.tsx index 75c253a..8750892 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -112,6 +112,8 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { const lastViewable = useRef(new Map()); const count = useRef(data.length); count.current = data.length; + const dataRef = useRef(data); + dataRef.current = data; // Each distinct message reports once per mount, in development only. const report = useCallback((level: 'warn' | 'error', message: string) => { @@ -328,6 +330,8 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { layout={layout} item={itemOf(next, entry.key)} render={resolved?.kind === 'react' ? (resolved.render as ReactCell) : undefined} + type={type ?? 'default'} + dataRef={dataRef} element={elementFor(entry.kind)} extraData={extraData} keyboardTaps={keyboardShouldPersistTaps ?? 'never'} diff --git a/src/FlumeSlot.tsx b/src/FlumeSlot.tsx index 5574658..73dddac 100644 --- a/src/FlumeSlot.tsx +++ b/src/FlumeSlot.tsx @@ -14,6 +14,9 @@ type FlumeSlotProps = { layout: SlotLayout; item: unknown; render: ReactCell | undefined; + type: string; + // One ref for the whole list, so a data change does not re-render every slot. + dataRef: { readonly current: readonly unknown[] }; element: ReactElement | null; extraData: unknown; keyboardTaps: 'always' | 'never' | 'handled'; @@ -35,6 +38,8 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl layout, item, render, + type, + dataRef, element, extraData, keyboardTaps, @@ -52,6 +57,8 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl index, target: kind === SlotKind.sticky ? 'StickyHeader' : 'Cell', extraData, + data: dataRef.current, + type, }) ?? null) : element; return ( diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index 8c0f6c8..a6d1b4a 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -391,7 +391,41 @@ describe('Flume React cells', () => { await sendSlots(tree, [rowEntry(1, 'a', 0)]); const [view] = slotViews(tree, 1); expect(view?.props.style).toEqual({ position: 'absolute', left: 0, right: 0 }); - expect(infos.at(-1)).toEqual({ item, index: 0, target: 'Cell', extraData: undefined }); + expect(infos.at(-1)).toEqual({ + item, + index: 0, + target: 'Cell', + extraData: undefined, + data: [item], + type: 'default', + }); + }); + + it('gives renderItem the data and the item type', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { infos, renderItem } = recordingCell(); + const data = [{ id: 'a', kind: 'photo' }]; + const tree = await mount( + createElement(Flume, { + data, + renderItem, + getItemType: (i: unknown) => (i as { kind: string }).kind, + }), + ); + await sendSlots(tree, [rowEntry(1, 'a', 0)]); + expect(infos.at(-1)?.data).toBe(data); + expect(infos.at(-1)?.type).toBe('photo'); + }); + + it('renders a string or a fragment from renderItem', async () => { + installHost(); + const { Flume } = await import('../Flume'); + for (const renderItem of [() => 'text', () => createElement(Fragment, null, 'a', 'b')]) { + const tree = await mount(createElement(Flume, { data: [item], renderItem })); + await sendSlots(tree, [rowEntry(1, 'a', 0)]); + expect(slotViews(tree, 1)).toHaveLength(1); + } }); it('renders the new item in the commit that changes the data', async () => { @@ -488,7 +522,14 @@ describe('Flume React cells', () => { await sendSlots(tree, [{ ...rowEntry(7, 'a', 0), kind: 4 }], 180); const [view] = slotViews(tree, 7); expect(view?.props.style).toEqual({ position: 'absolute', left: 0, right: 0 }); - expect(infos).toContainEqual({ item, index: 0, target: 'StickyHeader', extraData: undefined }); + expect(infos).toContainEqual({ + item, + index: 0, + target: 'StickyHeader', + extraData: undefined, + data: [item], + type: 'default', + }); }); it('keeps a React cell mounted at its new width when numColumns changes', async () => { diff --git a/src/types.ts b/src/types.ts index 5be26ff..be01900 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,4 @@ -import type { ComponentType, ReactElement } from 'react'; +import type { ComponentType, ReactElement, ReactNode } from 'react'; import type { ColorValue, Insets, @@ -210,9 +210,12 @@ export type CellInfo = { index: number; target: 'Cell' | 'StickyHeader'; extraData?: unknown; + // LegendList's fields: the data of the render that last drew the row, and the item's type. + data: readonly T[]; + type: string; }; -export type ReactCell = (info: CellInfo) => ReactElement | null; +export type ReactCell = (info: CellInfo) => ReactNode; export type FlumeProps = { data: readonly T[] | null | undefined; From 3a07f3b9b8f1c8eb3d88dfd133277b2d92c2229f Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 20 Nov 2026 23:37:09 +0100 Subject: [PATCH 06/14] feat: accept host view props and the props Flume does not need --- src/Flume.tsx | 6 +- src/__tests__/Flume.test.tsx | 54 ++++++++++ src/foreign.ts | 197 +++++++++++++++++++++++++++++++++++ src/index.ts | 4 + src/props.ts | 29 ++++-- src/types.ts | 19 +++- 6 files changed, 296 insertions(+), 13 deletions(-) create mode 100644 src/foreign.ts diff --git a/src/Flume.tsx b/src/Flume.tsx index 8750892..8520aa5 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -19,7 +19,8 @@ import { createSerializable } from 'react-native-worklets'; import { cellKinds, type ResolvedCell, resolveCell } from './cells'; import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data'; import { FlumeSlot } from './FlumeSlot'; -import { contentPadding, nativeProps, refreshOf, stickyIndicesOf, withoutNulls } from './props'; +import { hostProps } from './foreign'; +import { contentPadding, nativeProps, refreshOf, settleProps, stickyIndicesOf } from './props'; import { applySnapshot, gridCellWidth, @@ -49,7 +50,7 @@ function componentElement( } function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { - const props = withoutNulls(given); + const props = settleProps(given); const { data, renderCell, @@ -392,6 +393,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { return ( { expect(renderedStoreId(tree)).toBe(id); }); + it('passes host view props to the native view', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const tree = await mount( + createElement(Flume, { + data: [item], + renderCell, + nativeID: 'list', + pointerEvents: 'box-none', + accessibilityRole: 'list', + }), + ); + expect(tree.root.find((node) => String(node.type) === 'FlumeView').props).toMatchObject({ + nativeID: 'list', + pointerEvents: 'box-none', + accessibilityRole: 'list', + }); + }); + + it('keeps ignored props off the native view', async () => { + installHost(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const { Flume } = await import('../Flume'); + const tree = await mount( + createElement(Flume, { + data: [item], + renderCell, + windowSize: 5, + getItemLayout: () => ({ length: 10, offset: 0, index: 0 }), + removeClippedSubviews: true, + }), + ); + const props = tree.root.find((node) => String(node.type) === 'FlumeView').props; + expect(props).not.toHaveProperty('windowSize'); + expect(props).not.toHaveProperty('getItemLayout'); + expect(props).not.toHaveProperty('removeClippedSubviews'); + expect(warn).not.toHaveBeenCalled(); + }); + + it('scrolls to the index of an initialScrollIndex object', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const tree = await mount( + createElement(Flume, { + data: [item, item, item, item], + renderCell, + initialScrollIndex: { index: 3, viewOffset: 10 }, + }), + ); + expect( + tree.root.find((node) => String(node.type) === 'FlumeView').props.initialScrollIndex, + ).toBe(3); + }); + it('treats null callbacks as not given', async () => { installHost(); const { Flume } = await import('../Flume'); diff --git a/src/foreign.ts b/src/foreign.ts new file mode 100644 index 0000000..d942bbc --- /dev/null +++ b/src/foreign.ts @@ -0,0 +1,197 @@ +import type { ComponentType, ReactElement } from 'react'; +import type { ScrollViewProps, ViewProps } from 'react-native'; +import type { FlumeOwnProps, FlumeProps } from './types'; + +// The names other lists use to tune their JS rendering, accepted so their code type-checks. +export type IgnoredProps = { + /** @deprecated Flume lays rows out natively and does not use this. */ + getItemLayout?: + | (( + data: ArrayLike | null | undefined, + index: number, + ) => { length: number; offset: number; index: number }) + | null; + /** @deprecated Flume lays rows out natively and does not use this. */ + initialNumToRender?: number | null; + /** @deprecated Flume lays rows out natively and does not use this. */ + maxToRenderPerBatch?: number | null; + /** @deprecated Flume lays rows out natively and does not use this. */ + updateCellsBatchingPeriod?: number | null; + /** @deprecated Flume lays rows out natively and does not use this. */ + windowSize?: number | null; + /** @deprecated Flume lays rows out natively and does not use this. */ + removeClippedSubviews?: boolean | null; + /** @deprecated Flume lays rows out natively and does not use this. */ + disableVirtualization?: boolean | null; + /** @deprecated Flume lays rows out natively and does not use this. */ + debug?: boolean | null; + /** @deprecated Flume lays rows out natively and does not use this. */ + strictMode?: boolean | null; + /** @deprecated Flume lays rows out natively and does not use this. */ + onScrollToIndexFailed?: + | ((info: { + index: number; + highestMeasuredFrameIndex: number; + averageItemLength: number; + }) => void) + | null; + /** @deprecated Flume lays rows out natively and does not use this. */ + automaticallyAdjustContentInsets?: boolean; + /** @deprecated Flume lays rows out natively and does not use this. */ + bouncesZoom?: boolean; + /** @deprecated Flume lays rows out natively and does not use this. */ + maximumZoomScale?: number; + /** @deprecated Flume lays rows out natively and does not use this. */ + minimumZoomScale?: number; + /** @deprecated Flume lays rows out natively and does not use this. */ + pinchGestureEnabled?: boolean; + /** @deprecated Flume lays rows out natively and does not use this. */ + zoomScale?: number; + /** @deprecated Flume lays rows out natively and does not use this. */ + centerContent?: boolean; + /** @deprecated Flume lays rows out natively and does not use this. */ + disableScrollViewPanResponder?: boolean; + /** @deprecated Flume lays rows out natively and does not use this. */ + scrollPerfTag?: string; + /** @deprecated Flume lays rows out natively and does not use this. */ + maxItemsInRecyclePool?: number; + /** @deprecated Flume lays rows out natively and does not use this. */ + onCommitLayoutEffect?: () => void; + /** @deprecated Flume lays rows out natively and does not use this. */ + alwaysRender?: object; + /** @deprecated Flume lays rows out natively and does not use this. */ + estimatedListSize?: { height: number; width: number }; + /** @deprecated Flume lays rows out natively and does not use this. */ + estimatedHeaderSize?: number; + /** @deprecated Flume lays rows out natively and does not use this. */ + getFixedItemSize?: (item: T, index: number, type: string | undefined) => number | undefined; + /** @deprecated Flume lays rows out natively and does not use this. */ + contentInsetEndAdjustment?: number; + /** @deprecated Flume lays rows out natively and does not use this. */ + experimental_hideItemsUntilMeasured?: boolean; + /** @deprecated Flume lays rows out natively and does not use this. */ + recycleItems?: boolean; + /** @deprecated Flume cannot use this. See the migration guide. */ + renderScrollComponent?: (props: ScrollViewProps) => ReactElement; + /** @deprecated Flume cannot use this. See the migration guide. */ + StickyHeaderComponent?: ComponentType; + /** @deprecated Flume cannot use this. See the migration guide. */ + overrideProps?: object; + /** @deprecated Flume cannot use this. See the migration guide. */ + innerViewRef?: unknown; + /** @deprecated Flume cannot use this. See the migration guide. */ + useWindowScroll?: boolean; +}; + +export const IGNORED_KEYS = [ + 'getItemLayout', + 'initialNumToRender', + 'maxToRenderPerBatch', + 'updateCellsBatchingPeriod', + 'windowSize', + 'removeClippedSubviews', + 'disableVirtualization', + 'debug', + 'strictMode', + 'onScrollToIndexFailed', + 'automaticallyAdjustContentInsets', + 'bouncesZoom', + 'maximumZoomScale', + 'minimumZoomScale', + 'pinchGestureEnabled', + 'zoomScale', + 'centerContent', + 'disableScrollViewPanResponder', + 'scrollPerfTag', + 'maxItemsInRecyclePool', + 'onCommitLayoutEffect', + 'alwaysRender', + 'estimatedListSize', + 'estimatedHeaderSize', + 'getFixedItemSize', + 'contentInsetEndAdjustment', + 'experimental_hideItemsUntilMeasured', + 'recycleItems', + 'renderScrollComponent', + 'StickyHeaderComponent', + 'overrideProps', + 'innerViewRef', + 'useWindowScroll', +] as const satisfies readonly (keyof IgnoredProps)[]; + +export const OWN_KEYS = [ + 'data', + 'renderCell', + 'renderItem', + 'reactCells', + 'keyExtractor', + 'getItemType', + 'extraData', + 'itemAnimations', + 'onPress', + 'onLongPress', + 'style', + 'horizontal', + 'numColumns', + 'inverted', + 'contentContainerStyle', + 'estimatedItemSize', + 'drawDistance', + 'initialScrollIndex', + 'separator', + 'stickyHeaderIndices', + 'ListHeaderComponent', + 'ListFooterComponent', + 'ListEmptyComponent', + 'onScroll', + 'onScrollBeginDrag', + 'onScrollEndDrag', + 'onMomentumScrollBegin', + 'onMomentumScrollEnd', + 'scrollEventThrottle', + 'onViewableItemsChanged', + 'viewabilityConfig', + 'onEndReached', + 'onEndReachedThreshold', + 'onStartReached', + 'onStartReachedThreshold', + 'refreshing', + 'onRefresh', + 'refreshControl', + 'scrollEnabled', + 'nestedScrollEnabled', + 'overScrollMode', + 'decelerationRate', + 'showsVerticalScrollIndicator', + 'showsHorizontalScrollIndicator', + 'contentInset', + 'scrollIndicatorInsets', + 'contentInsetAdjustmentBehavior', + 'bounces', + 'alwaysBounceVertical', + 'keyboardDismissMode', + 'keyboardShouldPersistTaps', + 'maintainVisibleContentPosition', + 'onLayout', + 'testID', + 'accessibilityLabel', +] as const satisfies readonly (keyof FlumeOwnProps)[]; + +// Fails to compile when an own prop is missing from OWN_KEYS, so it cannot leak to the native view. +const everyOwnKey: [Exclude, (typeof OWN_KEYS)[number]>] extends [ + never, +] + ? true + : never = true; +void everyOwnKey; + +const NOT_HOST = new Set([...OWN_KEYS, ...IGNORED_KEYS, 'children']); + +// The plain view props a list may carry (nativeID, pointerEvents, accessibility), for the native view. +export function hostProps(props: FlumeProps): ViewProps { + const host: Record = {}; + for (const key in props) { + if (!NOT_HOST.has(key)) host[key] = (props as Record)[key]; + } + return host as ViewProps; +} diff --git a/src/index.ts b/src/index.ts index 26a1294..afed026 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,8 +8,12 @@ export type { CellPressableProps, CellStyle, CellTextOptions, + FlatListAnchoring, FlumeProps, FlumeRef, + LegendListAnchoring, + ListRenderItem, + ListRenderItemInfo, MaintainVisibleContentPosition, PressInfo, ReactCell, diff --git a/src/props.ts b/src/props.ts index eb2c26e..d14a636 100644 --- a/src/props.ts +++ b/src/props.ts @@ -196,7 +196,7 @@ export function refreshOf(props: FlumeProps): Refresh { progressViewOffset: control?.progressViewOffset ?? 0, }; } -// FlashList and LegendList type these as nullable, where null means not given. +// Props that FlashList and LegendList type as nullable, where null means not given. const NULLABLE = [ 'renderCell', 'renderItem', @@ -214,28 +214,41 @@ const NULLABLE = [ 'onStartReached', 'onRefresh', 'onLayout', + 'stickyHeaderIndices', ] as const; type Nullable = (typeof NULLABLE)[number]; -export type SettledProps = Omit, 'data' | Nullable> & { +export type SettledProps = Omit, 'data' | 'initialScrollIndex' | Nullable> & { data: readonly T[]; + initialScrollIndex?: number; } & { [K in Nullable]?: NonNullable[K]> }; const EMPTY: readonly never[] = []; -// The props with data defaulted and null callbacks removed, the same object when nothing is null. -export function withoutNulls(props: FlumeProps): SettledProps { - if (props.data != null && NULLABLE.every((key) => props[key] !== null)) { +// The props in one shape: data defaulted, nulls removed, initialScrollIndex as a number. Unchanged props pass as is. +export function settleProps(props: FlumeProps): SettledProps { + const initial = props.initialScrollIndex; + if ( + props.data != null && + (initial === undefined || typeof initial === 'number') && + NULLABLE.every((key) => props[key] !== null) + ) { return props as SettledProps; } - const settled: Record = { ...props, data: props.data ?? EMPTY }; - for (const key of NULLABLE) if (settled[key] === null) delete settled[key]; + const settled: Record = { + ...props, + data: props.data ?? EMPTY, + initialScrollIndex: typeof initial === 'object' && initial !== null ? initial.index : initial, + }; + for (const key of [...NULLABLE, 'initialScrollIndex']) { + if (settled[key] == null) delete settled[key]; + } return settled as SettledProps; } export function nativeProps(given: FlumeProps, warn: Warn): FlatProps { - const props = withoutNulls(given); + const props = settleProps(given); const refresh = refreshOf(props); const horizontal = props.horizontal === true; let numColumns = props.numColumns ?? 1; diff --git a/src/types.ts b/src/types.ts index be01900..63b3aa2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -7,8 +7,10 @@ import type { NativeSyntheticEvent, RefreshControlProps, StyleProp, + ViewProps, ViewStyle, } from 'react-native'; +import type { IgnoredProps } from './foreign'; export type CellDimension = number | `${number}%`; // Yoga takes auto on these keys only, as React Native does. @@ -217,7 +219,7 @@ export type CellInfo = { export type ReactCell = (info: CellInfo) => ReactNode; -export type FlumeProps = { +export type FlumeOwnProps = { data: readonly T[] | null | undefined; renderCell?: ((item: T, index: number) => CellNode) | null; // The React renderer for every type without a worklet cell or a reactCells entry. @@ -240,11 +242,15 @@ export type FlumeProps = { estimatedItemSize?: number; // How far past the viewport, in dp, cells are bound ahead; the default is one viewport. drawDistance?: number; - initialScrollIndex?: number; + // LegendList's object form opens at its index. Its offsets are not read yet. + initialScrollIndex?: + | number + | { index: number; viewOffset?: number; viewPosition?: number } + | null; // A native line between consecutive rows, inset along the cross axis from the start and end edges. separator?: { size: number; color?: string; insetStart?: number; insetEnd?: number }; // Data indices, as FlashList counts them; FlatList counts the header too. - stickyHeaderIndices?: number[]; + stickyHeaderIndices?: readonly number[] | null; // Rows around the data; the empty one shows instead of the data while it is empty, filling the viewport. ListHeaderComponent?: ComponentType | ReactElement | null; ListFooterComponent?: ComponentType | ReactElement | null; @@ -297,3 +303,10 @@ export type FlumeProps = { testID?: string; accessibilityLabel?: string; }; + +export type FlumeProps = FlumeOwnProps & + IgnoredProps & + Omit | keyof IgnoredProps | 'children'>; + +export type ListRenderItem = ReactCell; +export type ListRenderItemInfo = CellInfo; From 5c3193906086936870450bb4dae22854ec0e28df Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Fri, 20 Nov 2026 23:38:36 +0100 Subject: [PATCH 07/14] test: type-check list code from FlatList, FlashList and LegendList --- src/__tests__/types/flashlist.types.tsx | 28 +++++++++++++++++ src/__tests__/types/flatlist.types.tsx | 37 ++++++++++++++++++++++ src/__tests__/types/legendlist.types.tsx | 39 ++++++++++++++++++++++++ 3 files changed, 104 insertions(+) create mode 100644 src/__tests__/types/flashlist.types.tsx create mode 100644 src/__tests__/types/flatlist.types.tsx create mode 100644 src/__tests__/types/legendlist.types.tsx diff --git a/src/__tests__/types/flashlist.types.tsx b/src/__tests__/types/flashlist.types.tsx new file mode 100644 index 0000000..e2befa0 --- /dev/null +++ b/src/__tests__/types/flashlist.types.tsx @@ -0,0 +1,28 @@ +// FlashList code from its README, with only the import and the component name changed. +import { Text } from 'react-native'; +import { Flume } from 'react-native-flume'; + +const DATA = [ + { title: 'First Item', kind: 1 }, + { title: 'Second Item', kind: 2 }, +]; + +export function FlashListExample() { + return ( + ( + {target === 'Cell' ? item.title : String(extraData)} + )} + getItemType={(item) => item.kind} + estimatedItemSize={50} + drawDistance={250} + onEndReached={null} + onViewableItemsChanged={null} + maintainVisibleContentPosition={{ + autoscrollToBottomThreshold: 0.2, + startRenderingFromBottom: true, + }} + /> + ); +} diff --git a/src/__tests__/types/flatlist.types.tsx b/src/__tests__/types/flatlist.types.tsx new file mode 100644 index 0000000..ecc6189 --- /dev/null +++ b/src/__tests__/types/flatlist.types.tsx @@ -0,0 +1,37 @@ +// FlatList code from React Native's docs, with only the import and the component name changed. +import { useState } from 'react'; +import { RefreshControl, Text } from 'react-native'; +import { Flume, type ListRenderItem } from 'react-native-flume'; + +type ItemData = { id: string; title: string }; + +const DATA: ItemData[] | undefined = [ + { id: 'bd7acbea', title: 'First Item' }, + { id: '3ac68afc', title: 'Second Item' }, +]; + +const renderItem: ListRenderItem = ({ item }) => {item.title}; +const sticky: readonly number[] = [0]; + +export function FlatListExample() { + const [refreshing, setRefreshing] = useState(false); + return ( + item.id} + ListHeaderComponent={Header} + stickyHeaderIndices={sticky} + refreshControl={ + setRefreshing(true)} /> + } + getItemLayout={(_data, index) => ({ length: 50, offset: 50 * index, index })} + windowSize={5} + initialNumToRender={10} + removeClippedSubviews + maintainVisibleContentPosition={{ minIndexForVisible: 0 }} + nativeID="list" + accessibilityRole="list" + /> + ); +} diff --git a/src/__tests__/types/legendlist.types.tsx b/src/__tests__/types/legendlist.types.tsx new file mode 100644 index 0000000..21a9b8c --- /dev/null +++ b/src/__tests__/types/legendlist.types.tsx @@ -0,0 +1,39 @@ +// LegendList code from its README, with only the import and the names changed. +import { useRef } from 'react'; +import { Image, Text, View } from 'react-native'; +import { Flume, type FlumeRef, type ListRenderItemInfo } from 'react-native-flume'; + +interface UserData { + id: string; + name: string; + photoUri: string; +} + +export function LegendListExample({ data }: { data: UserData[] }) { + const listRef = useRef(null); + const renderItem = ({ item, data: all, type }: ListRenderItemInfo) => ( + + + {`${item.name} ${all.length} ${type}`} + + ); + return ( + <> + item.id} + recycleItems={true} + maintainVisibleContentPosition + ref={listRef} + /> + + + ); +} From 3e207cac0ae72269557c93198c375059665efc49 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 00:06:22 +0100 Subject: [PATCH 08/14] fix: keep a removed row's type and data while it animates out A row whose key left the data kept its item and renderer for the exit animation, but read its type and the data live, so renderItem saw type 'default' and the new data for those frames. The slot now keeps the type and data it last rendered with. --- src/FlumeSlot.tsx | 16 ++++++++++++---- src/__tests__/Flume.test.tsx | 15 +++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/FlumeSlot.tsx b/src/FlumeSlot.tsx index 73dddac..1678226 100644 --- a/src/FlumeSlot.tsx +++ b/src/FlumeSlot.tsx @@ -44,8 +44,16 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl extraData, keyboardTaps, } = props; - const last = useRef<{ item?: unknown; render?: ReactCell }>({}); - if (item !== undefined && render !== undefined) last.current = { item, render }; + const last = useRef<{ + item?: unknown; + render?: ReactCell; + type?: string; + data?: readonly unknown[]; + }>({}); + // A row that left the data renders its exit with what it had, type and data included. + if (item !== undefined && render !== undefined) { + last.current = { item, render, type, data: dataRef.current }; + } const entry = { slot, kind, key: itemKey, index, bound: true, minMain }; const style = slotStyle(entry, fullSpan, layout); if (style === null) return null; @@ -57,8 +65,8 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl index, target: kind === SlotKind.sticky ? 'StickyHeader' : 'Cell', extraData, - data: dataRef.current, - type, + data: last.current.data ?? dataRef.current, + type: last.current.type ?? type, }) ?? null) : element; return ( diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index 05659df..65482b3 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -508,6 +508,21 @@ describe('Flume React cells', () => { expect(infos.every((info) => info.item !== undefined)).toBe(true); }); + it('keeps the type and data of a row that left the data', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { infos, renderItem } = recordingCell(); + const photo = { id: 'a', kind: 'photo' }; + const getItemType = (i: unknown) => (i as { kind: string }).kind; + const tree = await mount(createElement(Flume, { data: [photo], renderItem, getItemType })); + await sendSlots(tree, [rowEntry(1, 'a', 0)]); + await act(async () => { + tree.update(createElement(Flume, { data: [], renderItem, getItemType })); + }); + expect(infos.map((info) => info.type)).not.toContain('default'); + expect(infos.at(-1)?.data).toEqual([photo]); + }); + it('renders the list components in their slots', async () => { installHost(); const { Flume } = await import('../Flume'); From 611ec1bcbdcffe72ba2ebd400a226ce55c2df2be Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 00:06:41 +0100 Subject: [PATCH 09/14] fix: accept more nullable props and FlatList anchoring on inverted lists viewabilityConfig={null} threw, and horizontal, inverted, the two reach thresholds and refreshing rejected null, which FlatList and FlashList allow. A null item type now means 'default' again. FlatList measures autoscrollToTopThreshold from the content start, which is the visual bottom of an inverted list, so Flume no longer applies it at the visual top there. --- src/__tests__/data.test.ts | 3 ++- src/__tests__/props.test.ts | 33 +++++++++++++++++++++++++++++++++ src/data.ts | 4 ++-- src/props.ts | 16 ++++++++++++++-- src/types.ts | 14 +++++++------- 5 files changed, 58 insertions(+), 12 deletions(-) diff --git a/src/__tests__/data.test.ts b/src/__tests__/data.test.ts index 3f59940..3a75b1c 100644 --- a/src/__tests__/data.test.ts +++ b/src/__tests__/data.test.ts @@ -147,10 +147,11 @@ describe('diffData types for native', () => { { id: 'a', t: 1 }, { id: 'b', t: '1' }, { id: 'c', t: undefined }, + { id: 'd', t: null }, ]; const d = diffData(undefined, items, undefined, (i) => i.t); expect(d.typeTable).toEqual(['1', 'default']); - expect([...d.typeIds]).toEqual([0, 0, 1]); + expect([...d.typeIds]).toEqual([0, 0, 1, 1]); }); }); diff --git a/src/__tests__/props.test.ts b/src/__tests__/props.test.ts index d6ed5c8..544476a 100644 --- a/src/__tests__/props.test.ts +++ b/src/__tests__/props.test.ts @@ -237,6 +237,39 @@ describe('nativeProps anchoring', () => { ).toBe(0); }); + it('drops the FlatList top threshold on an inverted list, where FlatList measures it at the bottom', () => { + const flatList = { minIndexForVisible: 0, autoscrollToTopThreshold: 10 }; + const sent = (inverted: boolean) => + nativeProps({ data: [], inverted, maintainVisibleContentPosition: flatList }, vi.fn()) + .maintainVisibleContentPosition?.autoscrollToTopThreshold; + expect(sent(false)).toBe(10); + expect(sent(true)).toBe(-1); + }); + + it('treats the nullable props of FlatList and FlashList as not given', () => { + expect( + nativeProps( + { + data: [], + horizontal: null, + inverted: null, + viewabilityConfig: null, + onEndReachedThreshold: null, + onStartReachedThreshold: null, + refreshing: null, + }, + vi.fn(), + ), + ).toMatchObject({ + horizontal: false, + inverted: false, + viewabilityConfig: undefined, + endReachedThreshold: 2, + startReachedThreshold: 2, + refreshing: false, + }); + }); + it('accepts the anchoring shapes of FlatList and LegendList', () => { const anchoring = (value: FlumeProps['maintainVisibleContentPosition']) => nativeProps({ data: [], maintainVisibleContentPosition: value }, vi.fn()) diff --git a/src/data.ts b/src/data.ts index ebe4b6e..0dbbfe2 100644 --- a/src/data.ts +++ b/src/data.ts @@ -1,5 +1,5 @@ export type KeyExtractor = (item: T, index: number) => string; -export type TypeExtractor = (item: T, index: number) => string | number | undefined; +export type TypeExtractor = (item: T, index: number) => string | number | null | undefined; // Index-aligned arrays plus one key-to-index map; look up by key through itemOf and typeOf. export type DataState = { @@ -117,7 +117,7 @@ function scan( index.set(key, i); keys[i] = key; const raw = getItemType?.(item, i); - const type = raw === undefined ? 'default' : typeof raw === 'string' ? raw : String(raw); + const type = raw == null ? 'default' : typeof raw === 'string' ? raw : String(raw); types[i] = type; // Lists switch type often and have few types: a short table is searched in place, a long one through the map. if (type !== idType) { diff --git a/src/props.ts b/src/props.ts index d14a636..5ca58f0 100644 --- a/src/props.ts +++ b/src/props.ts @@ -141,14 +141,17 @@ type AnchoringFields = { // Codegen structs read an unset member as 0 on iOS, so every field goes out, and -1 means no threshold. function anchoring( given: FlumeProps['maintainVisibleContentPosition'], + inverted: boolean, ): NonNullable { const config: AnchoringFields = typeof given === 'object' && given !== null ? given : {}; + // FlatList measures its top threshold from the content start, the visual bottom of an inverted list. + const flatListInverted = inverted && 'minIndexForVisible' in config; return { disabled: given === false || config.disabled === true || (config.data === false && config.size === false), - autoscrollToTopThreshold: config.autoscrollToTopThreshold ?? -1, + autoscrollToTopThreshold: flatListInverted ? -1 : (config.autoscrollToTopThreshold ?? -1), autoscrollToBottomThreshold: config.autoscrollToBottomThreshold ?? -1, animateAutoScrollToBottom: config.animateAutoScrollToBottom !== false, startRenderingFromBottom: config.startRenderingFromBottom === true, @@ -215,6 +218,12 @@ const NULLABLE = [ 'onRefresh', 'onLayout', 'stickyHeaderIndices', + 'horizontal', + 'inverted', + 'viewabilityConfig', + 'onEndReachedThreshold', + 'onStartReachedThreshold', + 'refreshing', ] as const; type Nullable = (typeof NULLABLE)[number]; @@ -314,6 +323,9 @@ export function nativeProps(given: FlumeProps, warn: Warn): FlatProps { keyboardDismissMode: props.keyboardDismissMode ?? 'none', keyboardShouldPersistTaps: props.keyboardShouldPersistTaps ?? 'never', rowsPressable: props.onPress !== undefined || props.onLongPress !== undefined, - maintainVisibleContentPosition: anchoring(props.maintainVisibleContentPosition), + maintainVisibleContentPosition: anchoring( + props.maintainVisibleContentPosition, + props.inverted === true, + ), }; } diff --git a/src/types.ts b/src/types.ts index 63b3aa2..02cd118 100644 --- a/src/types.ts +++ b/src/types.ts @@ -227,15 +227,15 @@ export type FlumeOwnProps = { // React renderers by item type; they take precedence over renderCell. reactCells?: Record>; keyExtractor?: ((item: T, index: number) => string) | null; - getItemType?: ((item: T, index: number) => string | number | undefined) | null; + getItemType?: ((item: T, index: number) => string | number | null | undefined) | null; extraData?: unknown; itemAnimations?: boolean; onPress?: ((info: PressInfo) => void) | null; onLongPress?: ((info: PressInfo) => void) | null; style?: StyleProp; - horizontal?: boolean; + horizontal?: boolean | null; numColumns?: number; - inverted?: boolean; + inverted?: boolean | null; // Padding only, as the spec says; other keys warn in development. contentContainerStyle?: StyleProp; // React cells only: the length in dp a cell takes until it measures; else the mean of its type, at least 50. @@ -265,12 +265,12 @@ export type FlumeOwnProps = { onViewableItemsChanged?: | ((info: { viewableItems: ViewToken[]; changed: ViewToken[] }) => void) | null; - viewabilityConfig?: ViewabilityConfig; + viewabilityConfig?: ViewabilityConfig | null; onEndReached?: ((info: { distanceFromEnd: number }) => void) | null; - onEndReachedThreshold?: number; + onEndReachedThreshold?: number | null; onStartReached?: ((info: { distanceFromStart: number }) => void) | null; - onStartReachedThreshold?: number; - refreshing?: boolean; + onStartReachedThreshold?: number | null; + refreshing?: boolean | null; onRefresh?: (() => void) | null; // A RefreshControl element, or the spinner style alone (tintColor on iOS, colors on Android). refreshControl?: From 2fb0c496b57f1cc81666dbfdad9e802ae9895087 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 00:06:59 +0100 Subject: [PATCH 10/14] docs: update the README prop types for lists moving to Flume --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ea9bfd1..8d11013 100644 --- a/README.md +++ b/README.md @@ -87,12 +87,12 @@ Data and rows: | Prop | Type | Default | Description | | --- | --- | --- | --- | -| `data` | `readonly T[]` | Required | Sets the items the list shows. | +| `data` | `readonly T[] \| null` | Required | Sets the items the list shows. `null` and `undefined` show an empty list. | | `renderCell` | `(item, index) => CellNode` | | Builds each row from a worklet that returns [cell nodes](#cells). | -| `renderItem` | `({ item, index, target, extraData }) => ReactElement` | | Renders each row as a React element when `renderCell` isn't set. | +| `renderItem` | `({ item, index, target, extraData, data, type }) => ReactNode` | | Renders each row with React when `renderCell` isn't set. | | `reactCells` | `Record>` | | Renders the item types it names as React elements, in place of `renderCell`. | | `keyExtractor` | `(item, index) => string` | `item.id`, then `item.key`, then the index | Returns a unique key for each item. | -| `getItemType` | `(item, index) => string` | `'default'` | Returns each item's type. Rows are reused within a type, and `reactCells` picks a renderer by it. | +| `getItemType` | `(item, index) => string \| number` | `'default'` | Returns each item's type. Rows are reused within a type, and `reactCells` picks a renderer by it. A number counts as its text, so `1` and `'1'` are one type. | | `extraData` | `unknown` | | Re-renders the React rows when it changes. | | `itemAnimations` | `boolean` | `true` | Animates rows that are added, removed or moved when `data` changes. | | `onPress` | `({ item, index, id }) => void` | | Called when a worklet row or a `cell.pressable` is tapped. `id` is the pressable's `id`, or `undefined` for the row. | @@ -107,13 +107,13 @@ Layout: | `inverted` | `boolean` | `false` | Flips the list so the first item shows at the bottom, as in a chat. | | `contentContainerStyle` | `StyleProp` | | Adds padding around the rows. Other style keys are ignored. | | `separator` | `{ size, color?, insetStart?, insetEnd? }` | | Adds a line `size` dp thick between rows, inset from the start and end edges. | -| `stickyHeaderIndices` | `number[]` | | Pins the items at these indices to the top while their section scrolls. | +| `stickyHeaderIndices` | `readonly number[]` | | Pins the items at these indices to the top while their section scrolls. | | `ListHeaderComponent` | `ComponentType \| ReactElement` | | Renders a row before the first item. | | `ListFooterComponent` | `ComponentType \| ReactElement` | | Renders a row after the last item. | | `ListEmptyComponent` | `ComponentType \| ReactElement` | | Renders in place of the rows while `data` is empty, filling the list. | | `estimatedItemSize` | `number` | The mean of the item's type, at least 50 | Sets the length in dp that a React row takes until it's measured. | | `drawDistance` | `number` | One screen | Sets how far past the screen edges, in dp, rows are prepared ahead of scrolling. | -| `initialScrollIndex` | `number` | | Opens the list at this item. | +| `initialScrollIndex` | `number \| { index }` | | Opens the list at this item. | | `maintainVisibleContentPosition` | `boolean \| MaintainVisibleContentPosition` | On | Keeps the visible rows in place when items are added above them. Pass `false` to turn it off. | `maintainVisibleContentPosition` takes these options: @@ -162,7 +162,7 @@ Visibility, loading and refresh: | `onStartReachedThreshold` | `number` | `2` | Sets the distance from the start, in screens, that calls `onStartReached`. | | `onRefresh` | `() => void` | | Adds pull to refresh and is called when the user pulls. | | `refreshing` | `boolean` | `false` | Shows the refresh spinner while it's `true`. | -| `refreshControl` | `{ tintColor?, colors?, progressViewOffset? }` | | Colors and moves the refresh spinner. `tintColor` works on iOS and `colors` on Android. | +| `refreshControl` | `ReactElement \| { tintColor?, colors?, progressViewOffset? }` | | Takes a `RefreshControl` element, as on FlatList, or only the spinner style. `tintColor` works on iOS and `colors` on Android. | The list view: @@ -210,7 +210,7 @@ Then rename `` to ``. `renderItem`, `keyExtractor`, the list co - `ItemSeparatorComponent` becomes `separator`, a line with a size and a color. - `stickyHeaderIndices` counts items only. With a `ListHeaderComponent`, subtract 1 from FlatList's indices. -- `contentContainerStyle` takes padding only, and `refreshControl` takes the spinner colors as an object. +- `contentContainerStyle` takes padding only. - Rows animate when `data` changes and stay in place when items load above them. `itemAnimations` and `maintainVisibleContentPosition` turn this off. ## Roadmap From 416bb99355654be5a578b8eee85fd471d6ce47b8 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 00:23:02 +0100 Subject: [PATCH 11/14] fix(android): treat a negative top threshold as none --- android/src/main/java/me/sectiontn/flume/ContentAnchor.kt | 2 +- android/src/test/java/me/sectiontn/flume/AnchorPolicyTest.kt | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/android/src/main/java/me/sectiontn/flume/ContentAnchor.kt b/android/src/main/java/me/sectiontn/flume/ContentAnchor.kt index fa44f63..04dd2f4 100644 --- a/android/src/main/java/me/sectiontn/flume/ContentAnchor.kt +++ b/android/src/main/java/me/sectiontn/flume/ContentAnchor.kt @@ -44,7 +44,7 @@ object AnchorPolicy { } // React Native's ScrollView always animates to the top. val top = config.autoscrollToTopThresholdPx - if (top != null && insertedAtVisualTop && before.distanceToVisualTopPx <= top) { + if (top != null && top >= 0 && insertedAtVisualTop && before.distanceToVisualTopPx <= top) { return AnchorDecision(restore = kept, scrollTo = VisualEdge.TOP, animated = true) } return if (anchorLost) restore else AnchorDecision() diff --git a/android/src/test/java/me/sectiontn/flume/AnchorPolicyTest.kt b/android/src/test/java/me/sectiontn/flume/AnchorPolicyTest.kt index bdb5a0c..d96131d 100644 --- a/android/src/test/java/me/sectiontn/flume/AnchorPolicyTest.kt +++ b/android/src/test/java/me/sectiontn/flume/AnchorPolicyTest.kt @@ -32,6 +32,11 @@ class AnchorPolicyTest { assertEquals(AnchorDecision(), AnchorPolicy.decide(AnchorConfig(autoscrollToTopThresholdPx = 899.0), before, true, false)) } + @Test fun aNegativeTopThresholdIsOff() { + val config = AnchorConfig(autoscrollToTopThresholdPx = -2.625) + assertEquals(AnchorDecision(), AnchorPolicy.decide(config, before.copy(distanceToVisualTopPx = -5), true, false)) + } + @Test fun aChangeThatRemovesEveryLaidOutRowKeepsThePosition() { assertEquals(AnchorDecision(restore = 3 to -12), AnchorPolicy.decide(AnchorConfig(), before, true, false, anchorLost = true)) } From b33dea7cd3618bc43bf5a8b5ef0c4c7f9974dd56 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 00:23:03 +0100 Subject: [PATCH 12/14] fix: keep pull to refresh off for a disabled RefreshControl --- src/__tests__/props.test.ts | 18 +++++++++++++++++- src/props.ts | 6 +++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/__tests__/props.test.ts b/src/__tests__/props.test.ts index 544476a..9ad27f4 100644 --- a/src/__tests__/props.test.ts +++ b/src/__tests__/props.test.ts @@ -148,14 +148,30 @@ describe('nativeProps refresh', () => { colors: ['red'], tintColor: 'blue', progressViewOffset: 20, + enabled: true, }); }); + it('keeps refresh off when the RefreshControl element is disabled', () => { + const element = createElement(RefreshControlStub, { + refreshing: false, + onRefresh: () => {}, + enabled: false, + }); + expect(nativeProps({ data: [], refreshControl: element }, vi.fn()).refreshEnabled).toBe(false); + }); + it('reads the config object of 0.1 with the top-level props', () => { const onRefresh = () => {}; expect( refreshOf({ data: [], onRefresh, refreshing: false, refreshControl: { colors: ['red'] } }), - ).toEqual({ onRefresh, refreshing: false, colors: ['red'], progressViewOffset: 0 }); + ).toEqual({ + onRefresh, + refreshing: false, + colors: ['red'], + progressViewOffset: 0, + enabled: true, + }); }); it('enables refresh only with onRefresh', () => { diff --git a/src/props.ts b/src/props.ts index 5ca58f0..aa2ff8c 100644 --- a/src/props.ts +++ b/src/props.ts @@ -176,6 +176,8 @@ export type Refresh = { colors?: ReadonlyArray; tintColor?: ColorValue; progressViewOffset: number; + // RefreshControl's enabled, which turns pull to refresh off on Android. + enabled: boolean; }; // As in VirtualizedList, a RefreshControl element replaces the list's own, so its props win. @@ -189,6 +191,7 @@ export function refreshOf(props: FlumeProps): Refresh { colors: given.colors, tintColor: given.tintColor, progressViewOffset: given.progressViewOffset ?? 0, + enabled: given.enabled !== false, }; } return { @@ -197,6 +200,7 @@ export function refreshOf(props: FlumeProps): Refresh { colors: control?.colors, tintColor: control?.tintColor, progressViewOffset: control?.progressViewOffset ?? 0, + enabled: true, }; } // Props that FlashList and LegendList type as nullable, where null means not given. @@ -304,7 +308,7 @@ export function nativeProps(given: FlumeProps, warn: Warn): FlatProps { viewabilityConfig: viewability(props.viewabilityConfig, warn), endReachedThreshold: props.onEndReachedThreshold ?? 2, startReachedThreshold: props.onStartReachedThreshold ?? 2, - refreshEnabled: refresh.onRefresh !== undefined, + refreshEnabled: refresh.enabled && refresh.onRefresh !== undefined, refreshing: refresh.refreshing, refreshColors: refresh.colors, refreshProgressViewOffset: refresh.progressViewOffset, From 29f360760fa5c304c3bd3cc43e75c44a5d625352 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 00:23:06 +0100 Subject: [PATCH 13/14] fix: take a leaving row's snapshot from a committed render --- src/FlumeSlot.tsx | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/FlumeSlot.tsx b/src/FlumeSlot.tsx index 1678226..bd82a1a 100644 --- a/src/FlumeSlot.tsx +++ b/src/FlumeSlot.tsx @@ -1,4 +1,4 @@ -import { memo, type ReactElement, useRef } from 'react'; +import { memo, type ReactElement, useLayoutEffect, useRef } from 'react'; import { Keyboard } from 'react-native'; import { SlotKind, type SlotLayout, slotStyle } from './slots'; import FlumeSlotViewNativeComponent from './specs/FlumeSlotViewNativeComponent'; @@ -50,23 +50,26 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl type?: string; data?: readonly unknown[]; }>({}); - // A row that left the data renders its exit with what it had, type and data included. - if (item !== undefined && render !== undefined) { - last.current = { item, render, type, data: dataRef.current }; - } + // A row that left the data renders its exit with what it last committed, type and data included. + const live = item !== undefined && render !== undefined; + const shown = live ? { item, render, type, data: dataRef.current } : last.current; + // Written after the commit, so a render React discards cannot change the snapshot. + useLayoutEffect(() => { + if (live) last.current = shown; + }); const entry = { slot, kind, key: itemKey, index, bound: true, minMain }; const style = slotStyle(entry, fullSpan, layout); if (style === null) return null; const cell = kind === SlotKind.row || kind === SlotKind.sticky; const handled = keyboardTaps === 'handled'; const content = cell - ? (last.current.render?.({ - item: last.current.item, + ? (shown.render?.({ + item: shown.item, index, target: kind === SlotKind.sticky ? 'StickyHeader' : 'Cell', extraData, - data: last.current.data ?? dataRef.current, - type: last.current.type ?? type, + data: shown.data ?? dataRef.current, + type: shown.type ?? type, }) ?? null) : element; return ( From 4c59ab3798cf1737f0795ac595903eb19da1f5c3 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 00:23:08 +0100 Subject: [PATCH 14/14] test: render Text children in the fragment test --- src/__tests__/Flume.test.tsx | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index 65482b3..e8d737a 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -472,14 +472,19 @@ describe('Flume React cells', () => { expect(infos.at(-1)?.type).toBe('photo'); }); - it('renders a string or a fragment from renderItem', async () => { + it('renders a fragment from renderItem', async () => { installHost(); const { Flume } = await import('../Flume'); - for (const renderItem of [() => 'text', () => createElement(Fragment, null, 'a', 'b')]) { - const tree = await mount(createElement(Flume, { data: [item], renderItem })); - await sendSlots(tree, [rowEntry(1, 'a', 0)]); - expect(slotViews(tree, 1)).toHaveLength(1); - } + const renderItem = () => + createElement( + Fragment, + null, + createElement('Text', null, 'a'), + createElement('Text', null, 'b'), + ); + const tree = await mount(createElement(Flume, { data: [item], renderItem })); + await sendSlots(tree, [rowEntry(1, 'a', 0)]); + expect(slotViews(tree, 1)).toHaveLength(1); }); it('renders the new item in the commit that changes the data', async () => {