Cotton code
68 lines · 2.6 KB · SwiftRaw
// A paper object under the pointer lifts a little.//// On a desk with a mouse, the one question a person asks before clicking is// "is this the thing that will open?", and a phone never has to answer it. The// answer here is the paper's own: the object under the pointer lifts — its// far shadow a little softer and a little lower (`PaperLift.layers`) — over// 120 ms, and settles when the pointer leaves.//// **Who does what, so the kit stays platform-free.** The HOST says the pointer// exists (`\.cottonPointerHover`, set by the Mac's columns host). The press// styles apply `HoverLift`, which tracks the pointer and says so to what it// wraps (`\.cottonPaperHovered`). `Paper` reads that one boolean. Nothing// under `Paper/` or `Screens/` asks which platform it is on, and on the phone// the host flag is false, so `HoverLift` is the view it wraps and nothing else.import SwiftUIprivate struct CottonPointerHoverKey: EnvironmentKey {    /// False, and false is the phone: a finger has no hover.    static let defaultValue = false}private struct CottonPaperHoveredKey: EnvironmentKey {    static let defaultValue = false}extension EnvironmentValues {    /// Whether this host has a pointer that hovers. Set by a host, never by a    /// screen.    public var cottonPointerHover: Bool {        get { self[CottonPointerHoverKey.self] }        set { self[CottonPointerHoverKey.self] = newValue }    }    /// Whether the pressable object this view sits inside is under the    /// pointer. Set by `HoverLift`; read by `Paper`.    public var cottonPaperHovered: Bool {        get { self[CottonPaperHoveredKey.self] }        set { self[CottonPaperHoveredKey.self] = newValue }    }}/// Tracks the pointer over a pressable and tells the paper inside it.struct HoverLift: ViewModifier {    /// How long the lift takes, both ways.    static let duration: Double = 0.12    @Environment(\.cottonPointerHover) private var pointer    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @State private var hovering = false    func body(content: Content) -> some View {        if pointer {            content                .environment(\.cottonPaperHovered, hovering)                .onHover { inside in                    // Under reduce-motion the lift still happens — it is how a                    // person knows what they are pointing at — it just does not                    // travel.                    withAnimation(reduceMotion ? nil : .easeOut(duration: Self.duration)) {                        hovering = inside                    }                }        } else {            content        }    }}