Cotton code
201 lines · 8.1 KB · SwiftRaw
// Long-press, then drag. Arrow steppers are banned app-wide.//// The DECISION LAYER is pure, clock-free and unit-tested without a device. The// view below it only turns finger positions into these calls and these answers// into offsets.//// The rules that travel:////   • THE WHOLE ROW IS THE HANDLE. A grip glyph is the caller's to draw inside//     its own row; this owns the gesture and the geometry, never a row's dress.//     The rows are paper, and the one picked up is//     LIFTED — `PaperShadow.lifted`, the kit's own pickup — so a drag reads as//     a sheet taken off the pile.//   • CENTRE PASSES CENTRE, against the RESTING layout — not the gap-closed//     one, which re-seats a tall row over a short neighbour the instant it is//     picked up, before the finger has moved at all.//   • ROWS ARE MEASURED, NOT ASSUMED: a record row's height depends on whether//     it carries a caption, so a fixed-pitch model drifts on any real list.//   • A NO-OP NEVER FIRES: `from == to` returns without calling the caller.//   • A TIER BOUNDARY IS ONE LIST PER TIER, so a drag physically cannot cross//     it. There is no sections concept and there must not be one.//   • KNOWN LIMIT, accepted: no edge auto-scroll.import SwiftUIpublic enum Reorder {    /// The top edge of each row, in list coordinates.    public static func rowOffsets(_ heights: [CGFloat]) -> [CGFloat] {        var offsets: [CGFloat] = []        var running: CGFloat = 0        for height in heights {            offsets.append(running)            running += height        }        return offsets    }    /// Where the row picked up at `from` currently belongs.    ///    /// Monotone (resting centres increase), so the answer never oscillates    /// while a finger holds still. The cost is the standard one: the first swap    /// needs half of this row plus half of the next.    public static func dropIndex(heights: [CGFloat], from: Int, translationY: CGFloat) -> Int {        let count = heights.count        guard from >= 0, from < count else { return from }        let offsets = rowOffsets(heights)        let centre = offsets[from] + translationY + heights[from] / 2        var to = from        if translationY > 0 {            var i = from + 1            while i < count {                if centre <= offsets[i] + heights[i] / 2 { break }                to = i                i += 1            }        } else if translationY < 0 {            var i = from - 1            while i >= 0 {                if centre >= offsets[i] + heights[i] / 2 { break }                to = i                i -= 1            }        }        return to    }    /// How far a row that is NOT being dragged must slide so the gap the finger    /// is over stays open: one active-row height, in whichever direction closes    /// the hole the pickup left.    public static func passiveShift(        index: Int,        from: Int,        to: Int,        activeHeight: CGFloat    ) -> CGFloat {        if index == from || from == to { return 0 }        if from < to { return index > from && index <= to ? -activeHeight : 0 }        return index >= to && index < from ? activeHeight : 0    }    /// `items` with the row at `from` moved to `to`. The input is untouched.    public static func reordered<T>(_ items: [T], from: Int, to: Int) -> [T] {        guard from != to, from >= 0, to >= 0, from < items.count, to < items.count else {            return items        }        var next = items        let moved = next.remove(at: from)        next.insert(moved, at: to)        return next    }}/// How long a finger rests before the row comes up.public let reorderPickupSeconds: TimeInterval = 0.22/// How long a passive row takes to slide out of the way.public let reorderShiftSeconds: TimeInterval = 0.14public struct ReorderableList<Item: Identifiable, Row: View>: View {    private let items: [Item]    private let isEnabled: Bool    private let onReorder: (Int, Int) -> Void    private let onDragActiveChange: ((Bool) -> Void)?    private let row: (Item, Int, Bool) -> Row    @Environment(\.cottonHaptics) private var haptics    @State private var heights: [CGFloat] = []    @State private var activeIndex: Int?    @State private var dragY: CGFloat = 0    public init(        items: [Item],        enabled: Bool = true,        onReorder: @escaping (Int, Int) -> Void,        onDragActiveChange: ((Bool) -> Void)? = nil,        @ViewBuilder row: @escaping (Item, Int, Bool) -> Row    ) {        self.items = items        self.isEnabled = enabled        self.onReorder = onReorder        self.onDragActiveChange = onDragActiveChange        self.row = row    }    public var body: some View {        VStack(spacing: 0) {            ForEach(Array(items.enumerated()), id: \.element.id) { index, item in                // The kit's LIFTED pair, faded in and out rather than switched:                // a modifier that branched would give the row a new identity                // at pickup, mid-gesture.                PaperLift.lifted(                    row(item, index, index == activeIndex)                        .background(measure(index))                        .offset(y: offset(for: index)),                    amount: index == activeIndex ? 1 : 0                )                    .zIndex(index == activeIndex ? 2 : 0)                    .animation(                        index == activeIndex ? nil : .easeOut(duration: reorderShiftSeconds),                        value: dragY                    )                    .gesture(isEnabled ? dragGesture(at: index) : nil)            }        }        // A SHRINKING list truncates the measurements with it — a stale height        // array would seat a drop against rows that are no longer there.        .onChange(of: items.count) { _, count in            if heights.count > count { heights.removeLast(heights.count - count) }        }    }    private func measure(_ index: Int) -> some View {        GeometryReader { proxy in            Color.clear.onAppear { record(height: proxy.size.height, at: index) }                .onChange(of: proxy.size.height) { _, next in record(height: next, at: index) }        }    }    private func record(height: CGFloat, at index: Int) {        if heights.count <= index { heights.append(contentsOf: Array(repeating: 0, count: index + 1 - heights.count)) }        heights[index] = height    }    private func offset(for index: Int) -> CGFloat {        guard let active = activeIndex, heights.count == items.count else { return 0 }        if index == active { return dragY }        let to = Reorder.dropIndex(heights: heights, from: active, translationY: dragY)        return Reorder.passiveShift(index: index, from: active, to: to, activeHeight: heights[active])    }    private func dragGesture(at index: Int) -> some Gesture {        LongPressGesture(minimumDuration: reorderPickupSeconds)            .onEnded { _ in                haptics.select()                activeIndex = index                dragY = 0                onDragActiveChange?(true)            }            .sequenced(before: DragGesture(minimumDistance: 0))            .onChanged { value in                guard case .second(_, let drag?) = value, activeIndex == index else { return }                dragY = drag.translation.height            }            // A CANCELLED gesture never reaches `onEnded` on the phone, which            // is why the RN component resets in `onFinalize`. SwiftUI's            // sequenced gesture does end here in both cases, and the reset is            // unconditional for the same reason: a row left lifted breaks the            // list.            .onEnded { _ in                defer {                    activeIndex = nil                    dragY = 0                    onDragActiveChange?(false)                }                guard let active = activeIndex, heights.count == items.count else { return }                let to = Reorder.dropIndex(heights: heights, from: active, translationY: dragY)                guard to != active else { return }                haptics.success()                onReorder(active, to)            }    }}