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..0b5a40b 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) + fun dropMountListener() { + val listener = mountListener ?: return + mountListener = null + UIManagerHelper.getUIManager(context as ReactContext, UIManagerType.FABRIC)?.removeUIManagerEventListener(listener) } fun setEstimatedItemSize(dp: Double) { diff --git a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt index ddaf121..ab77507 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt @@ -33,6 +33,8 @@ class FlumeViewManager : ViewGroupManager(), FlumeViewManagerInterfac } override fun onDropViewInstance(view: FlumeView) { + // A view dropped while detached registered its mount listener after its own detach cleanup. + view.dropMountListener() view.setStateWrapper(null) super.onDropViewInstance(view) } 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); +} 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() { | 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 +78,11 @@ function FlumeInner(given: FlumeProps, ref: Ref): ReactElement { ListHeaderComponent, ListFooterComponent, ListEmptyComponent, + ListHeaderComponentStyle, + ListFooterComponentStyle, + ListEmptyComponentStyle, + ItemSeparatorComponent, + inverted, itemAnimations = true, onPress, onLongPress, @@ -263,9 +280,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 @@ -316,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..1e1633a 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,31 @@ 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; + index?: number; + fullSpan?: boolean; }; // 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 +73,69 @@ 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, index, fullSpan } + : snapshot.current; + // Native's index for a row that left can differ from the one it rendered with. + const rowIndex = shown.index ?? index; + const span = shown.fullSpan ?? fullSpan; // 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 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 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: rowIndex, + target, + extraData, + data: shown.data ?? dataRef.current, + type: shown.type ?? type, + }) ?? null) + : null, + [cell, shown.render, shown.item, rowIndex, target, extraData, shown.type, type], + ); + const entry = { slot, kind, key: itemKey, index: rowIndex, bound: true, minMain }; + const style = slotStyle(entry, span, layout); + if (style === null) return null; 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 = element; + if (cell) { + const drawn = + separator !== null && 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 or the separator prop 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 && separator !== null + ? createElement(View, { style: SIDE_BY_SIDE }, parts) + : parts; + } return ( ({ }, })); 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,365 @@ 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); + } + } + }); +}); + +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('keeps a row mounted when ItemSeparatorComponent comes and goes', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const { Sep } = separatorSpy(); + const mounts = new Map(); + const Row = ({ id }: { id: string }) => { + useEffect(() => { + mounts.set(id, (mounts.get(id) ?? 0) + 1); + }, [id]); + return createElement('Row', { id }); + }; + const renderItem = (info: CellInfo) => + createElement(Row, { id: (info.item as { id: string }).id }); + const tree = await mount(createElement(Flume, { data: [a, b], renderItem })); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1)]); + const mounted = mounts.get('a'); + await act(async () => { + tree.update(createElement(Flume, { data: [a, b], renderItem, ItemSeparatorComponent: Sep })); + }); + await act(async () => { + tree.update(createElement(Flume, { data: [a, b], renderItem })); + }); + expect(mounts.get('a')).toBe(mounted); + }); + + it('renders a leaving row with the index it last committed', async () => { + installHost(); + const { Flume } = await import('../Flume'); + const x = { id: 'x' }; + const seen: { id: string; index: number }[] = []; + const renderItem = (info: CellInfo) => { + const id = (info.item as { id: string }).id; + seen.push({ id, index: info.index }); + return createElement('Row', { id }); + }; + const tree = await mount(createElement(Flume, { data: [a, b, c], renderItem })); + await sendSlots(tree, [rowEntry(1, 'a', 0), rowEntry(2, 'b', 1), rowEntry(3, 'c', 2)]); + // Native still lists b at 1 while the data has moved it to 2. + await act(async () => { + tree.update(createElement(Flume, { data: [x, a, b, c], renderItem })); + }); + seen.length = 0; + await act(async () => { + tree.update(createElement(Flume, { data: [x, a, c], renderItem })); + }); + expect(seen.filter((call) => call.id === 'b').map((call) => call.index)).toEqual([]); + }); + + 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 d942bbc..dbaa347 100644 --- a/src/foreign.ts +++ b/src/foreign.ts @@ -139,10 +139,14 @@ export const OWN_KEYS = [ 'drawDistance', 'initialScrollIndex', 'separator', + 'ItemSeparatorComponent', 'stickyHeaderIndices', 'ListHeaderComponent', 'ListFooterComponent', 'ListEmptyComponent', + 'ListHeaderComponentStyle', + 'ListFooterComponentStyle', + 'ListEmptyComponentStyle', 'onScroll', 'onScrollBeginDrag', 'onScrollEndDrag', 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 02cd118..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,12 +256,18 @@ 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. 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;