// 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.importCottonKitimportCottonVoiceimportFoundationimportObservation@MainActor@ObservablepublicfinalclassVoiceField {publiclet session: VoiceSession/// The field's text before and after the region, fixed when it began.privatevar before = ""privatevar after = ""/// What this field last wrote into the host, so the host's echo of it is/// not mistaken for the person typing.privatevar 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.publiclet inlineTentative: Boolpublicinit(session: VoiceSession, inlineTentative: Bool) {self.session = sessionself.inlineTentative = inlineTentative }/// The region as this field shows it.privatevar shownRegion: String { inlineTentative ? session.region.display : session.region.settled }publicvar isActive: Bool { session.isActive }/// Tap: anchor at the cursor (`selection`, UTF-16; nil means the end) and/// start the session.publicfunc start(text: String, selection: NSRange?, request: VoicePlanRequest) async {let units = text.utf16.countlet 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.iflet last = before.last, !last.isWhitespace, !before.isEmpty { before += " " } anchored = true written = nilawait session.start(request)if !session.isActive { anchored = false } }/// The text the field should show now, or nil when nothing is dictated.publicvar text: String? {guard anchored else { returnnil } _ = session.revisionreturn before + shownRegion + after }/// Where the tentative words sit in ``text`` (UTF-16), to draw lighter.publicvar tentativeRange: NSRange? {guard anchored, inlineTentative, !session.region.tentative.isEmpty else { returnnil }let range = session.region.tentativeRangereturn NSRange(location: before.utf16.count + range.location, length: range.length) }/// Where a second pass just corrected settled words, in ``text``.publicvar correctedRanges: [NSRange] {guard anchored else { return [] }let offset = before.utf16.countreturn session.region.corrected.map { NSRange(location: $0.location + offset, length: $0.length) } }/// The caret's place just after the dictated words.publicvar caret: Int { before.utf16.count + shownRegion.utf16.count }/// The host wrote ``text`` into its field.publicfunc didWrite(_ text: String) { written = text }/// The field changed. When it was the person, read the region back.publicfunc 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.countlet tail = after.utf16.countguard 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.publicfunc selectionChanged(_ range: NSRange) {guard anchored, session.isActive, range.length > 0else { return }let head = before.utf16.countlet from = range.location - headlet to = from + range.lengthguard 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.publicfunc 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.publicfunc cancel() -> String { session.cancel() anchored = falsereturn before.trimmingTrailingSpace + after }privatefunc adjustAnchor(old: String, new: String) {let a = Array(old.utf16)let b = Array(new.utf16)var prefix = 0while prefix < min(a.count, b.count), a[prefix] == b[prefix] { prefix += 1 }let head = before.utf16.countif prefix < head {// Typed before the region: the region moves with it.let delta = b.count - a.countlet newHead = head + deltaguard 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 >= 0else { return } after = String(utf16CodeUnits: Array(b[(b.count - tail)...]), count: tail) } written = new }}privateextensionString {var trimmingTrailingSpace: String { hasSuffix(" ") ? String(dropLast()) : self }}