Cotton code
254 lines · 10.5 KB · SwiftRaw
// The keyboard is dismissed ONCE, for the whole app — never per screen.//// Reported 2026-09-11: tapping outside a text field did not always dismiss the// keyboard (the chat composer, the Thoughts screen, others), and on Thoughts a// return from an inner screen sometimes showed the keyboard with no field// focused. Both are one missing rule, and a rule written per screen is a rule// the next screen forgets. So it lives in `cottonScreenFrame()`, which every// pushed screen wears, and it has four parts:////   1. **Every scroll view dismisses the keyboard interactively** —//      `.scrollDismissesKeyboard(.interactively)` on the frame reaches every//      `ScrollView` and `List` below it; a screen that must keep the keyboard//      through a scroll (the suggestion chips) says `.never` for itself.//   2. **A tap outside a text input dismisses it, and steals nothing.** The//      frame carries a SIMULTANEOUS spatial tap — a button under the finger//      still fires — and the handler asks two questions before resigning: is//      the view under the point a text input (then the tap was INTO a field,//      not out of one), and is the point inside a view that asked the keyboard//      to stay (`.keyboardStaysOnTap()`: the composer bar and its chips, where//      a tap on Send or on a suggestion must not fold the keyboard away).//   3. **A screen that leaves takes its keyboard with it.** When the screen's//      view is about to disappear — covered by a push, or popped — and the//      first responder is one of ITS views, it resigns. A returning screen can//      therefore never inherit a responder nobody can see, which is what "the//      keyboard with no field focused" was. A screen whose field was NOT the//      responder is left alone, so the screen arriving on top keeps whatever//      focus it asked for on appear.//   4. **Dragging DOWN puts it away** (architect 2045): `.interactively` folds//      the keyboard only once the finger reaches it, so a list dragged down//      kept it up. A pan on the WINDOW, recognized beside every other//      gesture and cancelling no touch, resigns on a clear downward drag that//      did not start in a text input or a view that keeps the keyboard. An//      upward drag — reading on while typing — keeps it.//// `KeyboardDismissalTests` holds the decision (`shouldDismiss`) and the sweep// that no screen writes its own `resignFirstResponder` / `endEditing` /// tap-to-dismiss.import SwiftUI#if canImport(UIKit)import UIKit#endifpublic enum KeyboardDismissal {    /// Global frames that keep the keyboard on a tap, by the view that asked.    @MainActor static var persistent: [UUID: CGRect] = [:]    /// The decision, pure: a tap at `point` resigns the keyboard unless it    /// landed on a text input (`hitIsTextInput`) or inside a frame that asked    /// the keyboard to stay.    public static func shouldDismiss(        at point: CGPoint,        hitIsTextInput: Bool,        persistent: [CGRect]    ) -> Bool {        if hitIsTextInput { return false }        return !persistent.contains { $0.contains(point) }    }    /// The drag half, pure: a drag puts the keyboard away when it runs down    /// far enough, and mostly down — not a nudge, not a sideways swipe.    public static func dragDismisses(_ translation: CGSize) -> Bool {        translation.height >= 48 && translation.height >= abs(translation.width) * 2    }    // The rest of the rule is UIKit's — a software keyboard, a window's hit    // test, a first responder. Since H2 `CottonUI` compiles for macOS too, where    // there is no software keyboard to dismiss; the DECISION above stays on    // both so its test runs on both.    #if os(iOS)    /// Resign whatever holds the keyboard. The one call in the app.    @MainActor public static func resign() {        UIApplication.shared.sendAction(            #selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil        )    }    /// The tap half of the rule, from a point in the window's coordinates.    @MainActor static func tapped(at point: CGPoint, in window: UIWindow?) {        let hit = window?.hitTest(point, with: nil)        let intoAField = hit.map(Self.isTextInput) ?? false        guard shouldDismiss(at: point, hitIsTextInput: intoAField, persistent: Array(persistent.values)) else {            return        }        resign()    }    /// A text input, or a view inside one (a text view's own content view).    static func isTextInput(_ view: UIView) -> Bool {        var current: UIView? = view        while let candidate = current {            if candidate is UITextInput { return true }            current = candidate.superview        }        return false    }    /// The view holding the keyboard, if any is in this window.    @MainActor static func firstResponder(in root: UIView) -> UIView? {        if root.isFirstResponder { return root }        for child in root.subviews {            if let found = firstResponder(in: child) { return found }        }        return nil    }    #endif}// MARK: - The frame's half/// What `cottonScreenFrame()` applies: the scroll rule, the tap, and the probe/// that resigns a leaving screen's own responder.#if os(iOS)struct DismissesKeyboard: ViewModifier {    @State private var box = WindowBox()    func body(content: Content) -> some View {        content            .scrollDismissesKeyboard(.interactively)            .simultaneousGesture(                SpatialTapGesture(coordinateSpace: .global).onEnded { value in                    KeyboardDismissal.tapped(at: value.location, in: box.window)                }            )            .background(KeyboardProbe(box: box).frame(width: 0, height: 0))    }}/// The window, found from inside the hierarchy, so the tap can hit-test.@MainActor final class WindowBox {    weak var window: UIWindow?}/// A child controller inside the screen: it learns the window, and it sees the/// screen's own appearance callbacks — a child gets `viewWillDisappear` when/// its parent is covered or popped.private struct KeyboardProbe: UIViewControllerRepresentable {    let box: WindowBox    func makeUIViewController(context: Context) -> KeyboardProbeController {        let controller = KeyboardProbeController()        controller.box = box        return controller    }    func updateUIViewController(_ controller: KeyboardProbeController, context: Context) {        controller.box = box    }}final class KeyboardProbeController: UIViewController {    var box: WindowBox?    override func viewDidAppear(_ animated: Bool) {        super.viewDidAppear(animated)        box?.window = view.window        if let window = view.window { DownwardDrag.watch(window) }    }    override func viewWillDisappear(_ animated: Bool) {        super.viewWillDisappear(animated)        // The SCREEN is the parent the SwiftUI host made for this child; its        // view is what is leaving. Resign only a responder that lives in it.        guard let screen = parent?.view, let window = view.window ?? box?.window,            let responder = KeyboardDismissal.firstResponder(in: window),            responder.isDescendant(of: screen)        else { return }        responder.resignFirstResponder()    }}/// The drag half: one pan per window, beside every other gesture.@MainActor private final class DownwardDrag: NSObject, UIGestureRecognizerDelegate {    private static var watched: [ObjectIdentifier: DownwardDrag] = [:]    private var start: CGPoint?    private var done = false    static func watch(_ window: UIWindow) {        let key = ObjectIdentifier(window)        guard watched[key] == nil else { return }        let drag = DownwardDrag()        let pan = UIPanGestureRecognizer(target: drag, action: #selector(panned(_:)))        pan.cancelsTouchesInView = false        pan.delaysTouchesBegan = false        pan.delaysTouchesEnded = false        pan.delegate = drag        window.addGestureRecognizer(pan)        watched[key] = drag    }    @objc private func panned(_ pan: UIPanGestureRecognizer) {        guard let window = pan.view as? UIWindow else { return }        switch pan.state {        case .began:            done = false            let here = pan.location(in: window)            let moved = pan.translation(in: window)            let from = CGPoint(x: here.x - moved.x, y: here.y - moved.y)            let intoAField = window.hitTest(from, with: nil).map(KeyboardDismissal.isTextInput) ?? false            start = KeyboardDismissal.shouldDismiss(                at: from, hitIsTextInput: intoAField, persistent: Array(KeyboardDismissal.persistent.values)) ? from : nil        case .changed:            let moved = pan.translation(in: window)            guard !done, start != nil, KeyboardDismissal.dragDismisses(CGSize(width: moved.x, height: moved.y)) else { return }            done = true            KeyboardDismissal.resign()        default:            start = nil        }    }    func gestureRecognizer(        _ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer    ) -> Bool { true }}// MARK: - Where the keyboard stays/// A view a tap on which must NOT fold the keyboard away — the composer bar/// with its Send button, the suggestion chips above it. It publishes its/// global frame while it is on screen; the frame's tap skips points inside.private struct KeyboardStaysOnTap: ViewModifier {    @State private var id = UUID()    func body(content: Content) -> some View {        content            .background(                GeometryReader { proxy in                    let frame = proxy.frame(in: .global)                    Color.clear                        .onAppear { KeyboardDismissal.persistent[id] = frame }                        .onChange(of: frame) { _, now in KeyboardDismissal.persistent[id] = now }                        .onDisappear { KeyboardDismissal.persistent[id] = nil }                }            )    }}extension View {    /// The frame's keyboard rule — applied by `cottonScreenFrame()` and by    /// nothing else.    func dismissesKeyboard() -> some View { modifier(DismissesKeyboard()) }    /// A tap inside this view keeps the keyboard up.    public func keyboardStaysOnTap() -> some View { modifier(KeyboardStaysOnTap()) }}#elseextension View {    /// No software keyboard on a Mac: both names stay so the frame and the    /// screens read the same, and do nothing.    func dismissesKeyboard() -> some View { self }    public func keyboardStaysOnTap() -> some View { self }}#endif