Call scrollToIndex only when ref is set and index is in range (#3285)

This commit is contained in:
Miguel Alatzar 2019-09-19 12:39:47 -07:00 committed by GitHub
parent 0f67b47026
commit 20fb25df8d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 14 deletions

View file

@ -299,30 +299,33 @@ export default class PostList extends PureComponent {
scrollToBottom = () => {
setTimeout(() => {
if (this.flatListRef && this.flatListRef.current) {
if (this.flatListRef?.current) {
this.flatListRef.current.scrollToOffset({offset: 0, animated: true});
}
}, 250);
};
flatListScrollToIndex = (index) => {
this.flatListRef.current.scrollToIndex({
animated: false,
index,
viewOffset: 0,
viewPosition: 1, // 0 is at bottom
});
}
scrollToIndex = (index) => {
if (this.flatListRef?.current) {
this.animationFrameInitialIndex = requestAnimationFrame(() => {
this.flatListRef.current.scrollToIndex({
animated: false,
index,
viewOffset: 0,
viewPosition: 1, // 0 is at bottom
});
});
}
this.animationFrameInitialIndex = requestAnimationFrame(() => {
if (this.flatListRef?.current && index > 0 && index <= this.getItemCount()) {
this.flatListScrollToIndex(index);
}
});
};
scrollToInitialIndexIfNeeded = (index, count = 0) => {
if (!this.hasDoneInitialScroll && this.flatListRef?.current) {
this.hasDoneInitialScroll = true;
if (!this.hasDoneInitialScroll) {
if (index > 0 && index <= this.getItemCount()) {
this.hasDoneInitialScroll = true;
this.scrollToIndex(index);
} else if (count < 3) {
setTimeout(() => {

View file

@ -55,4 +55,30 @@ describe('PostList', () => {
expect(baseProps.actions.handleSelectChannelByName).toHaveBeenCalled();
expect(wrapper.getElement()).toMatchSnapshot();
});
test('should call flatListScrollToIndex only when ref is set and index is in range', () => {
jest.spyOn(global, 'requestAnimationFrame').mockImplementation((cb) => cb());
const instance = wrapper.instance();
const flatListScrollToIndex = jest.spyOn(instance, 'flatListScrollToIndex');
const indexInRange = baseProps.postIds.length;
const indexOutOfRange = [-1, indexInRange + 1];
instance.flatListRef = {};
instance.scrollToIndex(indexInRange);
expect(flatListScrollToIndex).not.toHaveBeenCalled();
instance.flatListRef = {
current: {
scrollToIndex: jest.fn(),
},
};
for (const index of indexOutOfRange) {
instance.scrollToIndex(index);
expect(flatListScrollToIndex).not.toHaveBeenCalled();
}
instance.scrollToIndex(indexInRange);
expect(flatListScrollToIndex).toHaveBeenCalled();
});
});