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