Created
January 29, 2021 14:15
-
-
Save kmagiera/933d1294f240321084e65e62b081e560 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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