Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for VirtualizedList #26

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
4 changes: 3 additions & 1 deletion Example/App.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import React from 'react';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import ScrollViewExample from './src/ScrollViewExample';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import FlatListExample from './src/FlatListExample';
import VirtualizedListExample from './src/VirtualizedListExample';

const App = () => {
return <FlatListExample />;
return <VirtualizedListExample />;
};

export default App;
105 changes: 105 additions & 0 deletions Example/src/VirtualizedListExample.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import React, {useState} from 'react';
import {
View,
TouchableOpacity,
Text,
SafeAreaView,
StyleSheet,
} from 'react-native';
import {VirtualizedList} from '@stream-io/flat-list-mvcp';

const AddMoreButton = ({onPress}) => (
<TouchableOpacity onPress={onPress} style={styles.addMoreButton}>
<Text style={styles.addMoreButtonText}>Add 5 items from this side</Text>
</TouchableOpacity>
);

const ListItem = ({item}) => (
<View style={[styles.listItem, {paddingVertical: item.value * 5 + 100}]}>
<Text>List item: {item.value}</Text>
</View>
);

// Generate unique key list item.
export const generateUniqueKey = () =>
`_${Math.random().toString(36).substr(2, 9)}`;

export default () => {
const [numbers, setNumbers] = useState(
Array.from(Array(10).keys()).map((n) => ({
id: generateUniqueKey(),
value: n,
})),
);

const addToEnd = () => {
setNumbers((prev) => {
const additionalNumbers = Array.from(Array(5).keys()).map((n) => ({
id: generateUniqueKey(),
value: n + prev[prev.length - 1].value + 1,
}));

return prev.concat(additionalNumbers);
});
};

const addToStart = () => {
setNumbers((prev) => {
const additionalNumbers = Array.from(Array(5).keys())
.map((n) => ({
id: generateUniqueKey(),
value: prev[0].value - n - 1,
}))
.reverse();

return additionalNumbers.concat(prev);
});
};

return (
<SafeAreaView style={styles.safeArea}>
<AddMoreButton onPress={addToStart} />
<View style={styles.listContainer}>
<VirtualizedList
data={numbers}
keyExtractor={(item) => item.id}
maintainVisibleContentPosition={{
minIndexForVisible: 0,
}}
getItem={(data, index) => data[index]}
getItemCount={() => numbers.length}
renderItem={ListItem}
/>
</View>
<AddMoreButton onPress={addToEnd} />
</SafeAreaView>
);
};

const styles = StyleSheet.create({
safeArea: {
flex: 1,
},
addMoreButton: {
padding: 8,
backgroundColor: '#008CBA',
alignItems: 'center',
},
addMoreButtonText: {
color: 'white',
},
listContainer: {
paddingVertical: 4,
flexGrow: 1,
flexShrink: 1,
backgroundColor: 'black',
},
listItem: {
flex: 1,
padding: 32,
justifyContent: 'center',
alignItems: 'center',
borderWidth: 8,
backgroundColor: 'white',
},
});
122 changes: 122 additions & 0 deletions src/VirtualizedList.android.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import React, { MutableRefObject, useEffect, useRef } from 'react';
import {
VirtualizedList,
VirtualizedListProps,
NativeModules,
Platform,
} from 'react-native';

export const ScrollViewManager = NativeModules.MvcpScrollViewManager;

interface EnhancedVirtualizedList<ItemT> extends VirtualizedList<ItemT> {
getScrollableNode(): any;
}

export default (React.forwardRef(
<T extends any>(
props: VirtualizedListProps<T>,
forwardedRef:
| ((instance: EnhancedVirtualizedList<T> | null) => void)
| MutableRefObject<EnhancedVirtualizedList<T> | null>
| null
) => {
const { maintainVisibleContentPosition: mvcp } = props;

const flRef = useRef<EnhancedVirtualizedList<T> | null>(null);
const isMvcpEnabled = useRef<any>(null);
const autoscrollToTopThreshold = useRef<number | null>();
const minIndexForVisible = useRef<number>();
const handle = useRef<any>(null);
const enableMvcpRetries = useRef<number>(0);

const propAutoscrollToTopThreshold =
mvcp?.autoscrollToTopThreshold || -Number.MAX_SAFE_INTEGER;
const propMinIndexForVisible = mvcp?.minIndexForVisible || 1;
const hasMvcpChanged =
autoscrollToTopThreshold.current !== propAutoscrollToTopThreshold ||
minIndexForVisible.current !== propMinIndexForVisible;
const enableMvcp = () => {
if (!flRef.current) return;

const scrollableNode = flRef.current.getScrollableNode();
const enableMvcpPromise = ScrollViewManager.enableMaintainVisibleContentPosition(
scrollableNode,
autoscrollToTopThreshold.current,
minIndexForVisible.current
);

return enableMvcpPromise.then((_handle: number) => {
handle.current = _handle;
enableMvcpRetries.current = 0;
});
};

const enableMvcpWithRetries = () => {
return enableMvcp()?.catch(() => {
/**
* enableMaintainVisibleContentPosition from native module may throw IllegalViewOperationException,
* in case view is not ready yet. In that case, lets do a retry!!
*/
if (enableMvcpRetries.current < 10) {
setTimeout(enableMvcpWithRetries, 10);
enableMvcpRetries.current += 1;
}
});
};

const disableMvcp: () => Promise<void> = () => {
if (!ScrollViewManager || !handle?.current) {
return Promise.resolve();
}

return ScrollViewManager.disableMaintainVisibleContentPosition(
handle.current
);
};

// We can only call enableMaintainVisibleContentPosition once the ref to underlying scrollview is ready.
const resetMvcpIfNeeded = (): void => {
if (!mvcp || Platform.OS !== 'android' || !flRef.current) {
return;
}

/**
* If the enableMaintainVisibleContentPosition has already been called, then
* lets not call it again, unless prop values of mvcp changed.
*
* This condition is important since `resetMvcpIfNeeded` gets called in refCallback,
* which gets called by react on every update to list.
*/
if (isMvcpEnabled.current && !hasMvcpChanged) {
return;
}
autoscrollToTopThreshold.current = propAutoscrollToTopThreshold;
minIndexForVisible.current = propMinIndexForVisible;

isMvcpEnabled.current = true;
disableMvcp().then(enableMvcpWithRetries);
};

const refCallback: (instance: EnhancedVirtualizedList<T> | null) => void = (
ref
) => {
flRef.current = ref;

resetMvcpIfNeeded();
if (typeof forwardedRef === 'function') {
forwardedRef(ref);
} else if (forwardedRef) {
forwardedRef.current = ref;
}
};

useEffect(() => {
// disable before unmounting
return () => {
disableMvcp();
};
}, []);

return <VirtualizedList<T> {...props} ref={refCallback} />;
}
) as unknown) as typeof VirtualizedList;
3 changes: 3 additions & 0 deletions src/VirtualizedList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { VirtualizedList } from 'react-native';

export default VirtualizedList;
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { default as FlatList } from './FlatList';
export { default as ScrollView } from './ScrollView';
export { default as VirtualizedList } from './VirtualizedList';