$ git show tab-reorder
Drag to reorder grid
Long-press a tile, drag it over another, and the grid reshuffles around it.
Inspired by Google ChromeFrom William Candillon’s “Can it be done in React Native?” series. The code here is a simplified rewrite for Reanimated 4 and 3.
This snippet uses APIs that didn’t change between versions, so the same code runs on Reanimated 4 and 3.
const positions = useSharedValue(Object.fromEntries(ids.map((id, i) => [id, i])));
const toXY = i => { 'worklet'; return { x: (i % COLS) * SIZE, y: Math.floor(i / COLS) * SIZE }; };
function Tile({ id }) {
const start = toXY(positions.value[id]);
const tx = useSharedValue(start.x), ty = useSharedValue(start.y), active = useSharedValue(false);
useAnimatedReaction(() => positions.value[id], slot => {
if (!active.value) { const p = toXY(slot); tx.value = withSpring(p.x); ty.value = withSpring(p.y); }
});
const pan = Gesture.Pan().activateAfterLongPress(250)
.onStart(() => { active.value = true; })
.onChange(e => {
tx.value += e.changeX; ty.value += e.changeY;
const slot = clamp(Math.round(ty.value / SIZE) * COLS + Math.round(tx.value / SIZE), 0, ids.length - 1);
const from = positions.value[id];
if (slot !== from) {
const other = Object.keys(positions.value).find(k => positions.value[k] === slot);
positions.value = { ...positions.value, [id]: slot, [other]: from };
}
})
.onEnd(() => {
const p = toXY(positions.value[id]);
tx.value = withSpring(p.x); ty.value = withSpring(p.y); active.value = false;
});
const style = useAnimatedStyle(() => ({
position: 'absolute', zIndex: active.value ? 10 : 0,
transform: [{ translateX: tx.value }, { translateY: ty.value }, { scale: withSpring(active.value ? 1.06 : 1) }],
}));
// <GestureDetector gesture={pan}><Animated.View style={[styles.tile, style]} /></GestureDetector>
}