Cotton code
263 lines · 11.3 KB · SwiftRaw
// The composer's text area: one line high at rest, growing with the words to// about seven lines, then scrolling inside itself with the newest words kept// in view. Typed and dictated words share the text; tentative words are drawn// lighter. A hardware keyboard's Return sends or breaks the line as the app// says; Shift-Return always breaks it and Command-Return always sends.//// UIKit's text view, because SwiftUI's growing TextField can neither draw a// range lighter nor say where the caret is (a dictation anchors there).#if canImport(UIKit)import SwiftUIimport UIKit/// The keyboard's height on the screen, as its frame changes, and the text areas to measure again when it does.@MainActorfinal class ComposerKeyboard {    static let shared = ComposerKeyboard()    private var frame: CGRect = .zero    private let views = NSHashTable<UIView>.weakObjects()    private init() {        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: .main) { note in            let frame = (note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue ?? .zero            MainActor.assumeIsolated { ComposerKeyboard.shared.changed(frame) }        }        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { _ in            MainActor.assumeIsolated { ComposerKeyboard.shared.changed(.zero) }        }    }    func watch(_ view: UIView) { views.add(view) }    /// How much of a screen this high the keyboard covers (0 while it is down).    func height(over screen: CGFloat) -> CGFloat {        guard !frame.isEmpty else { return 0 }        return max(0, min(frame.height, screen - frame.minY))    }    private func changed(_ now: CGRect) {        guard now != frame else { return }        frame = now        for view in views.allObjects { view.invalidateIntrinsicContentSize() }    }}struct ComposerTextArea: UIViewRepresentable {    @Binding var text: String    var focused: Binding<Bool>?    let face: ComposerFace    let ink: Color    let faint: Color    let tentative: NSRange?    /// Where the caret goes after the composer itself writes the text (a dictation's end).    let caret: Int?    let returnSends: Bool    let label: String    let identifier: String    let send: () -> Void    let edited: (String) -> Void    let selected: (NSRange) -> Void    /// The height standing over the field inside the box (`Composer.reserving`).    var reserved: CGFloat = 0    static let inset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)    func makeCoordinator() -> Coordinator { Coordinator(self) }    func makeUIView(context: Context) -> ComposerTextView {        let view = ComposerTextView()        // The keyboard's rise or change of height measures the area again (its cap is a third of what is left).        ComposerKeyboard.shared.watch(view)        view.delegate = context.coordinator        view.backgroundColor = .clear        view.textContainerInset = Self.inset        view.textContainer.lineFragmentPadding = 0        view.adjustsFontForContentSizeCategory = true        view.isScrollEnabled = true        view.showsVerticalScrollIndicator = true        view.alwaysBounceVertical = false        view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)        view.setContentHuggingPriority(.defaultHigh, for: .vertical)        view.onKey = { [weak coordinator = context.coordinator, weak view] key in            guard let view else { return }            coordinator?.key(key, in: view)        }        context.coordinator.apply(to: view, force: true)        return view    }    func updateUIView(_ view: ComposerTextView, context: Context) {        context.coordinator.parent = self        context.coordinator.apply(to: view, force: false)        // Focus is asked for here; putting the keyboard down is the frame's        // (the app's keyboard dismissal), never the composer's own.        if let focused, focused.wrappedValue, !view.isFirstResponder, view.window != nil {            DispatchQueue.main.async { view.becomeFirstResponder() }        }    }    func sizeThatFits(_ proposal: ProposedViewSize, uiView view: ComposerTextView, context: Context) -> CGSize? {        let width = proposal.width ?? view.bounds.width        guard width > 0, width.isFinite else { return nil }        let content = view.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height        let line = (view.font ?? Self.uiFont(face)).lineHeight        let inset = Self.inset.top + Self.inset.bottom        // At the largest text sizes seven lines would fill the screen: the area        // stops at a third of it and scrolls. With the keyboard up, a third of        // what the keyboard leaves, so what is being answered stays in sight        // above the box (owner, Comms build 19: at the largest text five lines        // and the keyboard left no room for the conversation).        let screen = view.window?.windowScene?.screen.bounds.height ?? 800        let keyboard = ComposerKeyboard.shared.height(over: screen)        // What stands over the field inside the box takes its room from the field first: at the largest text an edit's        // strip and where the message goes left the box's own Send under the keyboard.        let room = screen - keyboard        let height = ComposerRules.height(content: content, line: line, inset: inset, cap: min(room / 3, room * 0.4 - reserved))        return CGSize(width: width, height: height)    }    static func uiFont(_ face: ComposerFace) -> UIFont {        let base = face.name.flatMap { UIFont(name: $0, size: face.size) } ?? .systemFont(ofSize: face.size)        return UIFontMetrics(forTextStyle: face.textStyle.uiKit).scaledFont(for: base)    }    @MainActor    final class Coordinator: NSObject, UITextViewDelegate {        var parent: ComposerTextArea        /// While the composer writes the view, the delegate's echoes are its own.        private var writing = false        private var lastTentative: NSRange?        private var lastFace: ComposerFace?        init(_ parent: ComposerTextArea) { self.parent = parent }        func apply(to view: ComposerTextView, force: Bool) {            if force || lastFace != parent.face {                view.font = ComposerTextArea.uiFont(parent.face)                lastFace = parent.face            }            view.textColor = UIColor(parent.ink)            view.tintColor = UIColor(parent.ink)            view.returnKeyType = parent.returnSends ? .send : .default            view.accessibilityLabel = parent.label            view.accessibilityIdentifier = parent.identifier            let textChanged = view.text != parent.text            let tentativeChanged = lastTentative != parent.tentative            // Never rewrite the view under a half-composed (marked) word.            guard force || ((textChanged || tentativeChanged) && view.markedTextRange == nil) else { return }            writing = true            defer { writing = false }            let keep = view.selectedRange            let atEnd = keep.location >= (view.text as NSString).length            view.attributedText = attributed(parent.text, font: view.font ?? ComposerTextArea.uiFont(parent.face))            lastTentative = parent.tentative            let length = (parent.text as NSString).length            if let caret = parent.caret {                view.selectedRange = NSRange(location: min(max(caret, 0), length), length: 0)            } else if textChanged {                view.selectedRange = atEnd ? NSRange(location: length, length: 0) : NSRange(location: min(keep.location, length), length: 0)            } else {                view.selectedRange = NSRange(location: min(keep.location, length), length: min(keep.length, max(0, length - keep.location)))            }            view.invalidateIntrinsicContentSize()            follow(view)        }        private func attributed(_ text: String, font: UIFont) -> NSAttributedString {            let out = NSMutableAttributedString(string: text, attributes: [.font: font, .foregroundColor: UIColor(parent.ink)])            if let faint = parent.tentative, NSMaxRange(faint) <= out.length, faint.length > 0 {                out.addAttribute(.foregroundColor, value: UIColor(parent.faint), range: faint)            }            return out        }        /// The newest words stay in view: the caret's line is scrolled to.        private func follow(_ view: UITextView) {            DispatchQueue.main.async {                view.layoutIfNeeded()                view.scrollRangeToVisible(view.selectedRange)            }        }        func textViewDidChange(_ view: UITextView) {            guard !writing else { return }            if view.markedTextRange != nil { return }            let now = view.text ?? ""            parent.text = now            parent.edited(now)            view.invalidateIntrinsicContentSize()            follow(view)        }        func textViewDidChangeSelection(_ view: UITextView) {            guard !writing else { return }            parent.selected(view.selectedRange)        }        func textViewDidBeginEditing(_ view: UITextView) {            if parent.focused?.wrappedValue == false { parent.focused?.wrappedValue = true }        }        func textViewDidEndEditing(_ view: UITextView) {            if parent.focused?.wrappedValue == true { parent.focused?.wrappedValue = false }        }        func textView(_ view: UITextView, shouldChangeTextIn range: NSRange, replacementText words: String) -> Bool {            // The on-screen keyboard's Return: sends when the app says so.            guard words == "\n", parent.returnSends, !breaking else { return true }            parent.send()            return false        }        /// Shift-Return's line break is written even where Return sends.        private var breaking = false        func key(_ key: ComposerTextView.Key, in view: UITextView) {            switch key {            case .send: parent.send()            case .newLine:                breaking = true                view.insertText("\n")                breaking = false            }        }    }}/// The text view, with the hardware keyboard's two Returns that are not the/// plain one.final class ComposerTextView: UITextView {    enum Key { case send, newLine }    var onKey: (@MainActor (Key) -> Void)?    override var keyCommands: [UIKeyCommand]? {        let send = UIKeyCommand(input: "\r", modifierFlags: .command, action: #selector(sendKey))        let line = UIKeyCommand(input: "\r", modifierFlags: .shift, action: #selector(newLineKey))        send.wantsPriorityOverSystemBehavior = true        line.wantsPriorityOverSystemBehavior = true        return (super.keyCommands ?? []) + [send, line]    }    @objc private func sendKey() { onKey?(.send) }    @objc private func newLineKey() { onKey?(.newLine) }}extension Font.TextStyle {    var uiKit: UIFont.TextStyle {        switch self {        case .largeTitle: .largeTitle        case .title: .title1        case .title2: .title2        case .title3: .title3        case .headline: .headline        case .subheadline: .subheadline        case .callout: .callout        case .footnote: .footnote        case .caption: .caption1        case .caption2: .caption2        default: .body        }    }}#endif