From 424948994b882df92843a3c26dcb3c5e367925ae Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 22:19:49 +0100 Subject: [PATCH 1/3] feat: pass separators in the renderItem info FlatList passes separators to renderItem so a row can highlight its own separator and the one above it, and update their props. Flume passed nothing, so separators.highlight() threw in code moved from FlatList. Each React row now gets a stable separators object, routed by key to the separators of the row and of the row before it in the latest data. --- src/Flume.tsx | 10 ++- src/FlumeSlot.tsx | 42 ++++++++++- src/__tests__/Flume.test.tsx | 121 ++++++++++++++++++++++++++++++- src/__tests__/separators.test.ts | 52 ++++++++++++- src/separators.ts | 42 +++++++++++ src/types.ts | 8 ++ 6 files changed, 266 insertions(+), 9 deletions(-) diff --git a/src/Flume.tsx b/src/Flume.tsx index d676d6c..bbef495 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -22,7 +22,7 @@ import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './da import { FlumeSlot } from './FlumeSlot'; import { hostProps } from './foreign'; import { contentPadding, nativeProps, refreshOf, settleProps, stickyIndicesOf } from './props'; -import { lastRowStart } from './separators'; +import { createSeparatorLinks, lastRowStart } from './separators'; import { applySnapshot, gridCellWidth, @@ -132,6 +132,12 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { count.current = data.length; const dataRef = useRef(data); dataRef.current = 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: [], + index: new Map(), + }); + const links = useMemo(() => createSeparatorLinks(separatorKeys), []); // Each distinct message reports once per mount, in development only. const report = useCallback((level: 'warn' | 'error', message: string) => { @@ -342,6 +348,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { return [...bySlot.values()].sort((a, b) => a.slot - b.slot); }, [fresh, table]); const { next } = commit.diff; + separatorKeys.current = next; const lastStart = lastRowStart(next.keys.length, horizontal ? 1 : numColumns, stickyIndices); const separator = (ItemSeparatorComponent ?? null) as | ComponentType> @@ -372,6 +379,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { render={resolved?.kind === 'react' ? (resolved.render as ReactCell) : undefined} type={type ?? 'default'} dataRef={dataRef} + links={links} element={elementFor(entry.kind)} extraData={extraData} keyboardTaps={keyboardShouldPersistTaps ?? 'never'} diff --git a/src/FlumeSlot.tsx b/src/FlumeSlot.tsx index 1e1633a..5aabb9e 100644 --- a/src/FlumeSlot.tsx +++ b/src/FlumeSlot.tsx @@ -9,11 +9,13 @@ import { useLayoutEffect, useMemo, useRef, + useState, } from 'react'; import { Keyboard, View } from 'react-native'; +import type { SeparatorLinks } from './separators'; import { SlotKind, type SlotLayout, slotStyle } from './slots'; import FlumeSlotViewNativeComponent from './specs/FlumeSlotViewNativeComponent'; -import type { ReactCell, SeparatorProps } from './types'; +import type { ReactCell, SeparatorProps, Separators } from './types'; type FlumeSlotProps = { slot: number; @@ -36,8 +38,28 @@ type FlumeSlotProps = { last: boolean; trailingItem: unknown; inverted: boolean; + links: SeparatorLinks; }; +type SeparatorCellProps = { + component: ComponentType>; + itemKey: string; + links: SeparatorLinks; + leadingItem: unknown; + trailingItem: unknown; +}; + +// Holds what highlight and updateProps sent, so they re-render the separator alone. +const SeparatorCell = memo(function SeparatorCell(props: SeparatorCellProps): ReactElement { + const { component, itemKey, links, leadingItem, trailingItem } = props; + const [sent, setSent] = useState>({}); + useLayoutEffect( + () => links.register(itemKey, (update) => setSent((current) => ({ ...current, ...update }))), + [links, itemKey], + ); + return createElement(component, { leadingItem, trailingItem, highlighted: false, ...sent }); +}); + type Shown = { item?: unknown; render?: ReactCell; @@ -77,7 +99,16 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl last, trailingItem, inverted, + links, } = props; + const separators = useMemo( + () => ({ + highlight: () => links.highlight(itemKey, true), + unhighlight: () => links.highlight(itemKey, false), + updateProps: (select, newProps) => links.update(itemKey, select, newProps), + }), + [links, itemKey], + ); const snapshot = useRef({}); // A row that left the data renders its exit with what it last committed, type and data included. const live = item !== undefined && render !== undefined; @@ -103,11 +134,12 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl index: rowIndex, target, extraData, + separators, data: shown.data ?? dataRef.current, type: shown.type ?? type, }) ?? null) : null, - [cell, shown.render, shown.item, rowIndex, target, extraData, shown.type, type], + [cell, shown.render, shown.item, rowIndex, target, extraData, separators, shown.type, type], ); const entry = { slot, kind, key: itemKey, index: rowIndex, bound: true, minMain }; const style = slotStyle(entry, span, layout); @@ -119,10 +151,12 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl separator !== null && shown.last === false ? isValidElement(separator) ? separator - : createElement(separator, { + : createElement(SeparatorCell, { + component: separator, + itemKey, + links, leadingItem: shown.item, trailingItem: shown.trailingItem, - highlighted: false, }) : null; // Keyed, so the row keeps its state when its separator or the separator prop comes or goes. diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index e8123d3..d3ab031 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -455,6 +455,7 @@ describe('Flume React cells', () => { extraData: undefined, data: [item], type: 'default', + separators: expect.any(Object), }); }); @@ -606,6 +607,7 @@ describe('Flume React cells', () => { extraData: undefined, data: [item], type: 'default', + separators: expect.any(Object), }); }); @@ -1144,10 +1146,16 @@ describe('Flume item separators', () => { node.props.itemKey === key && node.props.kind === kind, ); + const nameOf = (node: ReactTestInstance): string => + typeof node.type === 'string' ? node.type : (node.type as { name: string }).name; + // The separator renders inside the slot's SeparatorCell, which holds its highlight state. const childTypes = (slot: ReactTestInstance) => - (slot.children as ReactTestInstance[]).map((child) => - typeof child.type === 'string' ? child.type : (child.type as { name: string }).name, - ); + (slot.children as ReactTestInstance[]).map((child) => { + const [inner] = child.children as ReactTestInstance[]; + return nameOf(child) === 'SeparatorCell' && inner !== undefined + ? nameOf(inner) + : nameOf(child); + }); function expectSeparated(tree: ReactTestRenderer, key: string, separated: boolean) { const slots = slotsOfKey(tree, key); expect(slots.length).toBeGreaterThan(0); @@ -1402,3 +1410,110 @@ describe('Flume item separators', () => { expect(slot.props.style).toEqual({ position: 'absolute', width: 150 }); }); }); + +describe('Flume separators in the info', () => { + const rows = ['a', 'b', 'c', 'd', 'e'].map((id) => ({ id })); + type SepProps = { leadingItem: { id: string }; highlighted: boolean; color?: string }; + function setup() { + const seen: SepProps[] = []; + const Sep = (p: SepProps) => { + seen.push(p); + return createElement('Sep'); + }; + const infos = new Map[]>(); + const renderItem = (info: CellInfo<{ id: string }>) => { + infos.set(info.item.id, [...(infos.get(info.item.id) ?? []), info]); + return createElement('Row'); + }; + const latest = (id: string) => seen.filter((p) => p.leadingItem.id === id).at(-1); + const separatorsOf = (id: string) => infos.get(id)?.at(-1)?.separators; + return { Sep, renderItem, infos, latest, separatorsOf }; + } + async function mountRows(Sep: unknown, renderItem: unknown, data = rows, extraData?: unknown) { + const { Flume } = await import('../Flume'); + const element = (list: typeof rows, extra?: unknown) => + createElement(Flume, { + data: list, + renderItem: renderItem as (info: CellInfo) => ReturnType, + ItemSeparatorComponent: Sep as () => ReturnType, + extraData: extra, + }); + const tree = await mount(element(data, extraData)); + await sendSlots( + tree, + data.map((row, i) => rowEntry(i + 1, row.id, i)), + ); + return { tree, element }; + } + + it('highlights the separators of the row and the row before it', async () => { + installHost(); + const { Sep, renderItem, latest, separatorsOf } = setup(); + await mountRows(Sep, renderItem); + await act(async () => { + separatorsOf('d')?.highlight(); + }); + expect(latest('c')?.highlighted).toBe(true); + expect(latest('d')?.highlighted).toBe(true); + for (const id of ['a', 'b']) expect(latest(id)?.highlighted).toBe(false); + await act(async () => { + separatorsOf('d')?.unhighlight(); + }); + expect(latest('c')?.highlighted).toBe(false); + expect(latest('d')?.highlighted).toBe(false); + }); + + it('merges updateProps into the leading or trailing separator', async () => { + installHost(); + const { Sep, renderItem, latest, separatorsOf } = setup(); + await mountRows(Sep, renderItem); + await act(async () => { + separatorsOf('c')?.updateProps('leading', { color: 'red' }); + separatorsOf('c')?.updateProps('trailing', { color: 'blue' }); + }); + expect(latest('b')?.color).toBe('red'); + expect(latest('c')?.color).toBe('blue'); + expect(latest('a')?.color).toBeUndefined(); + }); + + it('keeps one separators object per row across renders', async () => { + installHost(); + const { Sep, renderItem, infos } = setup(); + const { tree, element } = await mountRows(Sep, renderItem); + // Native registered every pre-rendered slot, so each key has one slot from here on. + await sendSlots( + tree, + rows.map((row, i) => rowEntry(i + 1, row.id, i)), + -1, + -100, + ); + infos.clear(); + for (const extra of [1, 2]) { + await act(async () => { + tree.update(element(rows, extra)); + }); + } + const seen = infos.get('b') ?? []; + expect(seen.length).toBe(2); + expect(seen[0]?.separators).toBeDefined(); + expect(new Set(seen.map((info) => info.separators)).size).toBe(1); + }); + + it('leaves the new row before unhighlighted when the highlighted row before is deleted', async () => { + installHost(); + const { Sep, renderItem, latest, separatorsOf } = setup(); + const { tree, element } = await mountRows(Sep, renderItem); + await act(async () => { + separatorsOf('d')?.highlight(); + }); + await act(async () => { + tree.update(element(rows.filter((row) => row.id !== 'c'))); + }); + expect(latest('b')?.highlighted).toBe(false); + await act(async () => { + separatorsOf('d')?.unhighlight(); + }); + expect(latest('b')?.highlighted).toBe(false); + expect(latest('d')?.highlighted).toBe(false); + }); +}); diff --git a/src/__tests__/separators.test.ts b/src/__tests__/separators.test.ts index 1fc5a36..2698fd3 100644 --- a/src/__tests__/separators.test.ts +++ b/src/__tests__/separators.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { lastRowStart } from '../separators'; +import { createSeparatorLinks, lastRowStart } from '../separators'; // The same table as cpp/tests/separator_rule_test.cpp: count, columns, full-span indices, first index of the last row. const CASES: [number, number, number[], number][] = [ @@ -20,3 +20,53 @@ describe('lastRowStart', () => { }, ); }); + +describe('separator links', () => { + const state = (keys: string[]) => ({ + current: { keys, index: new Map(keys.map((key, i) => [key, i] as const)) }, + }); + + it('highlights this row and the row before it', () => { + const links = createSeparatorLinks(state(['a', 'b', 'c'])); + const got: [string, Record][] = []; + for (const key of ['a', 'b', 'c']) links.register(key, (props) => got.push([key, props])); + links.highlight('c', true); + expect(got).toEqual([ + ['c', { highlighted: true }], + ['b', { highlighted: true }], + ]); + }); + + it('sends leading props to the row before and trailing props to this row', () => { + const links = createSeparatorLinks(state(['a', 'b'])); + const got: [string, Record][] = []; + for (const key of ['a', 'b']) links.register(key, (props) => got.push([key, props])); + links.update('b', 'leading', { color: 'red' }); + links.update('b', 'trailing', { color: 'blue' }); + expect(got).toEqual([ + ['a', { color: 'red' }], + ['b', { color: 'blue' }], + ]); + }); + + it('reaches every slot of a key and none after unregistering', () => { + const links = createSeparatorLinks(state(['a'])); + const got: string[] = []; + const off = links.register('a', () => got.push('row')); + links.register('a', () => got.push('sticky')); + links.highlight('a', true); + off(); + links.highlight('a', false); + expect(got).toEqual(['row', 'sticky', 'sticky']); + }); + + it('reads the row before from the latest data', () => { + const data = state(['a', 'b', 'c']); + const links = createSeparatorLinks(data); + const got: string[] = []; + for (const key of ['a', 'b', 'c']) links.register(key, () => got.push(key)); + data.current = state(['a', 'c']).current; + links.highlight('c', true); + expect(got).toEqual(['c', 'a']); + }); +}); diff --git a/src/separators.ts b/src/separators.ts index c4c4316..98e245a 100644 --- a/src/separators.ts +++ b/src/separators.ts @@ -18,3 +18,45 @@ export function lastRowStart( const run = count - runStart; return count - (run % numColumns || numColumns); } + +export type SeparatorUpdate = (props: Record) => void; + +export type SeparatorLinks = { + register(key: string, update: SeparatorUpdate): () => void; + highlight(key: string, on: boolean): void; + update(key: string, select: 'leading' | 'trailing', props: Record): void; +}; + +type DataKeys = { readonly keys: readonly string[]; readonly index: ReadonlyMap }; + +// FlatList's separators routing by key: a row reaches its own separator and the one of the row before it, read from +// the latest data when called. A key can have a row and a sticky copy, so each key holds a set. +export function createSeparatorLinks(data: { readonly current: DataKeys }): SeparatorLinks { + const updates = new Map>(); + const send = (key: string | undefined, props: Record) => { + if (key === undefined) return; + for (const update of updates.get(key) ?? []) update(props); + }; + const before = (key: string): string | undefined => { + const index = data.current.index.get(key); + return index === undefined || index === 0 ? undefined : data.current.keys[index - 1]; + }; + return { + register(key, update) { + const set = updates.get(key) ?? new Set(); + updates.set(key, set); + set.add(update); + return () => { + set.delete(update); + if (set.size === 0 && updates.get(key) === set) updates.delete(key); + }; + }, + highlight(key, on) { + send(key, { highlighted: on }); + send(before(key), { highlighted: on }); + }, + update(key, select, props) { + send(select === 'leading' ? before(key) : key, props); + }, + }; +} diff --git a/src/types.ts b/src/types.ts index 59eed21..34dc74d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -206,12 +206,20 @@ export type LegendListAnchoring = { export type ScrollHandler = (event: NativeSyntheticEvent) => void; +// FlatList's: highlight and unhighlight reach this row's separator and the one before it. +export type Separators = { + highlight: () => void; + unhighlight: () => void; + updateProps: (select: 'leading' | 'trailing', newProps: Record) => void; +}; + // FlashList's render info; a pinned copy of a sticky row renders with the StickyHeader target. export type CellInfo = { item: T; index: number; target: 'Cell' | 'StickyHeader'; extraData?: unknown; + separators: Separators; // LegendList's fields: the data of the render that last drew the row, and the item's type. data: readonly T[]; type: string; From 9592bcabfd5fcd0cacefb451fe6c8d3b97820dbf Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 22:22:11 +0100 Subject: [PATCH 2/3] feat: accept ListItemComponent and CellRendererComponent FlatList code can render rows through ListItemComponent and wrap each cell in CellRendererComponent, and Flume had neither. ListItemComponent now takes the renderItem info as props and wins over renderItem, with FlatList's warning when both are given. CellRendererComponent wraps a React row and its separator inside the row's cell. Worklet rows have no React host, so it warns when the list has them. --- src/Flume.tsx | 23 +++++- src/FlumeSlot.tsx | 20 +++++- src/__tests__/Flume.test.tsx | 131 ++++++++++++++++++++++++++++++++++- src/cells.ts | 10 ++- src/foreign.ts | 2 + src/types.ts | 13 ++++ 6 files changed, 193 insertions(+), 6 deletions(-) diff --git a/src/Flume.tsx b/src/Flume.tsx index bbef495..776fcdd 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -17,7 +17,7 @@ import { } from 'react'; import { type StyleProp, View, type ViewStyle } from 'react-native'; import { createSerializable } from 'react-native-worklets'; -import { cellKinds, type ResolvedCell, resolveCell } from './cells'; +import { cellKinds, itemComponentCell, type ResolvedCell, resolveCell } from './cells'; import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data'; import { FlumeSlot } from './FlumeSlot'; import { hostProps } from './foreign'; @@ -42,6 +42,7 @@ import FlumeViewNativeComponent, { import { logSetData, statsEnabled } from './stats'; import { getHost, isDev } from './store'; import type { + CellRendererProps, FlumeProps, FlumeRef, PressInfo, @@ -66,7 +67,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { const { data, renderCell, - renderItem, + renderItem: givenRenderItem, reactCells, keyExtractor, getItemType, @@ -82,6 +83,8 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { ListFooterComponentStyle, ListEmptyComponentStyle, ItemSeparatorComponent, + ListItemComponent, + CellRendererComponent, inverted, itemAnimations = true, onPress, @@ -146,6 +149,18 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { console[level](`react-native-flume: ${message}`); }, []); const warn = useCallback((message: string) => report('warn', message), [report]); + // Memoized on the component, so every slot keeps its memo while it stays the same. + const itemCell = useMemo( + () => (ListItemComponent == null ? undefined : itemComponentCell(ListItemComponent)), + [ListItemComponent], + ); + const renderItem = itemCell ?? givenRenderItem; + if (itemCell !== undefined && givenRenderItem !== undefined) { + warn('ListItemComponent takes precedence over renderItem'); + } + if (CellRendererComponent != null && renderCell !== undefined) { + warn('CellRendererComponent wraps React rows only; worklet rows ignore it'); + } if (renderCell !== undefined && renderItem !== undefined) { warn('renderItem is ignored when renderCell is given; use reactCells to mix the two'); @@ -350,6 +365,9 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { const { next } = commit.diff; separatorKeys.current = next; const lastStart = lastRowStart(next.keys.length, horizontal ? 1 : numColumns, stickyIndices); + const cellRenderer = (CellRendererComponent ?? null) as ComponentType< + CellRendererProps + > | null; const separator = (ItemSeparatorComponent ?? null) as | ComponentType> | ReactElement @@ -380,6 +398,7 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { type={type ?? 'default'} dataRef={dataRef} links={links} + cellRenderer={row ? cellRenderer : null} element={elementFor(entry.kind)} extraData={extraData} keyboardTaps={keyboardShouldPersistTaps ?? 'never'} diff --git a/src/FlumeSlot.tsx b/src/FlumeSlot.tsx index 5aabb9e..97a5b03 100644 --- a/src/FlumeSlot.tsx +++ b/src/FlumeSlot.tsx @@ -15,7 +15,7 @@ import { Keyboard, View } from 'react-native'; import type { SeparatorLinks } from './separators'; import { SlotKind, type SlotLayout, slotStyle } from './slots'; import FlumeSlotViewNativeComponent from './specs/FlumeSlotViewNativeComponent'; -import type { ReactCell, SeparatorProps, Separators } from './types'; +import type { CellRendererProps, ReactCell, SeparatorProps, Separators } from './types'; type FlumeSlotProps = { slot: number; @@ -39,6 +39,7 @@ type FlumeSlotProps = { trailingItem: unknown; inverted: boolean; links: SeparatorLinks; + cellRenderer: ComponentType> | null; }; type SeparatorCellProps = { @@ -77,6 +78,7 @@ const closeKeyboard = () => Keyboard.dismiss(); // FlashList's horizontal cell: the row keeps its height and the separator stretches to it. const SIDE_BY_SIDE = { flexDirection: 'row', alignSelf: 'flex-start' } as const; +const ROW = { flexDirection: 'row' } as const; // One React cell. A key that left the data keeps its last item and renderer while native still lists the slot. export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactElement | null { @@ -100,6 +102,7 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl trailingItem, inverted, links, + cellRenderer, } = props; const separators = useMemo( () => ({ @@ -166,10 +169,23 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl ]; if (inverted) parts.reverse(); content = - layout.horizontal && separator !== null + layout.horizontal && separator !== null && cellRenderer === null ? createElement(View, { style: SIDE_BY_SIDE }, parts) : parts; } + // FlatList's cell renderer holds the row and its separator, laid out in a row when horizontal. + if (cell && cellRenderer !== null) { + content = createElement( + cellRenderer, + { + cellKey: itemKey, + index: rowIndex, + item: shown.item, + style: layout.horizontal ? ROW : undefined, + }, + content, + ); + } return ( { expect(latest('d')?.highlighted).toBe(false); }); }); + +describe('Flume ListItemComponent and CellRendererComponent', () => { + const a = { id: 'a' }; + const b = { id: 'b' }; + const Sep = () => createElement('Sep'); + const keyed = (tree: ReactTestRenderer, key: string) => + tree.root.findAll( + (node) => String(node.type) === 'FlumeSlotView' && node.props.itemKey === key, + ); + + it('renders ListItemComponent with the info in place of renderItem', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const got: CellInfo[] = []; + const Item = (info: CellInfo) => { + got.push(info); + return createElement('ItemNode'); + }; + const renderItem = vi.fn(() => createElement('Row')); + const tree = await mount( + createElement(Flume, { data: [a, b], renderItem, ListItemComponent: Item }), + ); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1)]); + expect(renderItem).not.toHaveBeenCalled(); + expect( + got.some((info) => info.item === a && info.index === 0 && info.separators !== undefined), + ).toBe(true); + expect(tree.root.findAll((node) => String(node.type) === 'ItemNode').length).toBeGreaterThan(0); + expect(warn.mock.calls.filter(([m]) => String(m).includes('ListItemComponent'))).toHaveLength( + 1, + ); + warn.mockRestore(); + }); + + it('keeps every slot memoized while ListItemComponent stays the same', async () => { + installHost(); + const { Flume } = await import('../Flume'); + let renders = 0; + const Item = () => { + renders++; + return createElement('ItemNode'); + }; + const data = [a, b]; + const tree = await mount(createElement(Flume, { data, ListItemComponent: Item })); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1)]); + const before = renders; + expect(before).toBeGreaterThan(0); + await act(async () => { + tree.update(createElement(Flume, { data, ListItemComponent: Item })); + }); + expect(renders).toBe(before); + }); + + it('wraps the row and its separator in CellRendererComponent', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const got: Record[] = []; + const Cell = (props: { + cellKey: string; + index: number; + item: unknown; + style?: unknown; + children?: ReactNode; + }) => { + got.push({ + cellKey: props.cellKey, + index: props.index, + item: props.item, + style: props.style, + }); + return createElement('CellNode', null, props.children); + }; + const element = (horizontal: boolean) => + createElement(Flume, { + data: [a, b], + renderItem: () => createElement('Row'), + ItemSeparatorComponent: Sep, + CellRendererComponent: Cell, + horizontal, + }); + const tree = await mount(element(false)); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1)]); + expect(got).toContainEqual({ cellKey: 'a', index: 0, item: a, style: undefined }); + for (const slot of keyed(tree, 'a')) { + const [cell] = slot.children as ReactTestInstance[]; + expect(String(cell?.type)).not.toBe('View'); + const node = cell?.find((n) => String(n.type) === 'CellNode'); + expect(node?.findAll((n) => String(n.type) === 'Row')).toHaveLength(1); + expect(node?.findAllByType(Sep)).toHaveLength(1); + } + got.length = 0; + await act(async () => { + tree.update(element(true)); + }); + expect(got).toContainEqual({ + cellKey: 'a', + index: 0, + item: a, + style: { flexDirection: 'row' }, + }); + }); + + it('warns once when CellRendererComponent is given with worklet rows', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const Cell = (props: { children?: ReactNode }) => + createElement('CellNode', null, props.children); + const tree = await mount( + createElement(Flume, { data: [a], renderCell, CellRendererComponent: Cell }), + ); + await act(async () => { + tree.update(createElement(Flume, { data: [a, b], renderCell, CellRendererComponent: Cell })); + }); + expect( + warn.mock.calls.filter(([m]) => String(m).includes('CellRendererComponent')), + ).toHaveLength(1); + warn.mockRestore(); + }); +}); diff --git a/src/cells.ts b/src/cells.ts index 370ecdc..b18c135 100644 --- a/src/cells.ts +++ b/src/cells.ts @@ -1,5 +1,13 @@ +import { type ComponentType, createElement, isValidElement, type ReactElement } from 'react'; import type { SettledProps } from './props'; -import type { ReactCell } from './types'; +import type { CellInfo, ReactCell } from './types'; + +// FlatList's ListItemComponent: a component takes the info as props, an element renders as given. +export function itemComponentCell( + component: ComponentType> | ReactElement, +): ReactCell { + return isValidElement(component) ? () => component : (info) => createElement(component, info); +} export type ResolvedCell = | { kind: 'worklet' } diff --git a/src/foreign.ts b/src/foreign.ts index dbaa347..0376159 100644 --- a/src/foreign.ts +++ b/src/foreign.ts @@ -140,6 +140,8 @@ export const OWN_KEYS = [ 'initialScrollIndex', 'separator', 'ItemSeparatorComponent', + 'ListItemComponent', + 'CellRendererComponent', 'stickyHeaderIndices', 'ListHeaderComponent', 'ListFooterComponent', diff --git a/src/types.ts b/src/types.ts index 34dc74d..96d91de 100644 --- a/src/types.ts +++ b/src/types.ts @@ -227,6 +227,15 @@ export type CellInfo = { export type ReactCell = (info: CellInfo) => ReactNode; +// FlatList's CellRendererComponent props; it wraps a React row and its separator inside the row's cell. +export type CellRendererProps = { + cellKey: string; + index: number; + item: T; + style?: StyleProp; + children?: ReactNode; +}; + // What ItemSeparatorComponent gets: FlatList's props and FlashList's trailingItem. export type SeparatorProps = { leadingItem: T; @@ -266,6 +275,10 @@ export type FlumeOwnProps = { separator?: { size: number; color?: string; insetStart?: number; insetEnd?: number }; // Drawn inside a React row's cell after the row, before it when inverted; none in the last grid row. ItemSeparatorComponent?: ComponentType> | ReactElement | null; + // FlatList's: takes the renderItem info as props and wins over renderItem; an element renders as given. + ListItemComponent?: ComponentType> | ReactElement | null; + // Wraps each React row and its separator inside the row's cell; worklet rows have no React host. + CellRendererComponent?: ComponentType> | null; // Data indices, as FlashList counts them; FlatList counts the header too. stickyHeaderIndices?: readonly number[] | null; // Rows around the data; the empty one shows instead of the data while it is empty, filling the viewport. From c510b54c0f4185491cd698b9c094d1fd068abbb8 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sun, 22 Nov 2026 20:57:59 +0100 Subject: [PATCH 3/3] fix: route separator calls by the rows on screen when React drops a render The separators of a row found the row before it in a lookup written during render. When a transition suspended elsewhere, React kept the old rows on screen and dropped the new render, but the lookup already held the new order, so highlighting c in a, b, c lit the separator after a instead of b. The lookup is now written in an insertion effect, which runs only for a commit and before any layout effect reads it. --- src/Flume.tsx | 6 ++++- src/__tests__/Flume.test.tsx | 49 +++++++++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/Flume.tsx b/src/Flume.tsx index 776fcdd..d561a75 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -9,6 +9,7 @@ import { useCallback, useEffect, useImperativeHandle, + useInsertionEffect, useLayoutEffect, useMemo, useReducer, @@ -363,7 +364,10 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { return [...bySlot.values()].sort((a, b) => a.slot - b.slot); }, [fresh, table]); const { next } = commit.diff; - separatorKeys.current = next; + // Before every layout effect of the commit, and never from a render React throws away. + useInsertionEffect(() => { + separatorKeys.current = next; + }, [next]); const lastStart = lastRowStart(next.keys.length, horizontal ? 1 : numColumns, stickyIndices); const cellRenderer = (CellRendererComponent ?? null) as ComponentType< CellRendererProps diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index 8f188d8..ffddc39 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -4,6 +4,8 @@ import { Fragment, type ReactNode, StrictMode, + Suspense, + startTransition, useEffect, useState, } from 'react'; @@ -1443,7 +1445,7 @@ describe('Flume separators in the info', () => { createElement(Flume, { data: list, renderItem: renderItem as (info: CellInfo) => ReturnType, - ItemSeparatorComponent: Sep as () => ReturnType, + ItemSeparatorComponent: Sep as unknown as () => ReturnType, extraData: extra, }); const tree = await mount(element(data, extraData)); @@ -1484,6 +1486,51 @@ describe('Flume separators in the info', () => { expect(latest('a')?.color).toBeUndefined(); }); + it('routes a separator call by the rows on screen while a newer render suspends', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Sep, renderItem, latest, separatorsOf } = setup(); + const never = new Promise(() => {}); + // Suspends the transition from outside the list, so React throws away the list's render too. + const Gate = ({ open }: { open: boolean }) => { + if (!open) throw never; + return null; + }; + const element = (list: { id: string }[], open: boolean) => + createElement( + Suspense, + { fallback: null }, + createElement(Flume, { + data: list, + renderItem: renderItem as (info: CellInfo) => ReturnType, + ItemSeparatorComponent: Sep as unknown as () => ReturnType, + }), + createElement(Gate, { open }), + ); + const shown = rows.slice(0, 3); + let tree: ReactTestRenderer | undefined; + await act(async () => { + tree = create(element(shown, true), { + createNodeMock: () => ({}), + unstable_isConcurrent: true, + } as Parameters[1]); + }); + await sendSlots( + tree as ReactTestRenderer, + shown.map((row, i) => rowEntry(i + 1, row.id, i)), + ); + // React keeps a, b, c on screen and throws the render of a, c, b away. + await act(async () => { + startTransition(() => { + tree?.update(element([{ id: 'a' }, { id: 'c' }, { id: 'b' }], false)); + }); + }); + await act(async () => { + separatorsOf('c')?.highlight(); + }); + expect(latest('b')?.highlighted).toBe(true); + expect(latest('a')?.highlighted).toBe(false); + }); it('keeps one separators object per row across renders', async () => { installHost(); const { Sep, renderItem, infos } = setup();