// Dictation into the note editor's body, at the cursor.//// **This is 4d's COMPONENT and 4e's SCREEN.** The note editor itself — the// field, the mic button, the toolbar, the autosave — is 4e's; what lives here is// the part that has nothing to do with how a note is drawn: where a dictated// span goes, when the body is written, and which ending is named. The seam is// named on purpose so the screen lane does not re-derive it and so this file// does not grow a view.//// The composer streams into its OWN field, so it folds// (`VoiceTake.foldDictationSegment`); here the stream is SPLICED into an// existing text at the last-known cursor (`VoiceTake.spliceDictation`, which// never trims the writer's surroundings — a paragraph break before the cursor is// theirs). Three rules carry across from the phone://// • **The body is written only on FINISH.** Partials render from// ``displayBody``, so the autosave never churns on half-sentences.// • **``land(_:)`` is the ONE path** for a finish the person tapped and for an// interruption the microphone suffered. The words land either way; iOS's own// dictation keeps what it heard and so does this.// • **The span lands VERBATIM.** What the recogniser said is what the body// gets; nothing rewrites it on the way in.//// ONE DELIBERATE DIFFERENCE FROM THE TYPESCRIPT: the cursor arrives as UTF-16// offsets, because that is what UIKit reports and what the phone's `number`// offsets were. They are converted to `String.Index` once, HERE, and clamped —// a stale offset from before a programmatic edit is a real event, and it must// splice at the end rather than trap.importCottonKitimportFoundation@MainActor@ObservablepublicfinalclassBodyDictation {/// Where the dictated span goes: the text either side of the cursor, taken/// when the session started.privatestructAnchor {let before: Stringlet after: String }privatelet dictation: DictationModelprivatelet haptics: any Haptics/// Read the CURRENT body — a getter, never a value captured at a render.privatelet body: @MainActor () -> Stringprivatelet setBody: @MainActor (String) -> Void/// Every ending, named — the host speaks the sentence/// (`VoiceTake.dictationMessage`).privatelet onEnded: @MainActor (DictationOutcome) -> Void/// The last cursor the field reported, in UTF-16 offsets. `-1` means the/// field has never been focused, and the words go on the end.publicprivate(set) var selectionStart = -1publicprivate(set) var selectionEnd = -1privatevar anchor: Anchor?/// Dictation owns the field.publicvar isActive: Bool { dictation.isLive }publicvar isFinishing: Bool { dictation.isFinishing }/// What the body input must DISPLAY right now: the live splice while/// dictating, or `nil` to render the real body.publicvar displayBody: String? {guard isActive else { returnnil }returnVoiceTake.spliceDictation( before: anchor?.before ?? body(), dictation.liveText, after: anchor?.after ?? "" ) }/// **This takes ownership of the model's unasked-ending channel.** One host/// per `DictationModel`: the interruption has exactly one place to land, and/// a second assignment would silently take the words away from the first.publicinit( dictation: DictationModel, haptics: any Haptics, body: @escaping @MainActor () -> String, setBody: @escaping @MainActor (String) -> Void, onEnded: @escaping @MainActor (DictationOutcome) -> Void ) {self.dictation = dictationself.haptics = hapticsself.body = bodyself.setBody = setBodyself.onEnded = onEnded dictation.onUnasked = { [weakself] result inself?.land(result) } }// ── The cursor ────────────────────────────────────────────────────────/// Track the cursor so ``start(hints:)`` knows where the words go.publicfunc selectionChanged(start: Int, end: Int) { selectionStart = start selectionEnd = end }// ── The three things a person does ────────────────────────────────────/// Tap the mic. Answers the ending that happened INSTEAD, when there is one/// — the caller has already been told through ``onEnded`` either way. @discardableResultpublicfunc start(hints: DictationHints) async -> DictationOutcome? {let text = body() anchor = BodyDictation.anchor(in: text, start: selectionStart, end: selectionEnd)// The body editor splices rather than folds, so dictation carries no// prefix of its own: `displayBody` puts the live text between the two// halves this anchor holds.let refusal = await dictation.start(prefix: "", hints: hints)iflet refusal { anchor = nil onEnded(refusal) }return refusal }/// Tap ✓.publicfunc finish() async { land(await dictation.finish()) }/// Tap ✕. The body is untouched — a discard is the one ending that keeps no/// words, and it owes no sentence.publicfunc cancel() { anchor = nil dictation.cancel() onEnded(.dictationCancelled) }// ── The one landing path ──────────────────────────────────────────────/// Splice a finished dictation into the body and name its ending — the ONE/// path for a finish the person tapped and for an interruption the/// microphone suffered (a call, Siri, an alarm).privatefunc land(_ result: DictationResult) {let anchor = self.anchorself.anchor = niliflet anchor, !result.text.isEmpty {let merged = VoiceTake.spliceDictation( before: anchor.before, result.text, after: anchor.after) setBody(merged) haptics.success() } onEnded(result.outcome) }// ── Pure ──────────────────────────────────────────────────────────────/// The two halves a dictated span goes between.////// A negative start means the field was never focused — the words go on the/// end, which is what typing would have done. Offsets past the text, or an/// end before its start, are clamped rather than trusted: a selection/// reported before a programmatic edit is stale by the time it is read.privatestaticfunc anchor(in text: String, start: Int, end: Int) -> Anchor {let length = text.utf16.countlet from = start < 0 ? length : min(max(start, 0), length)let to = min(max(end < 0 ? length : end, from), length)guardlet left = String.Index(String.Index(utf16Offset: from, in: text), within: text),let right = String.Index(String.Index(utf16Offset: to, in: text), within: text)else {// A cursor inside a grapheme cluster — an emoji's second half. The// whole text is the prefix rather than a string sliced through a// character.returnAnchor(before: text, after: "") }returnAnchor(before: String(text[..<left]), after: String(text[right...])) }}