Cotton code
346 lines · 15.0 KB · SwiftRaw
import CottonValuesimport Observationimport SwiftUI#if canImport(UIKit)import UIKit#endif/// A face-owned transition: positive travel turns to the next record,/// negative to the previous. Selection stays with the shell until settling.public struct FaceTurn {    public var progress: Double    /// The filled neighbours by signed offset from the shown card; each    /// carries its own picture.    public var window: [Int: DeckCard] = [:]    public var band: FaceTurnBand = .full    public init(progress: Double = 0, window: [Int: DeckCard] = [:], band: FaceTurnBand = .full) {        self.progress = progress        self.window = window        self.band = band    }}extension EnvironmentValues {    @Entry public var faceTurn = FaceTurn()}/// Shared by the phone deck and Loom: direct travel, a friction flywheel,/// and one selection commit after the mechanical detent. No data is read here.@MainActor @Observablepublic final class FaceTurnMotion {    public private(set) var progress: Double = 0    public private(set) var settling = false    public private(set) var velocity: Double = 0    public private(set) var band: FaceTurnBand = .full    public private(set) var tick = 0    public var index: Int { Int(progress.rounded(.towardZero)) }    public func position(from base: Int, count: Int) -> Int {        min(max(0, count - 1), max(0, base + index))    }    private var lastTickIndex = 0    private var runner: Task<Void, Never>?    #if canImport(UIKit)    private var displayLink: FaceTurnDisplayLink?    #endif    private var dragOrigin: Double?    private var lastTime: TimeInterval = 0    private var settleStart: TimeInterval?    private var settleOrigin: Double = 0    private var target = 0    private var bounds = 0...0    private var landing: ((Int) -> Void)?    private let clock: () -> TimeInterval    private let automatic: Bool    public init(clock: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }, automatic: Bool = true) {        self.clock = clock        self.automatic = automatic    }    public static let pointsPerCard: Double = 36    public static let deceleration: Double = 0.998    public static let friction = -1000 * log(deceleration)    public static func knobTravel(_ points: CGFloat) -> Double { Double(points) / pointsPerCard }    public static func carriedCards(velocity: Double, seconds: Double) -> Double {        velocity * (1 - exp(-friction * max(0, seconds))) / friction    }    /// UIKit's predicted end translation uses normal scroll deceleration.    public static func releaseVelocity(translation: CGFloat, predicted: CGFloat, gearing: Double) -> Double {        Double(predicted - translation) / gearing * friction    }    /// Catch at the visible detent without publishing an intermediate selection.    public func catchWheel() {        stopFrames()        progress = Double(min(bounds.upperBound, max(bounds.lowerBound, Int(progress.rounded()))))        velocity = 0; band = .full; settling = false        settleStart = nil; dragOrigin = nil    }    public func scrub(_ points: CGFloat, velocity pointsVelocity: CGFloat, gearing: Double = pointsPerCard,                      bounds: ClosedRange<Int>) {        if dragOrigin == nil {            self.bounds = bounds            if settling { catchWheel() }            dragOrigin = progress        }        self.bounds = bounds        let raw = (dragOrigin ?? 0) + Double(points) / gearing        let clamped = min(Double(bounds.upperBound), max(Double(bounds.lowerBound), raw))        // Ten degrees at most (45 degrees per card), with a soft end stop.        let excess = raw - clamped        progress = clamped + 0.22 * excess / (1 + abs(excess))        velocity = Double(pointsVelocity) / gearing        updateBandAndTick()    }    public func spinRelease(velocity: Double, bounds: ClosedRange<Int>, detent: Int? = nil, commit: @escaping (Int) -> Void) {        self.bounds = bounds; landing = commit; dragOrigin = nil        self.velocity = velocity        settling = true; lastTime = clock(); settleStart = nil        if progress < Double(bounds.lowerBound) || progress > Double(bounds.upperBound) || abs(velocity) < 0.8 {            beginDetent(at: lastTime)            if let detent { target = min(bounds.upperBound, max(bounds.lowerBound, detent)) }        }        stopFrames()        startFrames()    }    private func startFrames() {        guard automatic else { return }        #if canImport(UIKit)        displayLink = FaceTurnDisplayLink { [weak self] in            guard let self, self.settling else { return false }            self.advance()            return self.settling        }        #else        runner = Task { [weak self] in            while !Task.isCancelled {                try? await Task.sleep(for: .milliseconds(16))                guard !Task.isCancelled, let self, self.settling else { return }                self.advance()            }        }        #endif    }    private func stopFrames() {        runner?.cancel(); runner = nil        #if canImport(UIKit)        displayLink?.invalidate(); displayLink = nil        #endif    }    /// Analytic friction, driven by an injectable monotonic clock, independent of frame rate.    public func advance() {        guard settling else { return }        let now = clock()        if let start = settleStart {            let t = min(1, max(0, (now - start) / 0.35))            // The existing mechanical timing curve, evaluated so a catch reads the visible position.            var lo = 0.0, hi = 1.0            for _ in 0..<20 {                let u = (lo + hi) / 2                let x = 3 * (1-u) * (1-u) * u * 0.2 + 3 * (1-u) * u * u * 0.25 + u*u*u                if x < t { lo = u } else { hi = u }            }            let u = (lo + hi) / 2            let y = 3 * (1-u) * (1-u) * u * 0.75 + 3 * (1-u) * u*u + u*u*u            progress = settleOrigin + (Double(target) - settleOrigin) * y            if t >= 1 {                let commit = landing; landing = nil                let step = target                progress = 0; settling = false; velocity = 0; band = .full; settleStart = nil; lastTickIndex = 0                if step != 0 { commit?(step) }            }        } else {            let dt = max(0, now - lastTime)            progress += Self.carriedCards(velocity: velocity, seconds: dt)            velocity *= exp(-Self.friction * dt)            if progress < Double(bounds.lowerBound) || progress > Double(bounds.upperBound) {                let end = min(Double(bounds.upperBound), max(Double(bounds.lowerBound), progress))                progress = end + (velocity < 0 ? -0.2 : 0.2)                beginDetent(at: now)            } else if abs(velocity) < 0.8 { beginDetent(at: now, projected: progress + velocity / Self.friction) }        }        lastTime = now        updateBandAndTick()    }    private func beginDetent(at time: TimeInterval, projected: Double? = nil) {        target = min(bounds.upperBound, max(bounds.lowerBound, Int((projected ?? progress).rounded())))        settleOrigin = progress; settleStart = time        velocity = 0; band = .full    }    private func updateBandAndTick() {        band = band.updated(speed: abs(velocity))        let index = Int(progress.rounded())        if index != lastTickIndex, abs(velocity) < 10 || abs(index - lastTickIndex) >= 4 {            tick += 1; lastTickIndex = index        }    }    /// A slow card pull's travel, a fraction of a card either way.    public static func travel(_ translation: CGFloat, width: CGFloat) -> Double {        max(-1, min(1, -Double(translation / max(120, width * 0.65))))    }    public static func crossesTop(_ progress: Double, predicted: Double) -> Bool {        abs(progress) >= 0.5 || (abs(progress) > 0.025 && predicted * progress > 0 && abs(predicted) >= 0.5)    }    /// The wheel coasting on its flywheel, before its detent: a touch catches it.    public var coasting: Bool { settling && settleStart == nil }    /// A side-third tap: one card on through the same detent a drag lands    /// in. A tap made while the wheel settles adds to where it is going, so    /// every tap moves a card (owner, 29 Oct 2026: keep tapping and the    /// records fly by). At rest, an unavailable neighbour is the caller's    /// plain step, committed at once.    public func tap(_ step: Int, available: Bool, bounds: ClosedRange<Int>, commit: @escaping (Int) -> Void) {        guard settling || available else { commit(step); return }        let from = settling && settleStart != nil ? target : Int(progress.rounded())        stopFrames()        self.bounds = bounds; landing = commit; dragOrigin = nil        velocity = 0; band = .full; settling = true        lastTime = clock()        target = min(bounds.upperBound, max(bounds.lowerBound, from + step))        settleOrigin = progress; settleStart = lastTime        startFrames()    }    /// A search, face change or external selection cancels an unlanded turn.    public func cancel() {        stopFrames(); dragOrigin = nil; landing = nil        velocity = 0; band = .full; settleStart = nil; lastTickIndex = 0        var rest = Transaction()        rest.disablesAnimations = true        withTransaction(rest) { progress = 0; settling = false }    }}public enum FaceTurnBand: Sendable {    case full, name, riffle    public func updated(speed: Double) -> Self {        switch self {        case .full: speed > 12 ? .riffle : (speed >= 6 ? .name : .full)        case .name: speed > 12 ? .riffle : (speed < 5 ? .full : .name)        case .riffle: speed < 5 ? .full : (speed < 11 ? .name : .riffle)        }    }}/// Shared hit geometry: the gesture and the painted object use the same rects.public enum RolodexHit {    /// Points of a drag on the knob to one card.    public static let knobGearing = 36.0    public static func knob(_ point: CGPoint, in room: CGSize) -> Bool {        let k = RolodexKnobs.self        let w = min(room.width * k.fillWidth, room.height * k.fillHeight * k.aspect)        let h = w / k.aspect        return k.knobRects.contains { r in            let rect = CGRect(x: (room.width-w)/2 + r.minX*w, y: (room.height-h)/2 + r.minY*h,                              width: r.width*w, height: r.height*h)            return rect.insetBy(dx: -max(0, (44-rect.width)/2), dy: -max(0, (44-rect.height)/2)).contains(point)        }    }}public struct RolodexSpinGesture: ViewModifier {    let enabled: Bool    let motion: FaceTurnMotion    let bounds: ClosedRange<Int>    let commit: (Int) -> Void    @State private var last: (time: Date, points: CGFloat)?    @State private var speed: CGFloat = 0    @State private var caught = false    public init(enabled: Bool, motion: FaceTurnMotion, bounds: ClosedRange<Int>, commit: @escaping (Int) -> Void) {        self.enabled = enabled; self.motion = motion; self.bounds = bounds; self.commit = commit    }    public func body(content: Content) -> some View {        content.overlay {            GeometryReader { box in                Color.clear.allowsHitTesting(false)                    .preference(key: RolodexRoom.self, value: box.size)            }        }        .onPreferenceChange(RolodexRoom.self) { room = $0 }        .simultaneousGesture(DragGesture(minimumDistance: 0)            .onChanged { value in                guard enabled else { return }                if last == nil, !caught, motion.coasting {                    motion.catchWheel()                    caught = true                }                let knob = RolodexHit.knob(value.startLocation, in: room)                if knob {                    guard value.translation.height != 0 else { return }                } else {                    guard abs(value.translation.width) > abs(value.translation.height) else { return }                }                let points = knob ? value.translation.height : -value.translation.width                if let last {                    let dt = value.time.timeIntervalSince(last.time)                    if dt > 0 { speed = (points-last.points) / dt }                }                last = (value.time, points)                let gearing = knob ? RolodexHit.knobGearing : max(120, Double(room.width)*0.65)                let travel = knob ? points : min(CGFloat(gearing), max(-CGFloat(gearing), points))                motion.scrub(travel, velocity: speed, gearing: gearing, bounds: bounds)            }            .onEnded { value in                guard enabled else { return }                guard last != nil else {                    // A caught wheel rests at its card, unless the tap that                    // caught it has already set it going again.                    if caught, !motion.settling { motion.spinRelease(velocity: 0, bounds: bounds, commit: commit) }                    caught = false                    return                }                let knob = RolodexHit.knob(value.startLocation, in: room)                let translation = knob ? value.translation.height : -value.translation.width                let predicted = knob ? value.predictedEndTranslation.height : -value.predictedEndTranslation.width                let gearing = 36.0                var velocity = FaceTurnMotion.releaseVelocity(translation: translation, predicted: predicted, gearing: gearing)                // Slow card pulls retain the old half-card detent; a flick uses the wheel.                var detent: Int?                if !knob, abs(velocity) < 6 {                    let travel = FaceTurnMotion.travel(-translation, width: room.width)                    let prediction = FaceTurnMotion.travel(-predicted, width: room.width)                    let origin = Int((motion.progress - travel).rounded())                    detent = origin + (FaceTurnMotion.crossesTop(travel, predicted: prediction) ? (travel < 0 ? -1 : 1) : 0)                    velocity = 0                }                motion.spinRelease(velocity: velocity, bounds: bounds, detent: detent, commit: commit)                last = nil; speed = 0; caught = false            }, including: enabled ? .all : .none)        .sensoryFeedback(.selection, trigger: motion.tick)    }    @State private var room: CGSize = .zero}private struct RolodexRoom: PreferenceKey {    static let defaultValue: CGSize = .zero    static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() }}#if canImport(UIKit)/// Follow the phone's display cadence, including ProMotion, while the wheel runs.@MainActorprivate final class FaceTurnDisplayLink: NSObject {    private let tick: () -> Bool    private var link: CADisplayLink?    init(tick: @escaping () -> Bool) {        self.tick = tick        super.init()        let link = CADisplayLink(target: self, selector: #selector(frame))        link.preferredFrameRateRange = CAFrameRateRange(minimum: 30, maximum: 120, preferred: 120)        link.add(to: .main, forMode: .common)        self.link = link    }    @objc private func frame() { if !tick() { invalidate() } }    func invalidate() { link?.invalidate(); link = nil }}#endif