Skip to content

Commit

Permalink
Call scrollToIndex only when ref is set and index is in range (matter…
Browse files Browse the repository at this point in the history
  • Loading branch information
migbot authored and sudheerDev committed Sep 19, 2019
1 parent b6bd311 commit ecbbb3f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 14 deletions.
31 changes: 17 additions & 14 deletions app/components/post_list/post_list.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down
26 changes: 26 additions & 0 deletions app/components/post_list/post_list.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});

0 comments on commit ecbbb3f

Please sign in to comment.