Cotton code
172 lines · 5.5 KB · SwiftRaw
// The one press feel, and the one haptic seam.//// Every tappable in the design system is this: a spring scale to// 0.97 with a light haptic, skipping the scale — never the haptic — under// reduce-motion. The rule carries: a person who has asked for less movement// still gets the confirmation that their finger landed.import SwiftUI#if canImport(UIKit)import UIKit#endif/// What a control asks the phone to feel. A protocol so a test can assert WHICH/// haptic a control fires without a device, and so nothing in a view body/// reaches `UIImpactFeedbackGenerator` directly.public protocol Haptics: Sendable {    /// A move between things — a chip lands, a face is picked, a row is chosen.    func select()    /// A press that DOES something: a send, a submit, a mic tap. The phone's    /// `press` and `select` map to two different generators, and Send is the    /// most repeated action in the app — collapsing the two would change how    /// the single most-felt control feels.    func press()    func success()    /// A destructive act about to happen — the confirm on "Leave this database",    /// on revoking a device, on removing a key. The vocabulary declares FIVE    /// events and this app carried three; 4h's settings screens are where the    /// other two are actually asked for, and a `haptic("warning")` that fires    /// nothing is a warning the person does not get.    func warning()    /// Something did not work. The fifth of the five.    func error()}#if os(iOS)struct SystemHaptics: Haptics {    public init() {}    public func select() {        MainActor.assumeIsolated { UISelectionFeedbackGenerator().selectionChanged() }    }    public func press() {        MainActor.assumeIsolated {            UIImpactFeedbackGenerator(style: .light).impactOccurred()        }    }    public func success() {        MainActor.assumeIsolated {            UINotificationFeedbackGenerator().notificationOccurred(.success)        }    }    public func warning() {        MainActor.assumeIsolated {            UINotificationFeedbackGenerator().notificationOccurred(.warning)        }    }    public func error() {        MainActor.assumeIsolated {            UINotificationFeedbackGenerator().notificationOccurred(.error)        }    }}#else/// A Mac has no haptic engine to speak of, and no pointer press wants one.struct SystemHaptics: Haptics {    public init() {}    public func select() {}    public func press() {}    public func success() {}    public func warning() {}    public func error() {}}#endif/// Records what was asked for. Lives here rather than in the test target so a/// gallery build can run with the phone silent.public final class RecordingHaptics: Haptics, @unchecked Sendable {    public private(set) var events: [String] = []    private let lock = NSLock()    public init() {}    public func select() {        lock.lock()        events.append("select")        lock.unlock()    }    public func press() {        lock.lock()        events.append("press")        lock.unlock()    }    public func success() {        lock.lock()        events.append("success")        lock.unlock()    }    public func warning() {        lock.lock()        events.append("warning")        lock.unlock()    }    public func error() {        lock.lock()        events.append("error")        lock.unlock()    }}private struct HapticsKey: EnvironmentKey {    static let defaultValue: any Haptics = SystemHaptics()}extension EnvironmentValues {    public var cottonHaptics: any Haptics {        get { self[HapticsKey.self] }        set { self[HapticsKey.self] = newValue }    }}/// The app's press style: a spring scale, and nothing else. It does NOT fire/// the haptic — a control fires its own, because which one it is carries/// meaning (`select` for a move, `press` for an action, `success` for a/// completion).public struct MotionButtonStyle: ButtonStyle {    private let pressScale: CGFloat    @Environment(\.accessibilityReduceMotion) private var reduceMotion    public init(pressScale: CGFloat = 0.97) {        self.pressScale = pressScale    }    public func makeBody(configuration: Configuration) -> some View {        configuration.label            .scaleEffect(configuration.isPressed && !reduceMotion ? pressScale : 1)            .animation(.spring(response: 0.25, dampingFraction: 0.7), value: configuration.isPressed)            // The pressable paper objects lift under a pointer (`PointerHover.swift`);            // a host with no pointer leaves this the label.            .modifier(HoverLift())    }}/// An opacity press, for the rows that dim rather than shrink (a settings row,/// a popover row, a record row) — the phone's `active:opacity-*`.public struct OpacityButtonStyle: ButtonStyle {    private let pressed: Double    public init(pressed: Double = 0.6) {        self.pressed = pressed    }    public func makeBody(configuration: Configuration) -> some View {        configuration.label.opacity(configuration.isPressed ? pressed : 1)    }}/// The two disabled opacities the phone actually ships, kept apart rather than/// unified: 0.4 on rows and circles, 0.5 on a settings-card action pill. They/// are almost certainly drift, but the port's job is parity — a design decision/// to unify them is a design decision, and it is not this sub-step's.public enum DisabledOpacity {    public static let control: Double = 0.4    public static let actionPill: Double = 0.5}