Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, ReactCell<T>>` | | 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. |
Expand All @@ -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<ViewStyle>` | | 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. |
Expand Down Expand Up @@ -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:

Expand Down Expand Up @@ -210,7 +210,7 @@ Then rename `<FlatList>` to `<Flume>`. `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
Expand Down
8 changes: 4 additions & 4 deletions android/src/main/java/me/sectiontn/flume/ContentAnchor.kt
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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()
Expand Down
3 changes: 2 additions & 1 deletion android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -173,7 +174,7 @@ class FlumeViewManager : ViewGroupManager<FlumeView>(), 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),
Expand Down
17 changes: 15 additions & 2 deletions android/src/test/java/me/sectiontn/flume/AnchorPolicyTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand All @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion cpp/adapter/ContentAnchor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
4 changes: 2 additions & 2 deletions cpp/adapter/ContentAnchor.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};

Expand Down
12 changes: 10 additions & 2 deletions cpp/tests/content_anchor_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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);
}
16 changes: 12 additions & 4 deletions src/Flume.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -48,7 +49,8 @@ function componentElement(
return isValidElement(component) ? component : createElement(component);
}

function FlumeInner<T>(props: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
const props = settleProps(given);
const {
data,
renderCell,
Expand Down Expand Up @@ -79,9 +81,10 @@ function FlumeInner<T>(props: FlumeProps<T>, ref: Ref<FlumeRef>): 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<number | null>(null);
Expand All @@ -94,7 +97,7 @@ function FlumeInner<T>(props: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
const warned = useRef({ duplicates: false, messages: new Set<string>() });
const nativeRef = useRef<ComponentRef<typeof FlumeViewNativeComponent>>(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);
Expand All @@ -110,6 +113,8 @@ function FlumeInner<T>(props: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
const lastViewable = useRef(new Map<string, T>());
const count = useRef(data.length);
count.current = data.length;
const dataRef = useRef<readonly unknown[]>(data);
dataRef.current = data;

// Each distinct message reports once per mount, in development only.
const report = useCallback((level: 'warn' | 'error', message: string) => {
Expand Down Expand Up @@ -326,6 +331,8 @@ function FlumeInner<T>(props: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
layout={layout}
item={itemOf(next, entry.key)}
render={resolved?.kind === 'react' ? (resolved.render as ReactCell<unknown>) : undefined}
type={type ?? 'default'}
dataRef={dataRef}
element={elementFor(entry.kind)}
extraData={extraData}
keyboardTaps={keyboardShouldPersistTaps ?? 'never'}
Expand Down Expand Up @@ -386,6 +393,7 @@ function FlumeInner<T>(props: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {

return (
<FlumeViewNativeComponent
{...hostProps(given)}
{...nativeProps(props, warn)}
ref={nativeRef}
storeId={storeId}
Expand Down
28 changes: 23 additions & 5 deletions src/FlumeSlot.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { memo, type ReactElement, useRef } from 'react';
import { memo, type ReactElement, useLayoutEffect, useRef } from 'react';
import { Keyboard } from 'react-native';
import { SlotKind, type SlotLayout, slotStyle } from './slots';
import FlumeSlotViewNativeComponent from './specs/FlumeSlotViewNativeComponent';
Expand All @@ -14,6 +14,9 @@ type FlumeSlotProps = {
layout: SlotLayout;
item: unknown;
render: ReactCell<unknown> | 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';
Expand All @@ -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<unknown> }>({});
if (item !== undefined && render !== undefined) last.current = { item, render };
const last = useRef<{
item?: unknown;
render?: ReactCell<unknown>;
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 (
Expand Down
Loading
Loading