All files / src/components/Reorder/utils check-reorder.ts

94.74% Statements 18/19
92.86% Branches 13/14
100% Functions 2/2
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 3532x 32x     32x           6x   7x   4x   4x 4x   4x   3x 3x 3x   3x       2x     1x    
import { mix } from "popmotion"
import { moveItem } from "../../../utils/array"
import { ItemData } from "../types"
 
export function checkReorder<T>(
    order: ItemData<T>[],
    value: T,
    offset: number,
    velocity: number
): ItemData<T>[] {
    if (!velocity) return order
 
    const index = order.findIndex((item) => item.value === value)
 
    Iif (index === -1) return order
 
    const nextOffset = velocity > 0 ? 1 : -1
    const nextItem = order[index + nextOffset]
 
    if (!nextItem) return order
 
    const item = order[index]
    const nextLayout = nextItem.layout
    const nextItemCenter = mix(nextLayout.min, nextLayout.max, 0.5)
 
    if (
        (nextOffset === 1 && item.layout.max + offset > nextItemCenter) ||
        (nextOffset === -1 && item.layout.min + offset < nextItemCenter)
    ) {
        return moveItem(order, index, index + nextOffset)
    }
 
    return order
}