Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ const Item = ({item, separators}: ListRenderItemInfo<string>) => {
};

type Props = Readonly<{
data?: ReadonlyArray<string>,
exampleProps: Partial<React.ElementConfig<typeof FlatList>>,
exampleTestID?: ?string,
onTest?: ?() => void,
Expand Down Expand Up @@ -95,7 +96,7 @@ const BaseFlatListExample: component(
ref={ref}
testID="flat_list"
// $FlowFixMe[incompatible-type]
data={DATA}
data={props.data ?? DATA}
keyExtractor={(item, index) => item + index}
style={styles.list}
// $FlowFixMe[incompatible-type]
Expand Down
126 changes: 111 additions & 15 deletions packages/rn-tester/js/examples/FlatList/FlatList-onEndReached.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,41 +12,137 @@

import type {RNTesterModuleExample} from '../../types/RNTesterTypes';

import BaseFlatListExample from './BaseFlatListExample';
import BaseFlatListExample, {ITEM_HEIGHT} from './BaseFlatListExample';
import * as React from 'react';
import {useRef, useState} from 'react';
import {Button, FlatList} from 'react-native';

const DATA = Array.from({length: 20}, (_, index) => `Item ${index}`);
const SCROLL_TO_ITEM = DATA[18];

type EventCounts = {
dragEvents: number,
onEndReached: number,
onMomentumScrollEnd: number,
onStartReached: number,
};

export component FlatList_onEndReached() {
const [output, setOutput] = useState('');
const exampleProps = {
onEndReached: (info: {distanceFromEnd: number, ...}) =>
setOutput('onEndReached'),
onEndReachedThreshold: 0,
const [output, setOutput] = useState('ready');
const listRef = useRef<?FlatList<string>>(null);
const actionRef = useRef<'end' | 'start'>('end');
const attemptsRef = useRef(0);
const eventCountsRef = useRef<EventCounts>({
dragEvents: 0,
onEndReached: 0,
onMomentumScrollEnd: 0,
onStartReached: 0,
});
const recordEventsRef = useRef(false);
const momentumEndedRef = useRef(false);

const report = () => {
const {dragEvents, onEndReached, onMomentumScrollEnd, onStartReached} =
eventCountsRef.current;
setOutput(
`${actionRef.current}: attempts=${attemptsRef.current}, ` +
`onEndReached=${onEndReached}, onStartReached=${onStartReached}, ` +
`onMomentumScrollEnd=${onMomentumScrollEnd}, dragEvents=${dragEvents}`,
);
};

const onEndReached = () => {
if (recordEventsRef.current) {
eventCountsRef.current.onEndReached++;
if (momentumEndedRef.current) {
report();
}
}
};

const onStartReached = () => {
if (recordEventsRef.current) {
eventCountsRef.current.onStartReached++;
if (momentumEndedRef.current) {
report();
}
}
};
const ref = useRef<any>(null);

const onTest = () => {
const scrollResponder = ref?.current?.getScrollResponder();
if (scrollResponder != null) {
scrollResponder.scrollToEnd();
const onMomentumScrollEnd = () => {
if (recordEventsRef.current) {
eventCountsRef.current.onMomentumScrollEnd++;
momentumEndedRef.current = true;
report();
}
};

const onDragEvent = () => {
if (recordEventsRef.current) {
eventCountsRef.current.dragEvents++;
}
};

const scrollToEnd = () => {
recordEventsRef.current = true;
momentumEndedRef.current = false;
actionRef.current = 'end';
attemptsRef.current++;
setOutput('running');
listRef.current?.scrollToItem({
animated: true,
item: SCROLL_TO_ITEM,
viewOffset: -ITEM_HEIGHT,
});
};

const scrollToStart = () => {
momentumEndedRef.current = false;
actionRef.current = 'start';
attemptsRef.current++;
setOutput('running');
listRef.current?.scrollToOffset({animated: true, offset: 0});
};

const exampleProps = {
initialNumToRender: 19,
onEndReached,
onEndReachedThreshold: 0.2,
onMomentumScrollEnd,
onScrollBeginDrag: onDragEvent,
onScrollEndDrag: onDragEvent,
onStartReached,
onStartReachedThreshold: 0.1,
windowSize: 2,
};

return (
<BaseFlatListExample
ref={ref}
ref={listRef}
data={DATA}
exampleProps={exampleProps}
testOutput={output}
onTest={onTest}
/>
onTest={scrollToEnd}
testLabel="Scroll to item">
<Button
testID="scroll_to_start"
onPress={scrollToStart}
title="Scroll to start"
/>
<Button
testID="scroll_to_end"
onPress={scrollToEnd}
title="Scroll to item"
/>
</BaseFlatListExample>
);
}

export default {
title: 'onEndReached',
name: 'onEndReached',
description:
'Scroll to end of list or tap Test button to see `onEndReached` triggered.',
'Programmatic scrolling calls edge callbacks once and does not emit drag callbacks.',
render: function () {
return <FlatList_onEndReached />;
},
Expand Down
68 changes: 46 additions & 22 deletions packages/virtualized-lists/Lists/VirtualizedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -1195,7 +1195,7 @@ class VirtualizedList extends StateSafePureComponent<
}

componentDidUpdate(prevProps: VirtualizedListProps) {
const {data, extraData, getItemLayout} = this.props;
const {data, extraData} = this.props;
if (data !== prevProps.data || extraData !== prevProps.extraData) {
// clear the viewableIndices cache to also trigger
// the onViewableItemsChanged callback with the new data
Expand All @@ -1217,11 +1217,14 @@ class VirtualizedList extends StateSafePureComponent<
this._hiPriInProgress = false;
}

// We only call `onEndReached` after we render the last cell, but when
// getItemLayout is present, we can scroll past the last rendered cell, and
// never trigger a new layout or bounds change, so we need to check again
// after rendering more cells.
if (getItemLayout != null) {
// We only call `onEndReached` after we render the last cell, but
// programmatic scrolling (e.g. scrollToItem, scrollToIndex) or using
// getItemLayout can scroll past the last rendered cell, and never
// trigger a new layout or bounds change, so we need to check again
// after rendering more cells. We gate on having received at least one
// scroll event (timestamp > 0) to avoid false onEndReached calls
// during initial render.
if (this.props.getItemLayout != null || this._scrollMetrics.timestamp > 0) {
this._maybeCallOnEdgeReached();
}
}
Expand Down Expand Up @@ -1264,8 +1267,10 @@ class VirtualizedList extends StateSafePureComponent<
zoomScale: 1,
};
_scrollRef: ?React.ElementRef<typeof ScrollView> = null;
_sentStartForContentLength = 0;
_sentEndForContentLength = 0;
_sentStartForItemCount: ?number = null;
_sentStartForOffset: ?number = null;
_sentEndForItemCount: ?number = null;
_sentEndForOffset: ?number = null;
_updateCellsToRenderTimeoutID: ?ReturnType<typeof setTimeout> = null;
_viewabilityTuples: Array<ViewabilityHelperCallbackTuple> = [];

Expand Down Expand Up @@ -1557,7 +1562,7 @@ class VirtualizedList extends StateSafePureComponent<
};
}

_maybeCallOnEdgeReached() {
_maybeCallOnEdgeReached(isScrollEvent: boolean = false) {
const {
data,
getItemCount,
Expand Down Expand Up @@ -1610,39 +1615,53 @@ class VirtualizedList extends StateSafePureComponent<
const isWithinStartThreshold = distanceFromStart <= startThreshold;
const isWithinEndThreshold = distanceFromEnd <= endThreshold;

const itemCount = getItemCount(data);

// First check if the user just scrolled within the end threshold
// and call onEndReached only once for a given content length,
// and call onEndReached only once for a given item count,
// and only if onStartReached is not being executed
if (
onEndReached &&
this.state.cellsAroundViewport.last === getItemCount(data) - 1 &&
this.state.cellsAroundViewport.last === itemCount - 1 &&
isWithinEndThreshold &&
this._listMetrics.getContentLength() !== this._sentEndForContentLength
itemCount !== this._sentEndForItemCount
) {
this._sentEndForContentLength = this._listMetrics.getContentLength();
this._sentEndForItemCount = itemCount;
this._sentEndForOffset = offset;
onEndReached({distanceFromEnd});
}

// Next check if the user just scrolled within the start threshold
// and call onStartReached only once for a given content length,
// and call onStartReached only once for a given item count,
// and only if onEndReached is not being executed
if (
onStartReached != null &&
this.state.cellsAroundViewport.first === 0 &&
isWithinStartThreshold &&
this._listMetrics.getContentLength() !== this._sentStartForContentLength
itemCount !== this._sentStartForItemCount
) {
this._sentStartForContentLength = this._listMetrics.getContentLength();
this._sentStartForItemCount = itemCount;
this._sentStartForOffset = offset;
onStartReached({distanceFromStart});
}

// If the user scrolls away from the start or end and back again,
// cause onStartReached or onEndReached to be triggered again
if (!isWithinStartThreshold) {
this._sentStartForContentLength = 0;
if (isScrollEvent && this._sentStartForOffset != null) {
if (offset < this._sentStartForOffset) {
this._sentStartForOffset = offset;
} else if (!isWithinStartThreshold && offset > this._sentStartForOffset) {
this._sentStartForItemCount = null;
this._sentStartForOffset = null;
}
}
if (!isWithinEndThreshold) {
this._sentEndForContentLength = 0;
if (isScrollEvent && this._sentEndForOffset != null) {
if (offset > this._sentEndForOffset) {
this._sentEndForOffset = offset;
} else if (!isWithinEndThreshold && offset < this._sentEndForOffset) {
this._sentEndForItemCount = null;
this._sentEndForOffset = null;
}
}
}

Expand Down Expand Up @@ -1784,13 +1803,18 @@ class VirtualizedList extends StateSafePureComponent<
zoomScale,
};
if (this.state.pendingScrollUpdateCount > 0) {
this.setState<'pendingScrollUpdateCount'>({pendingScrollUpdateCount: 0});
this.setState<'pendingScrollUpdateCount'>(
{pendingScrollUpdateCount: 0},
() => {
this._maybeCallOnEdgeReached(true);
},
);
}
this._updateViewableItems(this.props, this.state.cellsAroundViewport);
if (!this.props) {
return;
}
this._maybeCallOnEdgeReached();
this._maybeCallOnEdgeReached(true);
if (velocity !== 0) {
this._fillRateHelper.activate();
}
Expand Down
Loading
Loading