Cotton code
165 lines · 6.9 KB · SwiftRaw
// A text field dictated into: the words go in at the cursor, between the text// before it and the text after it, and the field shows the session's region// there as it changes — the core's settled words, then the tentative ones.//// The person may keep typing while the microphone is open. Anything outside// the region is theirs and is never touched; anything inside it is read back// as the region's new text and handed to the session, which tells the core// the range they touched (`voice.touched`) so the second pass leaves it alone.//// Offsets are UTF-16 throughout, the unit UIKit's selection reports.import CottonKitimport CottonVoiceimport Foundationimport Observation@MainActor@Observablepublic final class VoiceField {    public let session: VoiceSession    /// The field's text before and after the region, fixed when it began.    private var before = ""    private var after = ""    /// What this field last wrote into the host, so the host's echo of it is    /// not mistaken for the person typing.    private var written: String?    private(set) var anchored = false    /// Whether the tentative words are written into the field (a field that    /// draws them lighter itself) or left to the strip over the bar.    public let inlineTentative: Bool    public init(session: VoiceSession, inlineTentative: Bool) {        self.session = session        self.inlineTentative = inlineTentative    }    /// The region as this field shows it.    private var shownRegion: String {        inlineTentative ? session.region.display : session.region.settled    }    public var isActive: Bool { session.isActive }    /// Tap: anchor at the cursor (`selection`, UTF-16; nil means the end) and    /// start the session.    public func start(text: String, selection: NSRange?, request: VoicePlanRequest) async {        let units = text.utf16.count        let range = selection.map { NSRange(location: min(max($0.location, 0), units), length: max(0, min($0.length, units - min(max($0.location, 0), units)))) }            ?? NSRange(location: units, length: 0)        let ns = text as NSString        before = ns.substring(to: range.location)        after = ns.substring(from: range.location + range.length)        // A space between the words before and the dictated ones, as typing        // would leave it; none at the start of a line.        if let last = before.last, !last.isWhitespace, !before.isEmpty { before += " " }        anchored = true        written = nil        await session.start(request)        if !session.isActive { anchored = false }    }    /// The text the field should show now, or nil when nothing is dictated.    public var text: String? {        guard anchored else { return nil }        _ = session.revision        return before + shownRegion + after    }    /// Where the tentative words sit in ``text`` (UTF-16), to draw lighter.    public var tentativeRange: NSRange? {        guard anchored, inlineTentative, !session.region.tentative.isEmpty else { return nil }        let range = session.region.tentativeRange        return NSRange(location: before.utf16.count + range.location, length: range.length)    }    /// Where a second pass just corrected settled words, in ``text``.    public var correctedRanges: [NSRange] {        guard anchored else { return [] }        let offset = before.utf16.count        return session.region.corrected.map { NSRange(location: $0.location + offset, length: $0.length) }    }    /// The caret's place just after the dictated words.    public var caret: Int { before.utf16.count + shownRegion.utf16.count }    /// The host wrote ``text`` into its field.    public func didWrite(_ text: String) { written = text }    /// The field changed. When it was the person, read the region back.    public func fieldChanged(_ text: String) {        guard anchored, session.isActive, text != written else { return }        // The person's words before and after are kept as they now are: the        // region is what lies between the two ends that did not move.        let units = Array(text.utf16)        let head = before.utf16.count        let tail = after.utf16.count        guard units.count >= head + tail else { return }        let headNow = String(utf16CodeUnits: Array(units[0 ..< head]), count: head)        let tailNow = String(utf16CodeUnits: Array(units[(units.count - tail)...]), count: tail)        guard headNow == before, tailNow == after else {            // The person typed outside the region (before it, moving it): the            // anchor follows what they typed.            let shown = before + shownRegion + after            adjustAnchor(old: shown, new: text)            return        }        let middle = String(utf16CodeUnits: Array(units[head ..< (units.count - tail)]), count: units.count - tail - head)        // A field without the tentative words typed against the settled ones:        // the region as the session knows it still ends with them.        session.typed(inlineTentative ? middle : middle + session.region.tentative)        written = text    }    /// The selection moved inside the region: tell the session.    public func selectionChanged(_ range: NSRange) {        guard anchored, session.isActive, range.length > 0 else { return }        let head = before.utf16.count        let from = range.location - head        let to = from + range.length        guard to > 0, from < shownRegion.utf16.count else { return }        session.selected(from: max(0, from), to: to)    }    /// Tap again: everything settles; answers the field's whole text.    public func stop() async -> String {        let region = await session.stop()        defer { anchored = false; written = nil }        return before + region + after    }    /// Discard: the field goes back to what it was, less the dictation.    public func cancel() -> String {        session.cancel()        anchored = false        return before.trimmingTrailingSpace + after    }    private func adjustAnchor(old: String, new: String) {        let a = Array(old.utf16)        let b = Array(new.utf16)        var prefix = 0        while prefix < min(a.count, b.count), a[prefix] == b[prefix] { prefix += 1 }        let head = before.utf16.count        if prefix < head {            // Typed before the region: the region moves with it.            let delta = b.count - a.count            let newHead = head + delta            guard newHead >= 0, newHead <= b.count else { return }            before = String(utf16CodeUnits: Array(b[0 ..< newHead]), count: newHead)        } else {            // Typed after it.            let tail = b.count - (head + shownRegion.utf16.count)            guard tail >= 0 else { return }            after = String(utf16CodeUnits: Array(b[(b.count - tail)...]), count: tail)        }        written = new    }}private extension String {    var trimmingTrailingSpace: String {        hasSuffix(" ") ? String(dropLast()) : self    }}