From c08cd22426465b6d9b65be02de67f19ead960c48 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 21:54:38 +0100 Subject: [PATCH 01/22] feat: accept header, footer and empty component styles --- src/Flume.tsx | 24 +++++++++-- src/__tests__/Flume.test.tsx | 81 +++++++++++++++++++++++++++++++++++- src/foreign.ts | 3 ++ src/types.ts | 4 ++ 4 files changed, 106 insertions(+), 6 deletions(-) diff --git a/src/Flume.tsx b/src/Flume.tsx index 8520aa5..c6971b9 100644 --- a/src/Flume.tsx +++ b/src/Flume.tsx @@ -15,6 +15,7 @@ import { useRef, useState, } 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 { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data'; @@ -42,11 +43,14 @@ import { getHost, isDev } from './store'; import type { FlumeProps, FlumeRef, PressInfo, ReactCell, ViewToken } from './types'; // FlatList's rule for the list components: an element renders as given, a component through createElement. +// A given style wraps it in a View, as FlatList and FlashList do. function componentElement( component: ComponentType | ReactElement | null | undefined, + style: StyleProp | null | undefined, ): ReactElement | null { if (component == null) return null; - return isValidElement(component) ? component : createElement(component); + const element = isValidElement(component) ? component : createElement(component); + return style == null ? element : createElement(View, { style }, element); } function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { @@ -66,6 +70,9 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { ListHeaderComponent, ListFooterComponent, ListEmptyComponent, + ListHeaderComponentStyle, + ListFooterComponentStyle, + ListEmptyComponentStyle, itemAnimations = true, onPress, onLongPress, @@ -263,9 +270,18 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { [horizontal, numColumns, padding.top, padding.left, padding.bottom, padding.right, cellWidth], ); const sticky = useMemo(() => new Set(stickyHeaderIndices), [stickyHeaderIndices]); - const header = useMemo(() => componentElement(ListHeaderComponent), [ListHeaderComponent]); - const footer = useMemo(() => componentElement(ListFooterComponent), [ListFooterComponent]); - const empty = useMemo(() => componentElement(ListEmptyComponent), [ListEmptyComponent]); + const header = useMemo( + () => componentElement(ListHeaderComponent, ListHeaderComponentStyle), + [ListHeaderComponent, ListHeaderComponentStyle], + ); + const footer = useMemo( + () => componentElement(ListFooterComponent, ListFooterComponentStyle), + [ListFooterComponent, ListFooterComponentStyle], + ); + const empty = useMemo( + () => componentElement(ListEmptyComponent, ListEmptyComponentStyle), + [ListEmptyComponent, ListEmptyComponentStyle], + ); const elementFor = (kind: number) => kind === SlotKind.header ? header diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index e8d737a..e95f9d0 100644 --- a/src/__tests__/Flume.test.tsx +++ b/src/__tests__/Flume.test.tsx @@ -1,5 +1,5 @@ import { createElement, createRef, Fragment, StrictMode, useEffect, useState } from 'react'; -import { act, create, type ReactTestRenderer } from 'react-test-renderer'; +import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { FlumeHost } from '../store'; import type { CellInfo, FlumeRef } from '../types'; @@ -23,7 +23,10 @@ vi.mock('../specs/FlumeViewNativeComponent', () => ({ }, })); vi.mock('../specs/FlumeSlotViewNativeComponent', () => ({ default: 'FlumeSlotView' })); -vi.mock('react-native', () => ({ Keyboard: { isVisible: vi.fn(() => true), dismiss: vi.fn() } })); +vi.mock('react-native', () => ({ + Keyboard: { isVisible: vi.fn(() => true), dismiss: vi.fn() }, + View: 'View', +})); type DataCall = { storeId: number; @@ -1037,3 +1040,77 @@ describe('Flume refresh', () => { expect(Commands.setNativeRefreshing).not.toHaveBeenCalled(); }); }); + +describe('Flume component styles', () => { + const Header = () => createElement('HeaderNode'); + const Footer = () => createElement('FooterNode'); + const Empty = () => createElement('EmptyNode'); + const entry = (slot: number, kind: number, key: string): Entry => ({ + slot, + kind, + key, + index: -1, + bound: true, + minMain: 0, + }); + const slotOf = (tree: ReactTestRenderer, kind: number) => + tree.root.findAll((node) => String(node.type) === 'FlumeSlotView' && node.props.kind === kind); + + it('wraps the header, footer and empty rows in a View with their style', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const style = { padding: 8 }; + const tree = await mount( + createElement(Flume, { + data: [], + renderItem: () => null, + ListHeaderComponent: Header, + ListFooterComponent: Footer, + ListEmptyComponent: Empty, + ListHeaderComponentStyle: style, + ListFooterComponentStyle: style, + ListEmptyComponentStyle: style, + }), + ); + await sendSlots(tree, [entry(1, 1, 'header'), entry(2, 2, 'footer'), entry(3, 3, 'empty')]); + for (const [kind, component] of [ + [1, Header], + [2, Footer], + [3, Empty], + ] as const) { + const slots = slotOf(tree, kind); + expect(slots.length).toBeGreaterThan(0); + for (const slot of slots) { + const [wrapper] = slot.children as ReactTestInstance[]; + expect(String(wrapper?.type)).toBe('View'); + expect(wrapper?.props.style).toBe(style); + expect(wrapper?.findAllByType(component)).toHaveLength(1); + } + } + }); + + it('adds no wrapper without a style', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const tree = await mount( + createElement(Flume, { + data: [], + renderItem: () => null, + ListHeaderComponent: Header, + ListEmptyComponent: Empty, + }), + ); + await sendSlots(tree, [entry(1, 1, 'header'), entry(3, 3, 'empty')]); + for (const [kind, component] of [ + [1, Header], + [3, Empty], + ] as const) { + const slots = slotOf(tree, kind); + expect(slots.length).toBeGreaterThan(0); + for (const slot of slots) { + const [child] = slot.children as ReactTestInstance[]; + expect(child?.type).toBe(component); + } + } + }); +}); diff --git a/src/foreign.ts b/src/foreign.ts index d942bbc..549f3e2 100644 --- a/src/foreign.ts +++ b/src/foreign.ts @@ -143,6 +143,9 @@ export const OWN_KEYS = [ 'ListHeaderComponent', 'ListFooterComponent', 'ListEmptyComponent', + 'ListHeaderComponentStyle', + 'ListFooterComponentStyle', + 'ListEmptyComponentStyle', 'onScroll', 'onScrollBeginDrag', 'onScrollEndDrag', diff --git a/src/types.ts b/src/types.ts index 02cd118..a216f21 100644 --- a/src/types.ts +++ b/src/types.ts @@ -255,6 +255,10 @@ export type FlumeOwnProps = { ListHeaderComponent?: ComponentType | ReactElement | null; ListFooterComponent?: ComponentType | ReactElement | null; ListEmptyComponent?: ComponentType | ReactElement | null; + // Each wraps its component in a View with this style. + ListHeaderComponentStyle?: StyleProp | null; + ListFooterComponentStyle?: StyleProp | null; + ListEmptyComponentStyle?: StyleProp | null; // The ScrollView events with the ScrollView payload; contentOffset counts from the content start. onScroll?: ScrollHandler | null; onScrollBeginDrag?: ScrollHandler | null; From 8a9f1841e3fbd5447ff115acbf59e8a2c51dd977 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 22:03:30 +0100 Subject: [PATCH 02/22] feat: draw ItemSeparatorComponent on React rows FlatList, FlashList and LegendList code passes ItemSeparatorComponent, and Flume had no such prop. React rows now draw it inside their cell after the row (before it when inverted, beside it when horizontal), with leadingItem, trailingItem and highlighted, and none in the last grid row. The decision reads each row's data index by key, which also stops fullSpan from pairing sticky indices with a slot index native has not updated yet. --- example/src/screens/ReactScreen.tsx | 15 ++ src/Flume.tsx | 29 +++- src/FlumeSlot.tsx | 100 +++++++++--- src/__tests__/Flume.test.tsx | 240 ++++++++++++++++++++++++++++ src/__tests__/separators.test.ts | 22 +++ src/foreign.ts | 1 + src/separators.ts | 20 +++ src/types.ts | 9 ++ 8 files changed, 411 insertions(+), 25 deletions(-) create mode 100644 src/__tests__/separators.test.ts create mode 100644 src/separators.ts diff --git a/example/src/screens/ReactScreen.tsx b/example/src/screens/ReactScreen.tsx index 37f11c1..e6fdc2c 100644 --- a/example/src/screens/ReactScreen.tsx +++ b/example/src/screens/ReactScreen.tsx @@ -128,6 +128,9 @@ const Empty = () => ( ); +const Divider = () => ; +const ChipDivider = () => ; + export default function ReactScreen() { const all = useMemo(() => makeReactRows(), []); const [rows, setRows] = useState(all); @@ -140,6 +143,7 @@ export default function ReactScreen() { const [taps, setTaps] = useState('never'); const [refreshing, setRefreshing] = useState(false); const [pressed, setPressed] = useState('none'); + const [separators, setSeparators] = useState(false); useEffect(() => { showPressed = setPressed; return () => { @@ -156,6 +160,11 @@ export default function ReactScreen() { const n = -++prepended.current; setRows((current) => [{ id: `p${n}`, kind: 'row', title: `Row ${n}`, n }, ...current]); }; + const appended = useRef(0); + const append = () => { + const n = ++appended.current; + setRows((current) => [...current, { id: `a${n}`, kind: 'row', title: `Appended ${n}`, n }]); + }; const refresh = () => { setRefreshing(true); setTimeout(() => setRefreshing(false), 1000); @@ -172,6 +181,8 @@ export default function ReactScreen() { [`Mode ${mode}`, () => setMode((value) => (value === 'react' ? 'mixed' : 'react'))], ['Block JS 3 s', () => blockJs(3000)], ['Prepend', prepend], + ['Append', append], + [`Separators ${separators ? 'off' : 'on'}`, () => setSeparators((on) => !on)], ['Replace all', () => setRows(makeReactRows(500, `v${++version.current}`))], ['Clear', () => setRows([])], ['Refill', () => setRows(all)], @@ -199,6 +210,7 @@ export default function ReactScreen() { (given: FlumeProps, ref: Ref): ReactElement { ListHeaderComponentStyle, ListFooterComponentStyle, ListEmptyComponentStyle, + ItemSeparatorComponent, + inverted, itemAnimations = true, onPress, onLongPress, @@ -332,18 +342,31 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { return [...bySlot.values()].sort((a, b) => a.slot - b.slot); }, [fresh, table]); const { next } = commit.diff; + const lastStart = lastRowStart(next.keys.length, horizontal ? 1 : numColumns, stickyIndices); + const separator = (ItemSeparatorComponent ?? null) as + | ComponentType> + | ReactElement + | null; const cells = entries.map((entry) => { const type = typeOf(next, entry.key); const resolved = type === undefined ? undefined : resolveCell(type, latest.current); + const row = entry.kind === SlotKind.row || entry.kind === SlotKind.sticky; + // By key from the data, since native's table can lag it; a row that left keeps native's index. + const dataIndex = row ? next.index.get(entry.key) : undefined; + const index = dataIndex ?? entry.index; return ( = lastStart} + trailingItem={dataIndex === undefined ? undefined : next.items[dataIndex + 1]} + inverted={inverted === true} layout={layout} item={itemOf(next, entry.key)} render={resolved?.kind === 'react' ? (resolved.render as ReactCell) : undefined} diff --git a/src/FlumeSlot.tsx b/src/FlumeSlot.tsx index bd82a1a..7a3cb7f 100644 --- a/src/FlumeSlot.tsx +++ b/src/FlumeSlot.tsx @@ -1,8 +1,19 @@ -import { memo, type ReactElement, useLayoutEffect, useRef } from 'react'; -import { Keyboard } from 'react-native'; +import { + type ComponentType, + createElement, + Fragment, + isValidElement, + memo, + type ReactElement, + type ReactNode, + useLayoutEffect, + useMemo, + useRef, +} from 'react'; +import { Keyboard, View } from 'react-native'; import { SlotKind, type SlotLayout, slotStyle } from './slots'; import FlumeSlotViewNativeComponent from './specs/FlumeSlotViewNativeComponent'; -import type { ReactCell } from './types'; +import type { ReactCell, SeparatorProps } from './types'; type FlumeSlotProps = { slot: number; @@ -20,12 +31,29 @@ type FlumeSlotProps = { element: ReactElement | null; extraData: unknown; keyboardTaps: 'always' | 'never' | 'handled'; + separator: ComponentType> | ReactElement | null; + // The row is in the last grid row, so it draws no separator. + last: boolean; + trailingItem: unknown; + inverted: boolean; +}; + +type Shown = { + item?: unknown; + render?: ReactCell; + type?: string; + data?: readonly unknown[]; + last?: boolean; + trailingItem?: unknown; }; // ScrollView's handled rule: a tap no child of the cell claims closes the keyboard. const claimsTap = () => Keyboard.isVisible(); 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; + // 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 { const { @@ -43,35 +71,63 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl element, extraData, keyboardTaps, + separator, + last, + trailingItem, + inverted, } = props; - const last = useRef<{ - item?: unknown; - render?: ReactCell; - type?: string; - data?: readonly unknown[]; - }>({}); + 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; - const shown = live ? { item, render, type, data: dataRef.current } : last.current; + const shown: Shown = live + ? { item, render, type, data: dataRef.current, last, trailingItem } + : snapshot.current; // Written after the commit, so a render React discards cannot change the snapshot. useLayoutEffect(() => { - if (live) last.current = shown; + if (live) snapshot.current = shown; }); + const cell = kind === SlotKind.row || kind === SlotKind.sticky; + const target = kind === SlotKind.sticky ? 'StickyHeader' : 'Cell'; + // Apart from the separator, so a row that only gains or loses its separator does not render again. + // biome-ignore lint/correctness/useExhaustiveDependencies: data is the data of the render that drew the row + const rowContent = useMemo( + () => + cell + ? (shown.render?.({ + item: shown.item, + index, + target, + extraData, + data: shown.data ?? dataRef.current, + type: shown.type ?? type, + }) ?? null) + : null, + [cell, shown.render, shown.item, index, target, extraData, shown.type, type], + ); 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 - ? (shown.render?.({ - item: shown.item, - index, - target: kind === SlotKind.sticky ? 'StickyHeader' : 'Cell', - extraData, - data: shown.data ?? dataRef.current, - type: shown.type ?? type, - }) ?? null) - : element; + let content: ReactNode = cell ? rowContent : element; + if (cell && separator !== null) { + const drawn = + shown.last === false + ? isValidElement(separator) + ? separator + : createElement(separator, { + leadingItem: shown.item, + trailingItem: shown.trailingItem, + highlighted: false, + }) + : null; + // Keyed, so the row keeps its state when its separator comes or goes. + const parts = [ + createElement(Fragment, { key: 'row' }, rowContent), + drawn === null ? null : createElement(Fragment, { key: 'separator' }, drawn), + ]; + if (inverted) parts.reverse(); + content = layout.horizontal ? createElement(View, { style: SIDE_BY_SIDE }, parts) : parts; + } return ( { } }); }); + +describe('Flume item separators', () => { + const a = { id: 'a' }; + const b = { id: 'b' }; + const c = { id: 'c' }; + type SepProps = { leadingItem: unknown; trailingItem: unknown; highlighted: boolean }; + function separatorSpy() { + const props: SepProps[] = []; + const Sep = (p: SepProps) => { + props.push(p); + return createElement('Sep'); + }; + return { props, Sep }; + } + function countingCell() { + const calls = new Map(); + const renderItem = (info: CellInfo) => { + const id = (info.item as { id: string }).id; + calls.set(id, (calls.get(id) ?? 0) + 1); + return createElement('Row', { id }); + }; + return { calls, renderItem }; + } + const slotsOfKey = (tree: ReactTestRenderer, key: string, kind = 0) => + tree.root.findAll( + (node) => + String(node.type) === 'FlumeSlotView' && + node.props.itemKey === key && + node.props.kind === kind, + ); + const childTypes = (slot: ReactTestInstance) => + (slot.children as ReactTestInstance[]).map((child) => + typeof child.type === 'string' ? child.type : (child.type as { name: string }).name, + ); + function expectSeparated(tree: ReactTestRenderer, key: string, separated: boolean) { + const slots = slotsOfKey(tree, key); + expect(slots.length).toBeGreaterThan(0); + for (const slot of slots) + expect(childTypes(slot)).toEqual(separated ? ['Row', 'Sep'] : ['Row']); + } + + it('renders the separator after every row but the last', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { props, Sep } = separatorSpy(); + const { renderItem } = countingCell(); + const tree = await mount( + createElement(Flume, { data: [a, b, c], renderItem, ItemSeparatorComponent: Sep }), + ); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1), rowEntry(3, 'c', 2)]); + expectSeparated(tree, 'a', true); + expectSeparated(tree, 'b', true); + expectSeparated(tree, 'c', false); + expect(props).toContainEqual({ leadingItem: a, trailingItem: b, highlighted: false }); + expect(props).toContainEqual({ leadingItem: b, trailingItem: c, highlighted: false }); + }); + + it('re-renders only the old last row on an append', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { props, Sep } = separatorSpy(); + const { calls, renderItem } = countingCell(); + const tree = await mount( + createElement(Flume, { data: [a, b], renderItem, ItemSeparatorComponent: Sep }), + ); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1)]); + calls.clear(); + props.length = 0; + await act(async () => { + tree.update( + createElement(Flume, { data: [a, b, c], renderItem, ItemSeparatorComponent: Sep }), + ); + }); + expect(calls.get('a')).toBeUndefined(); + expect(calls.get('b')).toBeUndefined(); + expect(props.length).toBeGreaterThan(0); + expect(props.every((p) => p.leadingItem === b && p.trailingItem === c)).toBe(true); + expectSeparated(tree, 'b', true); + }); + + it('re-renders the new last row when the last row is deleted', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Sep } = separatorSpy(); + const { calls, renderItem } = countingCell(); + const tree = await mount( + createElement(Flume, { data: [a, b, c], renderItem, ItemSeparatorComponent: Sep }), + ); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1), rowEntry(3, 'c', 2)]); + calls.clear(); + await act(async () => { + tree.update(createElement(Flume, { data: [a, b], renderItem, ItemSeparatorComponent: Sep })); + }); + expect(calls.get('a')).toBeUndefined(); + expect(calls.get('b')).toBeUndefined(); + expectSeparated(tree, 'b', false); + // c left the data and still has its slot: it keeps what it showed. + for (const slot of slotsOfKey(tree, 'c')) expect(childTypes(slot)).toEqual(['Row']); + }); + + it('keeps a leaving row separated as it last committed', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Sep } = separatorSpy(); + const { renderItem } = countingCell(); + const tree = await mount( + createElement(Flume, { data: [a, b, c], renderItem, ItemSeparatorComponent: Sep }), + ); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1), rowEntry(3, 'c', 2)]); + await act(async () => { + tree.update(createElement(Flume, { data: [a, c], renderItem, ItemSeparatorComponent: Sep })); + }); + expectSeparated(tree, 'b', true); + }); + + it('draws one separator per grid item and none in the last grid row', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Sep } = separatorSpy(); + const { renderItem } = countingCell(); + const data = Array.from({ length: 10 }, (_, i) => ({ id: `i${i}` })); + const element = (numColumns: number) => + createElement(Flume, { data, renderItem, numColumns, ItemSeparatorComponent: Sep }); + const tree = await mount(element(3)); + await sendSlots( + tree, + data.map((item, i) => rowEntry(i + 1, item.id, i)), + 100, + 0, + 300, + ); + for (let i = 0; i < 10; i++) expectSeparated(tree, `i${i}`, i < 9); + await act(async () => { + tree.update(element(2)); + }); + for (let i = 0; i < 10; i++) expectSeparated(tree, `i${i}`, i < 8); + }); + + it('renders the separator before the row when inverted', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Sep } = separatorSpy(); + const { renderItem } = countingCell(); + const tree = await mount( + createElement(Flume, { + data: [a, b], + renderItem, + inverted: true, + ItemSeparatorComponent: Sep, + }), + ); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1)]); + for (const slot of slotsOfKey(tree, 'a')) expect(childTypes(slot)).toEqual(['Sep', 'Row']); + for (const slot of slotsOfKey(tree, 'b')) expect(childTypes(slot)).toEqual(['Row']); + }); + + it('puts the row and its separator side by side when horizontal', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Sep } = separatorSpy(); + const { renderItem } = countingCell(); + const tree = await mount( + createElement(Flume, { + data: [a, b], + renderItem, + horizontal: true, + ItemSeparatorComponent: Sep, + }), + ); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1)]); + for (const [key, inside] of [ + ['a', ['Row', 'Sep']], + ['b', ['Row']], + ] as const) { + for (const slot of slotsOfKey(tree, key)) { + const [wrapper] = slot.children as ReactTestInstance[]; + expect(String(wrapper?.type)).toBe('View'); + expect(wrapper?.props.style).toEqual({ flexDirection: 'row', alignSelf: 'flex-start' }); + expect(childTypes(wrapper as ReactTestInstance)).toEqual(inside); + } + } + }); + + it('renders the separator on a sticky copy', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Sep } = separatorSpy(); + const { renderItem } = countingCell(); + const tree = await mount( + createElement(Flume, { data: [a, b], renderItem, ItemSeparatorComponent: Sep }), + ); + await sendSlots(tree, [{ ...rowEntry(7, 'a', 0), kind: 4 }]); + const sticky = slotsOfKey(tree, 'a', 4); + expect(sticky).toHaveLength(1); + expect(childTypes(sticky[0] as ReactTestInstance)).toEqual(['Row', 'Sep']); + }); + + it('draws no separator next to the header and footer', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Sep } = separatorSpy(); + const { renderItem } = countingCell(); + const Header = () => createElement('HeaderNode'); + const tree = await mount( + createElement(Flume, { + data: [a], + renderItem, + ItemSeparatorComponent: Sep, + ListHeaderComponent: Header, + ListFooterComponent: Header, + }), + ); + await sendSlots(tree, [ + { ...rowEntry(1, 'header', -1), kind: 1 }, + rowEntry(2, 'a', 0), + { ...rowEntry(3, 'footer', -1), kind: 2 }, + ]); + expect(tree.root.findAllByType(Sep)).toHaveLength(0); + }); + + it('reads fullSpan from the data index of the key', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { renderItem } = countingCell(); + const tree = await mount( + createElement(Flume, { + data: [a, b, c], + renderItem, + numColumns: 2, + stickyHeaderIndices: [1], + }), + ); + // Native's entry for b still carries index 0 from before a data change. + await sendSlots(tree, [rowEntry(1, 'a', 1), rowEntry(2, 'b', 0)], 150, 0, 300); + for (const slot of slotsOfKey(tree, 'b')) + expect(slot.props.style).toEqual({ position: 'absolute', left: 0, right: 0 }); + for (const slot of slotsOfKey(tree, 'a')) + expect(slot.props.style).toEqual({ position: 'absolute', width: 150 }); + }); +}); diff --git a/src/__tests__/separators.test.ts b/src/__tests__/separators.test.ts new file mode 100644 index 0000000..1fc5a36 --- /dev/null +++ b/src/__tests__/separators.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest'; +import { 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][] = [ + [0, 1, [], 0], + [5, 1, [], 4], + [9, 3, [], 6], + [10, 3, [], 9], + [10, 3, [4], 8], + [10, 3, [9], 9], + [6, 2, [0, 3], 4], +]; + +describe('lastRowStart', () => { + it.each(CASES)( + 'count %i in %i columns with full spans %j starts the last row at %i', + (count, columns, spans, start) => { + expect(lastRowStart(count, columns, spans)).toBe(start); + }, + ); +}); diff --git a/src/foreign.ts b/src/foreign.ts index 549f3e2..dbaa347 100644 --- a/src/foreign.ts +++ b/src/foreign.ts @@ -139,6 +139,7 @@ export const OWN_KEYS = [ 'drawDistance', 'initialScrollIndex', 'separator', + 'ItemSeparatorComponent', 'stickyHeaderIndices', 'ListHeaderComponent', 'ListFooterComponent', diff --git a/src/separators.ts b/src/separators.ts new file mode 100644 index 0000000..c4c4316 --- /dev/null +++ b/src/separators.ts @@ -0,0 +1,20 @@ +// The first index of the last grid row: rows at or past it get no separator. A full-span index ends a run of +// columns, and fullSpans is sorted. Mirrors flume::lastRowStart in cpp/core/SeparatorRule.h. +export function lastRowStart( + count: number, + numColumns: number, + fullSpans: readonly number[], +): number { + if (count <= 0) return 0; + if (numColumns <= 1) return count - 1; + let runStart = 0; + for (let i = fullSpans.length - 1; i >= 0; i--) { + const span = fullSpans[i] ?? -1; + if (span >= count) continue; + if (span === count - 1) return count - 1; + runStart = span + 1; + break; + } + const run = count - runStart; + return count - (run % numColumns || numColumns); +} diff --git a/src/types.ts b/src/types.ts index a216f21..59eed21 100644 --- a/src/types.ts +++ b/src/types.ts @@ -219,6 +219,13 @@ export type CellInfo = { export type ReactCell = (info: CellInfo) => ReactNode; +// What ItemSeparatorComponent gets: FlatList's props and FlashList's trailingItem. +export type SeparatorProps = { + leadingItem: T; + trailingItem: T | undefined; + highlighted: boolean; +} & Record; + export type FlumeOwnProps = { data: readonly T[] | null | undefined; renderCell?: ((item: T, index: number) => CellNode) | null; @@ -249,6 +256,8 @@ export type FlumeOwnProps = { | 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 }; + // Drawn inside a React row's cell after the row, before it when inverted; none in the last grid row. + ItemSeparatorComponent?: ComponentType> | ReactElement | 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 b23f2b1ff8838ea29e2bdbe50d9c2c2ea6c005ee Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 22:17:22 +0100 Subject: [PATCH 03/22] fix(android): apply deferred data in the frame of its mount Data that waits for its pre-rendered React rows applied two posts after the mount batch that registered them, while Fabric drew the rows the same commit re-rendered at once. Appending a row with an item separator showed the old last row with its new separator and the footer still under it for two to three frames. The data now applies right after the mount batch, before the frame is laid out, as iOS already does. A batch that ends before the data reaches the store keeps waiting for it, with the posted refresh as fallback. --- android/src/main/cpp/FlumeJni.cpp | 5 +++ .../main/java/me/sectiontn/flume/FlumeJni.kt | 3 ++ .../main/java/me/sectiontn/flume/FlumeView.kt | 33 ++++++++++++++++++- cpp/bindings/Engine.cpp | 24 +++++++++----- cpp/bindings/Engine.h | 3 ++ cpp/tests/jsi/engine_session_test.cpp | 27 +++++++++++++++ 6 files changed, 86 insertions(+), 9 deletions(-) diff --git a/android/src/main/cpp/FlumeJni.cpp b/android/src/main/cpp/FlumeJni.cpp index f7d5cdb..4b66512 100644 --- a/android/src/main/cpp/FlumeJni.cpp +++ b/android/src/main/cpp/FlumeJni.cpp @@ -95,6 +95,10 @@ struct JFlumeJni : jni::JavaClass { static void refresh(jni::alias_ref, jint storeId) { flume::Engine::instance().refresh(storeId); } + static jboolean applyNow(jni::alias_ref, jint storeId) { + return flume::Engine::instance().applyNow(storeId) ? JNI_TRUE : JNI_FALSE; + } + static void setStatsEnabled(jni::alias_ref, jboolean enabled) { flume::Engine::instance().setStatsEnabled(enabled); } @@ -118,6 +122,7 @@ struct JFlumeJni : jni::JavaClass { makeNativeMethod("releaseHolder", JFlumeJni::releaseHolder), makeNativeMethod("invalidateMeasures", JFlumeJni::invalidateMeasures), makeNativeMethod("refresh", JFlumeJni::refresh), + makeNativeMethod("applyNow", JFlumeJni::applyNow), makeNativeMethod("setStatsEnabled", JFlumeJni::setStatsEnabled), }); } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeJni.kt b/android/src/main/java/me/sectiontn/flume/FlumeJni.kt index bb49b95..604d26d 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeJni.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeJni.kt @@ -41,6 +41,9 @@ object FlumeJni { // Applies data JS deferred until its pre-rendered cells mounted. @JvmStatic external fun refresh(storeId: Int) + // UI thread: applies deferred data now, in the frame of the mount that brought its cells. False when none was pending. + @JvmStatic external fun applyNow(storeId: Int): Boolean + // Binds read the clock and return stats only while this is on. @JvmStatic external fun setStatsEnabled(enabled: Boolean) } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 3bd9413..094df39 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -14,10 +14,14 @@ import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.facebook.react.bridge.ReactContext +import com.facebook.react.bridge.UIManager +import com.facebook.react.bridge.UIManagerListener +import com.facebook.react.common.annotations.UnstableReactNativeAPI import com.facebook.react.uimanager.StateWrapper import com.facebook.react.uimanager.UIManagerHelper import com.facebook.react.uimanager.events.Event import com.facebook.react.uimanager.events.NativeGestureUtil +import com.facebook.react.uimanager.common.UIManagerType import kotlin.math.roundToInt class FlumeView(context: Context) : FrameLayout(context) { @@ -792,6 +796,7 @@ class FlumeView(context: Context) : FrameLayout(context) { } override fun onDetachedFromWindow() { + dropMountListener() adapter.detach() super.onDetachedFromWindow() } @@ -805,11 +810,37 @@ class FlumeView(context: Context) : FrameLayout(context) { } private val dataRefresh = Runnable { if (storeId != 0) FlumeJni.refresh(storeId) } + @OptIn(UnstableReactNativeAPI::class) private var mountListener: UIManagerListener? = null - // Data JS deferred for its pre-rendered cells applies after the mount batch that registers them, once they measured. + // Data JS deferred for its pre-rendered cells applies right after the mount batch that registers them, in the frame + // that shows the rows it re-rendered with them. The post only covers a batch Fabric never reports. + @OptIn(UnstableReactNativeAPI::class) fun refreshData() { removeCallbacks(dataRefresh) post(dataRefresh) + if (mountListener != null) return + val uiManager = UIManagerHelper.getUIManager(context as ReactContext, UIManagerType.FABRIC) ?: return + val listener = object : UIManagerListener { + override fun willDispatchViewUpdates(uiManager: UIManager) = Unit + override fun willMountItems(uiManager: UIManager) = Unit + override fun didDispatchMountItems(uiManager: UIManager) = Unit + override fun didScheduleMountItems(uiManager: UIManager) = Unit + // A batch that lands before the deferred data keeps the listener and the posted fallback. + override fun didMountItems(uiManager: UIManager) { + if (storeId == 0 || !FlumeJni.applyNow(storeId)) return + dropMountListener() + removeCallbacks(dataRefresh) + } + } + mountListener = listener + uiManager.addUIManagerEventListener(listener) + } + + @OptIn(UnstableReactNativeAPI::class) + private fun dropMountListener() { + val listener = mountListener ?: return + mountListener = null + UIManagerHelper.getUIManager(context as ReactContext, UIManagerType.FABRIC)?.removeUIManagerEventListener(listener) } fun setEstimatedItemSize(dp: Double) { diff --git a/cpp/bindings/Engine.cpp b/cpp/bindings/Engine.cpp index cc1e980..9a42543 100644 --- a/cpp/bindings/Engine.cpp +++ b/cpp/bindings/Engine.cpp @@ -133,17 +133,25 @@ void Engine::scheduleRefresh(const std::shared_ptr& store, bool always) { if (scheduler == nullptr) return; std::weak_ptr weak = store; worklets::scheduleOnUI(scheduler, [weak, always] { - auto s = weak.lock(); - if (s == nullptr) return; - std::optional ops = s->list.applyPending(); - if (s->listener == nullptr || (!ops && !always)) return; - ListOps reset; - reset.reset = true; - reset.sticky = s->list.sticky(); - s->listener->onListChanged(always ? reset : *ops, s->list.count()); + if (auto s = weak.lock()) applyPending(*s, always); }); } +bool Engine::applyPending(Store& store, bool always) { + std::optional ops = store.list.applyPending(); + if (store.listener == nullptr || (!ops && !always)) return ops.has_value(); + ListOps reset; + reset.reset = true; + reset.sticky = store.list.sticky(); + store.listener->onListChanged(always ? reset : *ops, store.list.count()); + return ops.has_value(); +} + +bool Engine::applyNow(int storeId) { + auto store = find(storeId); + return store != nullptr && store->list.attached() && applyPending(*store, false); +} + // The JS thread only unregisters. The UI job releases runtime handles under the runtime lock, ~Store the native parts. void Engine::releaseStore(int storeId) { std::shared_ptr scheduler; diff --git a/cpp/bindings/Engine.h b/cpp/bindings/Engine.h index a5e9397..4ef7931 100644 --- a/cpp/bindings/Engine.h +++ b/cpp/bindings/Engine.h @@ -62,6 +62,8 @@ class Engine { void releaseHolder(int storeId, int holderId); void invalidateMeasures(int storeId); // clears the text measure cache void refresh(int storeId); // applies deferred data + // UI thread: applies deferred data now, in the frame of the mount that brought its cells. False when none was pending. + bool applyNow(int storeId); void setStatsEnabled(bool enabled) { statsEnabled_ = enabled; } // any thread; binds read the clock only while on private: @@ -85,6 +87,7 @@ class Engine { std::shared_ptr schedulerOf(int session); std::shared_ptr flumeOf(int session); void scheduleRefresh(const std::shared_ptr& store, bool always); + static bool applyPending(Store& store, bool always); void bindOnRuntime(facebook::jsi::Runtime& rt, int index); void releaseOnRuntime(int storeId); void logLine(const std::string& message); diff --git a/cpp/tests/jsi/engine_session_test.cpp b/cpp/tests/jsi/engine_session_test.cpp index b14156f..448e05f 100644 --- a/cpp/tests/jsi/engine_session_test.cpp +++ b/cpp/tests/jsi/engine_session_test.cpp @@ -181,3 +181,30 @@ TEST_CASE("a sticky-only change reaches the listener as empty ops") { CHECK(listener.calls.back().sticky == std::vector{0, 2}); CHECK(flume::Engine::instance().stickyIndices(id) == std::vector{0, 2}); } + +TEST_CASE("deferred data waits for its cells and applyNow applies it at once") { + ReactSide side; + RecordingListener listener; + int id = stickyStore(side, listener); + listener.calls.clear(); + side.rig.eval( + "__flume.setData(id, ['a', 'b', 'c', 'd'], ['row'], new Int32Array([0, 0, 0, 0]), [], [], true, true, [1]);"); + CHECK(listener.calls.empty()); + CHECK(flume::Engine::instance().applyNow(id)); + REQUIRE(listener.calls.size() == 1); + CHECK(listener.calls.back().inserted == std::vector{{3, 1}}); + CHECK_FALSE(flume::Engine::instance().applyNow(id)); + CHECK(listener.calls.size() == 1); +} + +TEST_CASE("applyNow before the deferred data arrives reports nothing applied") { + ReactSide side; + RecordingListener listener; + int id = stickyStore(side, listener); + listener.calls.clear(); + CHECK_FALSE(flume::Engine::instance().applyNow(id)); + side.rig.eval( + "__flume.setData(id, ['a', 'b', 'c', 'd'], ['row'], new Int32Array([0, 0, 0, 0]), [], [], true, true, [1]);"); + CHECK(flume::Engine::instance().applyNow(id)); + CHECK(listener.calls.size() == 1); +} From 143a58a8b9d9dbc5ae989d02c38f6ddbfd721d4f Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 22:19:49 +0100 Subject: [PATCH 04/22] 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 7a3cb7f..bc78fa6 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; @@ -75,7 +97,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; @@ -98,11 +129,12 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl index, target, extraData, + separators, data: shown.data ?? dataRef.current, type: shown.type ?? type, }) ?? null) : null, - [cell, shown.render, shown.item, index, target, extraData, shown.type, type], + [cell, shown.render, shown.item, index, target, extraData, separators, shown.type, type], ); const entry = { slot, kind, key: itemKey, index, bound: true, minMain }; const style = slotStyle(entry, fullSpan, layout); @@ -114,10 +146,12 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl 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 comes or goes. diff --git a/src/__tests__/Flume.test.tsx b/src/__tests__/Flume.test.tsx index 0a19f64..b5e04a3 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); @@ -1354,3 +1362,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 bf04388e628735211da62bcf5e94725f60bc2fde Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 22:22:11 +0100 Subject: [PATCH 05/22] 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 | 18 ++++- src/__tests__/Flume.test.tsx | 131 ++++++++++++++++++++++++++++++++++- src/cells.ts | 10 ++- src/foreign.ts | 2 + src/types.ts | 13 ++++ 6 files changed, 191 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 bc78fa6..f548a10 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 = { @@ -75,6 +76,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 { @@ -98,6 +100,7 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl trailingItem, inverted, links, + cellRenderer, } = props; const separators = useMemo( () => ({ @@ -160,7 +163,18 @@ export const FlumeSlot = memo(function FlumeSlot(props: FlumeSlotProps): ReactEl drawn === null ? null : createElement(Fragment, { key: 'separator' }, drawn), ]; if (inverted) parts.reverse(); - content = layout.horizontal ? createElement(View, { style: SIDE_BY_SIDE }, parts) : parts; + content = + layout.horizontal && 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, 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 02524b9acd3fa3bef38fde654f9d954eaf4b3c92 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 23:27:00 +0100 Subject: [PATCH 06/22] feat: draw worklet separators with renderSeparatorCell ItemSeparatorComponent draws only inside React rows, so worklet rows had no item separator. renderSeparatorCell is a worklet that gets leadingItem and trailingItem and returns a cell tree, which the engine lays out under the row in the row's own cell (above it when inverted), except in the last grid row. The cell keeps the row root's press, label, testID and role, and a cell root's margins no longer shrink its layout, as they never moved its paint. --- android/src/main/cpp/FlumeJni.cpp | 5 + .../java/me/sectiontn/flume/FlumeAdapter.kt | 12 +- .../main/java/me/sectiontn/flume/FlumeJni.kt | 3 + .../main/java/me/sectiontn/flume/FlumeView.kt | 2 + cpp/bindings/Engine.cpp | 61 +++++++ cpp/bindings/Engine.h | 3 + cpp/bindings/FlumeHost.cpp | 16 +- cpp/bindings/Store.cpp | 11 ++ cpp/bindings/Store.h | 17 ++ cpp/core/ListStore.cpp | 1 + cpp/core/Mounted.h | 3 +- cpp/core/Node.h | 1 + cpp/core/Reconciler.cpp | 4 + cpp/core/SeparatorRule.cpp | 51 ++++++ cpp/core/SeparatorRule.h | 17 ++ cpp/core/Style.cpp | 15 ++ cpp/core/Style.h | 3 + cpp/tests/jsi/engine_separator_test.cpp | 130 +++++++++++++++ cpp/tests/list_store_test.cpp | 7 + cpp/tests/separator_rule_test.cpp | 155 ++++++++++++++++++ example/src/chat.ts | 12 +- example/src/screens/ChatScreen.tsx | 19 ++- ios/FLMView.mm | 12 ++ src/Flume.tsx | 18 ++ src/__tests__/Flume.test.tsx | 91 ++++++++++ src/foreign.ts | 1 + src/index.ts | 4 + src/props.ts | 1 + src/store.ts | 6 + src/types.ts | 8 + 30 files changed, 683 insertions(+), 6 deletions(-) create mode 100644 cpp/core/SeparatorRule.cpp create mode 100644 cpp/core/SeparatorRule.h create mode 100644 cpp/tests/jsi/engine_separator_test.cpp create mode 100644 cpp/tests/separator_rule_test.cpp diff --git a/android/src/main/cpp/FlumeJni.cpp b/android/src/main/cpp/FlumeJni.cpp index 4b66512..63ed947 100644 --- a/android/src/main/cpp/FlumeJni.cpp +++ b/android/src/main/cpp/FlumeJni.cpp @@ -99,6 +99,10 @@ struct JFlumeJni : jni::JavaClass { return flume::Engine::instance().applyNow(storeId) ? JNI_TRUE : JNI_FALSE; } + static void setRowShape(jni::alias_ref, jint storeId, jboolean horizontal, jboolean inverted, jint lanes) { + flume::Engine::instance().setRowShape(storeId, {horizontal == JNI_TRUE, inverted == JNI_TRUE, lanes}); + } + static void setStatsEnabled(jni::alias_ref, jboolean enabled) { flume::Engine::instance().setStatsEnabled(enabled); } @@ -123,6 +127,7 @@ struct JFlumeJni : jni::JavaClass { makeNativeMethod("invalidateMeasures", JFlumeJni::invalidateMeasures), makeNativeMethod("refresh", JFlumeJni::refresh), makeNativeMethod("applyNow", JFlumeJni::applyNow), + makeNativeMethod("setRowShape", JFlumeJni::setRowShape), makeNativeMethod("setStatsEnabled", JFlumeJni::setStatsEnabled), }); } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt b/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt index 1e21b75..aba6def 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt @@ -46,7 +46,16 @@ class FlumeAdapter( // Orientation, columns and padding come from the host; a change of the cell size rebinds every row. fun configure(horizontal: Boolean, numColumns: Int, inverted: Boolean, paddingPx: IntArray) { - if (geometry.configure(horizontal, numColumns, inverted, paddingPx)) rebindAll() + if (!geometry.configure(horizontal, numColumns, inverted, paddingPx)) return + sendRowShape() + rebindAll() + } + + // The engine composes worklet separators with the shape the rows are laid out with. + private fun sendRowShape() { + if (storeId == 0) return + val lanes = if (geometry.horizontal) 1 else geometry.numColumns + FlumeJni.setRowShape(storeId, geometry.horizontal, geometry.inverted, lanes) } private fun rebindAll() { @@ -69,6 +78,7 @@ class FlumeAdapter( if (this.storeId != 0 && this.storeId != storeId) detach() val reload = attached.onAttach(storeId) val attachedCount = FlumeJni.attach(storeId, this, measurer, density) + sendRowShape() val sticky = FlumeJni.stickyIndices(storeId) val stickyChanged = !sticky.contentEquals(stickyIndices) stickyIndices = sticky diff --git a/android/src/main/java/me/sectiontn/flume/FlumeJni.kt b/android/src/main/java/me/sectiontn/flume/FlumeJni.kt index 604d26d..df2d172 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeJni.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeJni.kt @@ -44,6 +44,9 @@ object FlumeJni { // UI thread: applies deferred data now, in the frame of the mount that brought its cells. False when none was pending. @JvmStatic external fun applyNow(storeId: Int): Boolean + // UI thread: the shape the rows are laid out with, before any bind that uses it. + @JvmStatic external fun setRowShape(storeId: Int, horizontal: Boolean, inverted: Boolean, lanes: Int) + // Binds read the clock and return stats only while this is on. @JvmStatic external fun setStatsEnabled(enabled: Boolean) } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 094df39..422b865 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -194,6 +194,8 @@ class FlumeView(context: Context) : FrameLayout(context) { recycler.adapter = adapter recycler.itemAnimator = animator recycler.clipToPadding = false + // A row composed with its separator draws its shadow from a child view, which a clipping cell would cut. + recycler.clipChildren = false adapter.onPress = { position, pressId, long -> val index = rows.dataIndex(position) if (index >= 0) emitPress(index, FlumeJni.keyAt(storeId, index), pressId, long) diff --git a/cpp/bindings/Engine.cpp b/cpp/bindings/Engine.cpp index 9a42543..386c39a 100644 --- a/cpp/bindings/Engine.cpp +++ b/cpp/bindings/Engine.cpp @@ -4,6 +4,7 @@ #include #include "bindings/JsiConverter.h" +#include "core/SeparatorRule.h" #include "core/TreeParser.h" #ifdef __ANDROID__ @@ -118,6 +119,13 @@ void Engine::setCell(int storeId, std::shared_ptr render scheduleRefresh(store, true); } +void Engine::setSeparatorCell(int storeId, std::shared_ptr separatorCell) { + auto store = find(storeId); + if (store == nullptr) return; + store->setSeparatorCell(std::move(separatorCell)); + scheduleRefresh(store, true); +} + void Engine::setCellKinds(int storeId, bool reactByDefault, std::vector reactTypes) { auto store = find(storeId); if (store == nullptr) return; @@ -211,6 +219,7 @@ void Engine::releaseOnRuntime(int storeId) { store = it->second; } store->slot.renderCellFn.reset(); + store->slot.separatorCellFn.reset(); store->slot.items.clear(); } @@ -236,6 +245,11 @@ void Engine::detach(int storeId) { store->list.setAttached(false); } +void Engine::setRowShape(int storeId, RowShape shape) { + auto store = find(storeId); + if (store != nullptr) store->shape = shape; +} + int Engine::count(int storeId) { auto store = find(storeId); return store == nullptr ? 0 : store->list.count(); @@ -350,6 +364,53 @@ void Engine::bindOnRuntime(jsi::Runtime& rt, int index) { } catch (const std::exception& e) { current_.error = std::string("renderCell failed: ") + e.what(); } + if (current_.fresh != nullptr) composeOnRuntime(rt, *store, index); +} + +// With a separator worklet every row binds composed, and rows before the last grid row get its tree. +void Engine::composeOnRuntime(jsi::Runtime& rt, Store& store, int index) { + Store::RuntimeSlot& slot = store.slot; + auto [separatorCell, version] = store.separatorCell(); + if (separatorCell == nullptr) { + slot.separatorCellFn.reset(); + return; + } + const RowShape& shape = store.shape; + std::unique_ptr separator; + try { + if (!slot.separatorCellFn || slot.separatorCellVersion != version) { + slot.separatorCellFn = separatorCell->toJSValue(rt).asObject(rt).asFunction(rt); + slot.separatorCellVersion = version; + } + int count = store.list.count(); + if (index < lastRowStart(count, shape.horizontal ? 1 : shape.lanes, store.list.sticky())) { + const ListStore& list = store.list; + jsi::Object info(rt); + info.setProperty(rt, "leadingItem", + jsi::Value(rt, slot.items.materialize(rt, list.keyAt(index), list.itemVersion(index), + list.itemAt(index)))); + int next = index + 1; + // A React row's item lives in JS only, so its separator gets no trailing item. + if (next < count && !list.isReactAt(next)) { + info.setProperty(rt, "trailingItem", + jsi::Value(rt, slot.items.materialize(rt, list.keyAt(next), list.itemVersion(next), + list.itemAt(next)))); + } + jsi::Value result = slot.separatorCellFn->call(rt, {jsi::Value(rt, info)}); + if (!result.isNull() && !result.isUndefined()) { + std::vector unknownKeys; + ParseResult parsed = parseTree(toValue(rt, result), &unknownKeys); + for (const std::string& key : unknownKeys) report(1, "unknown style key: " + key); + if (parsed.root == nullptr) report(2, "renderSeparatorCell returned an invalid tree: " + parsed.error); + separator = std::move(parsed.root); + } + } + } catch (const jsi::JSError& e) { + report(2, "renderSeparatorCell threw: " + e.getMessage()); + } catch (const std::exception& e) { + report(2, std::string("renderSeparatorCell failed: ") + e.what()); + } + current_.fresh = composeRow(std::move(current_.fresh), std::move(separator), shape.horizontal, shape.inverted); } int Engine::viewType(int storeId, int position) { diff --git a/cpp/bindings/Engine.h b/cpp/bindings/Engine.h index 4ef7931..0d60600 100644 --- a/cpp/bindings/Engine.h +++ b/cpp/bindings/Engine.h @@ -41,6 +41,7 @@ class Engine { // A sticky-only change: it joins pending data, or applies alone. void setStickyHeaderIndices(int storeId, std::vector sticky); void setCell(int storeId, std::shared_ptr renderCell); + void setSeparatorCell(int storeId, std::shared_ptr separatorCell); // null clears it void setCellKinds(int storeId, bool reactByDefault, std::vector reactTypes); void setReporter(int session, facebook::jsi::Function reporter); // a function on the React runtime, development only void report(int level, const std::string& message); // once per message: the reporter when set, else logcat @@ -52,6 +53,7 @@ class Engine { // UI thread (platform bridge) int attach(int storeId, StoreListener* listener, std::unique_ptr measurer, float pointScale); void detach(int storeId); + void setRowShape(int storeId, RowShape shape); // before any bind laid out with the new shape int count(int storeId); int viewType(int storeId, int position); // type id * 2, plus 1 for React; 0 for an unknown position bool hasReactKinds(int storeId); // some item type renders as a React row @@ -89,6 +91,7 @@ class Engine { void scheduleRefresh(const std::shared_ptr& store, bool always); static bool applyPending(Store& store, bool always); void bindOnRuntime(facebook::jsi::Runtime& rt, int index); + void composeOnRuntime(facebook::jsi::Runtime& rt, Store& store, int index); void releaseOnRuntime(int storeId); void logLine(const std::string& message); diff --git a/cpp/bindings/FlumeHost.cpp b/cpp/bindings/FlumeHost.cpp index d6f7f30..8365635 100644 --- a/cpp/bindings/FlumeHost.cpp +++ b/cpp/bindings/FlumeHost.cpp @@ -15,7 +15,8 @@ namespace jsi = facebook::jsi; namespace { const char* const kNames[] = {"install", "setScheduler", "createStore", "releaseStore", "setData", - "setCell", "setCellKinds", "setStickyHeaderIndices", "setReporter"}; + "setCell", "setSeparatorCell", "setCellKinds", "setStickyHeaderIndices", + "setReporter"}; std::vector stringsOf(jsi::Runtime& rt, const jsi::Value& value) { std::vector out; @@ -157,6 +158,19 @@ jsi::Value FlumeHost::get(jsi::Runtime& rt, const jsi::PropNameID& nameId) { return jsi::Value::undefined(); }); } + if (name == "setSeparatorCell") { + return hostFunction(rt, "setSeparatorCell", 2, + [&engine](jsi::Runtime& rt, const jsi::Value&, const jsi::Value* args, size_t count) { + if (count < 1) throw jsi::JSError(rt, "setSeparatorCell needs a store id"); + std::shared_ptr worklet; + if (count > 1 && !args[1].isNull() && !args[1].isUndefined()) { + worklet = worklets::extractSerializable( + rt, args[1], "react-native-flume: renderSeparatorCell must be a worklet"); + } + engine.setSeparatorCell(static_cast(args[0].asNumber()), std::move(worklet)); + return jsi::Value::undefined(); + }); + } if (name == "setCellKinds") { return hostFunction(rt, "setCellKinds", 3, [&engine](jsi::Runtime& rt, const jsi::Value&, const jsi::Value* args, size_t count) { diff --git a/cpp/bindings/Store.cpp b/cpp/bindings/Store.cpp index 4f0e361..7c0c061 100644 --- a/cpp/bindings/Store.cpp +++ b/cpp/bindings/Store.cpp @@ -28,4 +28,15 @@ uint64_t Store::renderCellVersion() const { return renderCellVersion_; } +void Store::setSeparatorCell(std::shared_ptr separatorCell) { + std::lock_guard lock(mutex_); + separatorCell_ = std::move(separatorCell); + separatorCellVersion_++; +} + +std::pair, uint64_t> Store::separatorCell() const { + std::lock_guard lock(mutex_); + return {separatorCell_, separatorCellVersion_}; +} + } // namespace flume diff --git a/cpp/bindings/Store.h b/cpp/bindings/Store.h index 464cc94..23f26d6 100644 --- a/cpp/bindings/Store.h +++ b/cpp/bindings/Store.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include "bindings/ItemCache.h" @@ -37,6 +38,14 @@ struct FlumeRuntime { const facebook::jsi::Function release; }; +// How the platform lays rows out, which decides where a separator goes and which rows draw one. +struct RowShape { + bool horizontal = false; + bool inverted = false; + int lanes = 1; + bool operator==(const RowShape&) const = default; +}; + // One list: its order and items, the cell worklet, its holders and its runtime handles. class Store : public std::enable_shared_from_this { public: @@ -49,10 +58,14 @@ class Store : public std::enable_shared_from_this { // JS thread void setRenderCell(std::shared_ptr renderCell); + void setSeparatorCell(std::shared_ptr separatorCell); // null clears it // UI thread std::shared_ptr renderCell() const; uint64_t renderCellVersion() const; + // The separator worklet with its version, read together so a set between two reads cannot pair them wrong. + std::pair, uint64_t> separatorCell() const; + RowShape shape; // set by the platform view before it binds with a new shape std::unordered_map> holders; StoreListener* listener = nullptr; @@ -65,6 +78,8 @@ class Store : public std::enable_shared_from_this { std::shared_ptr flume; // the runtime of the values below, declared first so it dies last std::optional renderCellFn; uint64_t renderCellVersion = 0; + std::optional separatorCellFn; + uint64_t separatorCellVersion = 0; ItemCache items; uint64_t retainedGeneration = 0; } slot; @@ -73,6 +88,8 @@ class Store : public std::enable_shared_from_this { mutable std::mutex mutex_; std::shared_ptr renderCell_; uint64_t renderCellVersion_ = 0; + std::shared_ptr separatorCell_; + uint64_t separatorCellVersion_ = 0; }; } // namespace flume diff --git a/cpp/core/ListStore.cpp b/cpp/core/ListStore.cpp index 6864f6b..e5b320f 100644 --- a/cpp/core/ListStore.cpp +++ b/cpp/core/ListStore.cpp @@ -51,6 +51,7 @@ std::vector stickyWithin(const std::vector& sticky, size_t count) { for (int index : sticky) { if (index >= 0 && static_cast(index) < count) out.push_back(index); } + std::sort(out.begin(), out.end()); return out; } diff --git a/cpp/core/Mounted.h b/cpp/core/Mounted.h index db80f26..af9e02d 100644 --- a/cpp/core/Mounted.h +++ b/cpp/core/Mounted.h @@ -32,7 +32,8 @@ struct Mounted { std::string testID; std::string accessibilityLabel; std::optional accessible; - std::string derivedLabel; // the label last sent from the texts inside a pressable without its own + bool separator = false; // the separator half of a composed row, left out of the row's label + std::string derivedLabel; // the label last sent from the texts inside a pressable without its own int viewId = 0; // 0 is the holder's own view YGNodeRef yoga = nullptr; Layout* layout = nullptr; diff --git a/cpp/core/Node.h b/cpp/core/Node.h index 9900d2a..4a5220a 100644 --- a/cpp/core/Node.h +++ b/cpp/core/Node.h @@ -28,6 +28,7 @@ struct Node { std::string testID; std::string accessibilityLabel; std::optional accessible; + bool separator = false; // the separator half of a composed row, left out of the row's label std::vector> children; // view and pressable only }; diff --git a/cpp/core/Reconciler.cpp b/cpp/core/Reconciler.cpp index 1e59b83..7e63a55 100644 --- a/cpp/core/Reconciler.cpp +++ b/cpp/core/Reconciler.cpp @@ -81,9 +81,11 @@ void copyProps(Mounted& mounted, Node& fresh) { mounted.testID = std::move(fresh.testID); mounted.accessibilityLabel = std::move(fresh.accessibilityLabel); mounted.accessible = fresh.accessible; + mounted.separator = fresh.separator; } void appendTexts(const Mounted& node, std::string& out) { + if (node.separator) return; if (node.type == NodeType::Text && !node.text.empty()) { if (!out.empty()) out += ' '; out += node.text; @@ -101,6 +103,8 @@ void Reconciler::reconcile(Holder& holder, std::unique_ptr fresh, OpBatch& } return; } + // The cell view is the root's box, so a root margin would only shrink the layout under an unchanged paint. + clearParentLayout(fresh->style); if (holder.root != nullptr && holder.root->type != fresh->type) { unmount(*holder.root, out); holder.root.reset(); diff --git a/cpp/core/SeparatorRule.cpp b/cpp/core/SeparatorRule.cpp new file mode 100644 index 0000000..de813ec --- /dev/null +++ b/cpp/core/SeparatorRule.cpp @@ -0,0 +1,51 @@ +#include "core/SeparatorRule.h" + +#include +#include + +namespace flume { + +int lastRowStart(int count, int lanes, const std::vector& sortedFullSpans) { + if (count <= 0) return 0; + int last = count - 1; + lanes = std::max(lanes, 1); + // Only the last full span at or before the last index decides where the last run of lanes starts. + auto after = std::upper_bound(sortedFullSpans.begin(), sortedFullSpans.end(), last); + int runStart = 0; + if (after != sortedFullSpans.begin()) { + int span = *(after - 1); + if (span == last) return last; + runStart = span + 1; + } + return runStart + (last - runStart) / lanes * lanes; +} + +std::unique_ptr composeRow(std::unique_ptr row, std::unique_ptr separator, bool horizontal, + bool inverted) { + auto root = std::make_unique(); + root->style.flexDirection = horizontal ? YGFlexDirectionRow : YGFlexDirectionColumn; + if (row->type == NodeType::Pressable) { + root->type = NodeType::Pressable; + row->type = NodeType::View; + } + root->pressId = std::move(row->pressId); + root->pressedOpacity = row->pressedOpacity; + root->testID = std::move(row->testID); + root->accessibilityLabel = std::move(row->accessibilityLabel); + root->accessible = row->accessible; + row->pressId.clear(); + row->testID.clear(); + row->accessibilityLabel.clear(); + row->accessible.reset(); + clearParentLayout(row->style); + row->key = "r"; + root->children.push_back(std::move(row)); + if (separator != nullptr) { + separator->key = "s"; + separator->separator = true; + root->children.insert(inverted ? root->children.begin() : root->children.end(), std::move(separator)); + } + return root; +} + +} // namespace flume diff --git a/cpp/core/SeparatorRule.h b/cpp/core/SeparatorRule.h new file mode 100644 index 0000000..2cb5901 --- /dev/null +++ b/cpp/core/SeparatorRule.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +#include "core/Node.h" + +namespace flume { + +// The first index of the last grid row, whose rows draw no separator. A full-span index ends a run of lanes. +int lastRowStart(int count, int lanes, const std::vector& sortedFullSpans); + +// The row and its separator (first when inverted) under a root that takes the row root's press, label, id and role. +std::unique_ptr composeRow(std::unique_ptr row, std::unique_ptr separator, bool horizontal, + bool inverted); + +} // namespace flume diff --git a/cpp/core/Style.cpp b/cpp/core/Style.cpp index 880b701..aafd611 100644 --- a/cpp/core/Style.cpp +++ b/cpp/core/Style.cpp @@ -290,3 +290,18 @@ Style Style::fromValue(const Value& object, std::vector* unknownKey } } // namespace flume + +namespace flume { + +void clearParentLayout(Style& style) { + style.margin.fill(Dimension{}); + style.position.fill(Dimension{}); + style.positionType.reset(); + style.alignSelf.reset(); + style.flex.reset(); + style.flexGrow.reset(); + style.flexShrink.reset(); + style.flexBasis = Dimension{}; +} + +} // namespace flume diff --git a/cpp/core/Style.h b/cpp/core/Style.h index 3004928..dcac85f 100644 --- a/cpp/core/Style.h +++ b/cpp/core/Style.h @@ -60,4 +60,7 @@ struct Style { bool operator==(const Style&) const = default; }; +// Drops what only a parent reads (margins, insets, position type, alignSelf and flex), as a cell root never has one. +void clearParentLayout(Style& style); + } // namespace flume diff --git a/cpp/tests/jsi/engine_separator_test.cpp b/cpp/tests/jsi/engine_separator_test.cpp new file mode 100644 index 0000000..2c12f5c --- /dev/null +++ b/cpp/tests/jsi/engine_separator_test.cpp @@ -0,0 +1,130 @@ +#include +#include +#include +#include + +#include "batch.h" +#include "bindings/Engine.h" +#include "bindings/FlumeHost.h" +#include "doctest.h" +#include "fake_measurer.h" +#include "fake_worklets.h" +#include "hermes_rig.h" + +namespace { + +// A React runtime with __flume and a flume runtime installed, so rows bind. +struct ReactSide { + HermesRig rig; + std::shared_ptr invoker = std::make_shared(); + ReactSide() { + flume::FlumeHost::install(rig.rt(), invoker); + installFlumeRuntime(rig.rt()); + } +}; + +struct NullListener : flume::StoreListener { + void onListChanged(const flume::ListOps&, int) override {} +}; + +// Rows 10 pt tall, typed by typeIds, and a separator 1 pt tall whose text names its leading and trailing items. +int separatedStore(ReactSide& side, flume::StoreListener& listener, int count, const std::string& typeIds, + const std::string& reactTypes = "[]") { + std::string keys, items; + for (int i = 0; i < count; i++) { + keys += (i ? ", '" : "'") + std::to_string(i) + "'"; + items += (i ? ", {n: " : "{n: ") + std::to_string(i) + "}"; + } + std::string indices; + for (int i = 0; i < count; i++) indices += (i ? ", " : "") + std::to_string(i); + int id = static_cast( + side.rig + .eval("__flume.setScheduler({});" + "var id = __flume.createStore();" + "__flume.setCellKinds(id, false, " + + reactTypes + + ");" + "__flume.setData(id, [" + + keys + "], ['row', 'react'], new Int32Array([" + typeIds + "]), [" + indices + "], [" + items + + "], true, false);" + "__flume.setCell(id, function (item, index) {" + " 'show source';" + " return {type: 'view', style: {height: 10}};" + "});" + "__flume.setSeparatorCell(id, function (info) {" + " 'show source';" + " var trailing = info.trailingItem === undefined ? 'none' : String(info.trailingItem.n);" + " return {type: 'text', text: info.leadingItem.n + '-' + trailing, style: {height: 1}};" + "});" + "id") + .asNumber()); + REQUIRE(flume::Engine::instance().attach(id, &listener, std::make_unique(), 1) == count); + return id; +} + +flume::OpBatch bound(int id, int index) { + flume::OpBatch out; + REQUIRE(flume::Engine::instance().bind(id, index, index, 300, NAN, out)); + return out; +} + +bool says(const flume::OpBatch& batch, const std::string& text) { + return std::find(batch.strings.begin(), batch.strings.end(), text) != batch.strings.end(); +} + +} // namespace + +TEST_CASE("a separator worklet draws under every row but the last, with the next item") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + auto first = bound(id, 0); + CHECK(says(first, "0-1")); + CHECK(first.rootHeight == 11); + auto last = bound(id, 2); + CHECK_FALSE(says(last, "2-none")); + CHECK(last.rootHeight == 10); + // The last row keeps the composed root, so it never switches shape. + CHECK(frameOf(last, 1).has_value()); +} + +TEST_CASE("a separator before a React row has no trailing item") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 1", "['react']"); + CHECK(says(bound(id, 1), "1-none")); +} + +TEST_CASE("an inverted row shape puts the separator before the row") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + flume::Engine::instance().setRowShape(id, {false, true, 1}); + auto out = bound(id, 0); + // The separator is created first: view 1 at the top, the row view 2 under it. + auto divider = frameOf(out, 1); + auto row = frameOf(out, 2); + REQUIRE(divider); + REQUIRE(row); + CHECK((*divider)[1] == 0); + CHECK((*row)[1] == 1); +} + +TEST_CASE("three lanes leave the last grid row without a separator") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 10, "0, 0, 0, 0, 0, 0, 0, 0, 0, 0"); + flume::Engine::instance().setRowShape(id, {false, false, 3}); + CHECK(says(bound(id, 8), "8-9")); + CHECK(bound(id, 9).rootHeight == 10); +} + +TEST_CASE("clearing the separator worklet binds plain rows again") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + side.rig.eval("__flume.setSeparatorCell(id, null)"); + auto out = bound(id, 0); + CHECK(out.rootHeight == 10); + CHECK_FALSE(frameOf(out, 1).has_value()); +} diff --git a/cpp/tests/list_store_test.cpp b/cpp/tests/list_store_test.cpp index a23018a..65d1be3 100644 --- a/cpp/tests/list_store_test.cpp +++ b/cpp/tests/list_store_test.cpp @@ -18,6 +18,13 @@ TEST_CASE("a first snapshot inserts everything") { CHECK(store.keyAt(2) == "c"); } +TEST_CASE("sticky indices apply sorted, so the last full span is found by a search") { + flume::ListStore store; + store.setPending({"a", "b", "c", "d"}, {"t", "t", "t", "t"}, {0, 1, 2, 3}, {V(1), V(2), V(3), V(4)}, true, {3, 0, 2}); + store.applyPending(); + CHECK(store.sticky() == std::vector{0, 2, 3}); +} + TEST_CASE("a reset carries the sticky indices of its own data") { flume::ListStore store; store.setPending({"a", "b", "c"}, {"t", "t", "t"}, {0, 1, 2}, {V(1), V(2), V(3)}, true, {0}); diff --git a/cpp/tests/separator_rule_test.cpp b/cpp/tests/separator_rule_test.cpp new file mode 100644 index 0000000..038e890 --- /dev/null +++ b/cpp/tests/separator_rule_test.cpp @@ -0,0 +1,155 @@ +#include "doctest.h" + +#include +#include +#include +#include + +#include "batch.h" +#include "core/Layout.h" +#include "core/Reconciler.h" +#include "core/SeparatorRule.h" +#include "core/TreeParser.h" +#include "fake_measurer.h" +#include "values.h" + +namespace { + +// The same table as src/__tests__/separators.test.ts. +struct Case { + int count, columns; + std::vector spans; + int start; +}; + +struct Bound { + FakeMeasurer fake; + flume::Layout layout{fake, 1}; + flume::Reconciler rec{layout}; + flume::Holder holder; + flume::OpBatch batch; + + void bind(std::unique_ptr root, float width = 360) { + batch.clear(); + rec.reconcile(holder, std::move(root), batch); + layout.layout(*holder.root, width, NAN); + layout.readFrames(*holder.root, batch); + rec.emitAfterLayout(holder, batch); + } +}; + +std::unique_ptr parsed(const flume::Value& tree) { + auto result = flume::parseTree(tree); + REQUIRE(result.root); + return std::move(result.root); +} + +flume::Value row(const char* label = nullptr) { + flume::Value::Object row{ + {"type", V("pressable")}, + {"id", V("open")}, + {"testID", V("row-a")}, + {"style", obj({{"margin", V(10)}, {"padding", V(12)}, {"backgroundColor", V("#ffffff")}, + {"shadowOpacity", V(0.3)}, {"shadowRadius", V(4)}})}, + {"children", arr({obj({{"type", V("text")}, {"text", V("hello")}}), + obj({{"type", V("text")}, {"text", V("9:41")}})})}}; + if (label != nullptr) row.emplace_back("accessibilityLabel", V(label)); + return flume::Value(std::move(row)); +} + +flume::Value separator() { + return obj({{"type", V("view")}, + {"style", obj({{"height", V(1)}, {"backgroundColor", V("#cccccc")}})}, + {"children", arr({obj({{"type", V("text")}, {"text", V("divider")}})})}}); +} + +// The last accessibility op of a view: label, testID, role. +struct Access { + std::string label, testID; + int role; +}; +std::optional accessOf(const flume::OpBatch& batch, int id) { + std::optional found; + for (const auto& op : decode(batch)) { + if (op.op != 8 || op.id != id) continue; + auto text = [&](int index) { return index < 0 ? std::string() : batch.strings[index]; }; + found = Access{text(op.ints[0]), text(op.ints[1]), op.ints[2]}; + } + return found; +} + +} // namespace + +TEST_CASE("the last grid row starts where the table says") { + const std::vector cases{{0, 1, {}, 0}, {5, 1, {}, 4}, {9, 3, {}, 6}, {10, 3, {}, 9}, + {10, 3, {4}, 8}, {10, 3, {9}, 9}, {6, 2, {0, 3}, 4}}; + for (const Case& c : cases) { + CAPTURE(c.count); + CAPTURE(c.columns); + CHECK(flume::lastRowStart(c.count, c.columns, c.spans) == c.start); + } +} + +TEST_CASE("a composed row draws like the plain row") { + Bound plain; + plain.bind(parsed(row())); + Bound composed; + composed.bind(flume::composeRow(parsed(row()), parsed(separator()), false, false)); + // Plain: the root is view 0 and its texts views 1 and 2. Composed: the row is view 1, its texts 2 and 3. + auto plainRoot = frameOf(plain.batch, 0); + auto composedRow = frameOf(composed.batch, 1); + REQUIRE(plainRoot); + REQUIRE(composedRow); + // A root margin is ignored, so the row spans the bind width in both. + CHECK((*plainRoot)[2] == 360); + CHECK((*composedRow)[0] == 0); + CHECK((*composedRow)[1] == 0); + CHECK((*composedRow)[2] == (*plainRoot)[2]); + CHECK((*composedRow)[3] == (*plainRoot)[3]); + CHECK(frameOf(composed.batch, 2) == frameOf(plain.batch, 1)); + CHECK(frameOf(composed.batch, 3) == frameOf(plain.batch, 2)); + // The separator is view 4, under the row and as wide as the bind width. + auto divider = frameOf(composed.batch, 4); + REQUIRE(divider); + CHECK((*divider)[0] == 0); + CHECK((*divider)[1] == (*plainRoot)[3]); + CHECK((*divider)[2] == 360); + CHECK((*divider)[3] == 1); + auto plainAccess = accessOf(plain.batch, 0); + auto composedAccess = accessOf(composed.batch, 0); + REQUIRE(plainAccess); + REQUIRE(composedAccess); + CHECK(composedAccess->label == plainAccess->label); + CHECK(composedAccess->label.find("divider") == std::string::npos); + CHECK(composedAccess->testID == "row-a"); + CHECK(composedAccess->role == 1); + CHECK_FALSE(accessOf(composed.batch, 1).has_value()); + CHECK(firstOp(composed.batch, 7, 0).id == 0); +} + +TEST_CASE("a composed row keeps the row's own label on the cell") { + Bound composed; + composed.bind(flume::composeRow(parsed(row("Open chat")), parsed(separator()), false, false)); + auto access = accessOf(composed.batch, 0); + REQUIRE(access); + CHECK(access->label == "Open chat"); + CHECK(access->testID == "row-a"); + CHECK_FALSE(accessOf(composed.batch, 1).has_value()); +} + +TEST_CASE("an inverted composed row puts the separator first") { + Bound composed; + composed.bind(flume::composeRow(parsed(row()), parsed(separator()), false, true)); + // The separator is created first, so it is view 1 and the row view 3. + auto divider = frameOf(composed.batch, 1); + REQUIRE(divider); + CHECK((*divider)[1] == 0); + CHECK((*divider)[3] == 1); +} + +TEST_CASE("a composed row without a separator keeps the row alone") { + Bound composed; + composed.bind(flume::composeRow(parsed(row()), nullptr, false, false)); + CHECK(frameOf(composed.batch, 1).has_value()); + CHECK_FALSE(frameOf(composed.batch, 4).has_value()); +} diff --git a/example/src/chat.ts b/example/src/chat.ts index 61354a2..36b29b0 100644 --- a/example/src/chat.ts +++ b/example/src/chat.ts @@ -1,4 +1,4 @@ -import { type CellNode, cell } from 'react-native-flume'; +import { type CellNode, cell, type SeparatorCellInfo } from 'react-native-flume'; export type Chat = { id: string; @@ -68,6 +68,16 @@ export function dayIndices(chats: readonly Chat[]): number[] { export const accentColor = (dark: boolean) => (dark ? '#6ea8ff' : '#0066ff'); +// A hairline under each message, inset past the avatar, and full width next to a day chip. +export function makeRenderSeparatorCell(dark: boolean) { + const line = dark ? '#3a3a3a' : '#dddddd'; + return ({ leadingItem, trailingItem }: SeparatorCellInfo): CellNode => { + 'worklet'; + const nextToDay = leadingItem.kind === 'day' || trailingItem?.kind === 'day'; + return cell.view({ height: 1, marginLeft: nextToDay ? 0 : 64, backgroundColor: line }); + }; +} + export function makeRenderCell(dark: boolean) { const textColor = dark ? '#eeeeee' : '#111111'; const timeColor = dark ? '#aaaaaa' : '#666666'; diff --git a/example/src/screens/ChatScreen.tsx b/example/src/screens/ChatScreen.tsx index 9519aeb..c9a8c9c 100644 --- a/example/src/screens/ChatScreen.tsx +++ b/example/src/screens/ChatScreen.tsx @@ -1,7 +1,14 @@ import { useMemo, useRef, useState } from 'react'; import { Button, Platform, ToastAndroid, View } from 'react-native'; import { Flume, type FlumeRef, type PressInfo } from 'react-native-flume'; -import { accentColor, type Chat, dayIndices, makeChats, makeRenderCell } from '../chat'; +import { + accentColor, + type Chat, + dayIndices, + makeChats, + makeRenderCell, + makeRenderSeparatorCell, +} from '../chat'; function blockJs(ms: number) { const end = Date.now() + ms; @@ -53,6 +60,9 @@ export default function ChatScreen() { older: 0, })); const renderCell = useMemo(() => makeRenderCell(dark), [dark]); + // Native hairlines from the separator prop, or a worklet that draws each one next to its rows. + const [workletSeparators, setWorkletSeparators] = useState(false); + const renderSeparatorCell = useMemo(() => makeRenderSeparatorCell(dark), [dark]); const sticky = useMemo(() => dayIndices(list.chats), [list.chats]); const onPress = ({ item, id }: PressInfo) => toast(id === 'like' ? `like ${item.id}` : `open ${item.id}`); @@ -107,6 +117,10 @@ export default function ChatScreen() {