// 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.importSwiftUI#if canImport(UIKit)import UIKit#endifpublicenumKeyboardDismissal {/// Global frames that keep the keyboard on a tap, by the view that asked. @MainActor staticvar 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.publicstaticfunc shouldDismiss( at point: CGPoint, hitIsTextInput: Bool, persistent: [CGRect] ) -> Bool {if hitIsTextInput { returnfalse }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.publicstaticfunc 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 publicstaticfunc 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 staticfunc tapped(at point: CGPoint, in window: UIWindow?) {let hit = window?.hitTest(point, with: nil)let intoAField = hit.map(Self.isTextInput) ?? falseguard 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).staticfunc isTextInput(_ view: UIView) -> Bool {var current: UIView? = viewwhilelet candidate = current {if candidate is UITextInput { returntrue } current = candidate.superview }returnfalse }/// The view holding the keyboard, if any is in this window. @MainActor staticfunc firstResponder(in root: UIView) -> UIView? {if root.isFirstResponder { return root }for child in root.subviews {iflet found = firstResponder(in: child) { return found } }returnnil } #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)structDismissesKeyboard: ViewModifier { @State privatevar box = WindowBox()func body(content: Content) -> someView { content .scrollDismissesKeyboard(.interactively) .simultaneousGesture(SpatialTapGesture(coordinateSpace: .global).onEnded { value inKeyboardDismissal.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 finalclassWindowBox {weakvar 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.privatestructKeyboardProbe: UIViewControllerRepresentable {let box: WindowBoxfunc makeUIViewController(context: Context) -> KeyboardProbeController {let controller = KeyboardProbeController() controller.box = boxreturn controller }func updateUIViewController(_ controller: KeyboardProbeController, context: Context) { controller.box = box }}finalclassKeyboardProbeController: UIViewController {var box: WindowBox?overridefunc viewDidAppear(_ animated: Bool) {super.viewDidAppear(animated) box?.window = view.windowiflet window = view.window { DownwardDrag.watch(window) } }overridefunc 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.guardlet 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 privatefinalclassDownwardDrag: NSObject, UIGestureRecognizerDelegate {privatestaticvar watched: [ObjectIdentifier: DownwardDrag] = [:]privatevar start: CGPoint?privatevar done = falsestaticfunc watch(_ window: UIWindow) {let key = ObjectIdentifier(window)guard watched[key] == nilelse { 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 privatefunc panned(_ pan: UIPanGestureRecognizer) {guardlet window = pan.view as? UIWindow else { return }switch pan.state {case .began: done = falselet 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 : nilcase .changed:let moved = pan.translation(in: window)guard !done, start != nil, KeyboardDismissal.dragDismisses(CGSize(width: moved.x, height: moved.y)) else { return } done = trueKeyboardDismissal.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.privatestructKeyboardStaysOnTap: ViewModifier { @State privatevar id = UUID()func body(content: Content) -> someView { content .background(GeometryReader { proxy inlet frame = proxy.frame(in: .global)Color.clear .onAppear { KeyboardDismissal.persistent[id] = frame } .onChange(of: frame) { _, now inKeyboardDismissal.persistent[id] = now } .onDisappear { KeyboardDismissal.persistent[id] = nil } } ) }}extensionView {/// The frame's keyboard rule — applied by `cottonScreenFrame()` and by/// nothing else.func dismissesKeyboard() -> someView { modifier(DismissesKeyboard()) }/// A tap inside this view keeps the keyboard up.publicfunc keyboardStaysOnTap() -> someView { modifier(KeyboardStaysOnTap()) }}#elseextensionView {/// No software keyboard on a Mac: both names stay so the frame and the/// screens read the same, and do nothing.func dismissesKeyboard() -> someView { self }publicfunc keyboardStaysOnTap() -> someView { self }}#endif