Skip to content

Instantly share code, notes, and snippets.

@kmagiera
Created January 29, 2021 14:15
Show Gist options
  • Save kmagiera/933d1294f240321084e65e62b081e560 to your computer and use it in GitHub Desktop.
Save kmagiera/933d1294f240321084e65e62b081e560 to your computer and use it in GitHub Desktop.
import React, { ReactElement, useState } from "react";
import Animated, {
useAnimatedRef,
useAnimatedScrollHandler,
useSharedValue,
} from "react-native-reanimated";
import Item from "./Item";
import { COL, Positions, SIZE } from "./Config";
interface ListProps {
children: ReactElement<{ id: string }>[];
editing: boolean;
onDragEnd: (diff: Positions) => void;
}
const List = ({ children, editing, onDragEnd }: ListProps) => {
const scrollY = useSharedValue(0);
const scrollView = useAnimatedRef<Animated.ScrollView>();
const onScroll = useAnimatedScrollHandler({
onScroll: ({ contentOffset: { y } }) => {
scrollY.value = y;
},
});
const dragFromIndex = useSharedValue(-1);
const dragToIndex = useSharedValue(-1);
const [order, setOrder] = useState(children.map((child, index) => index));
const onDragEndHandler = (from, to) => {
const newOrder = [...order];
if (from < to) {
for (let i = from; i < to; i++) {
newOrder[i] = order[i+1]
}
newOrder[to] = order[from];
} else {
for (let i = from; i > to; i--) {
newOrder[i] = order[i-1]
}
newOrder[to] = order[from];
}
setOrder(newOrder);
}
return (
<Animated.ScrollView
onScroll={onScroll}
ref={scrollView}
contentContainerStyle={{
height: Math.ceil(children.length / COL) * SIZE,
}}
showsVerticalScrollIndicator={false}
bounces={false}
scrollEventThrottle={16}
>
{order.map((order, index) => {
const child = children[order];
return (
<Item
editing={true}
key={child.props.id}
dragFromIndex={dragFromIndex}
dragToIndex={dragToIndex}
index={index}
onDragEnd={onDragEndHandler}
scrollView={scrollView}
scrollY={scrollY}
>
{child}
</Item>
);
})}
</Animated.ScrollView>
);
};
export default List;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment