Cotton code
172 lines · 7.6 KB · SwiftRaw
// 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.import CottonKitimport Foundation@MainActor@Observablepublic final class BodyDictation {    /// Where the dictated span goes: the text either side of the cursor, taken    /// when the session started.    private struct Anchor {        let before: String        let after: String    }    private let dictation: DictationModel    private let haptics: any Haptics    /// Read the CURRENT body — a getter, never a value captured at a render.    private let body: @MainActor () -> String    private let setBody: @MainActor (String) -> Void    /// Every ending, named — the host speaks the sentence    /// (`VoiceTake.dictationMessage`).    private let 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.    public private(set) var selectionStart = -1    public private(set) var selectionEnd = -1    private var anchor: Anchor?    /// Dictation owns the field.    public var isActive: Bool { dictation.isLive }    public var isFinishing: Bool { dictation.isFinishing }    /// What the body input must DISPLAY right now: the live splice while    /// dictating, or `nil` to render the real body.    public var displayBody: String? {        guard isActive else { return nil }        return VoiceTake.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.    public init(        dictation: DictationModel,        haptics: any Haptics,        body: @escaping @MainActor () -> String,        setBody: @escaping @MainActor (String) -> Void,        onEnded: @escaping @MainActor (DictationOutcome) -> Void    ) {        self.dictation = dictation        self.haptics = haptics        self.body = body        self.setBody = setBody        self.onEnded = onEnded        dictation.onUnasked = { [weak self] result in self?.land(result) }    }    // ── The cursor ────────────────────────────────────────────────────────    /// Track the cursor so ``start(hints:)`` knows where the words go.    public func 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.    @discardableResult    public func 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)        if let refusal {            anchor = nil            onEnded(refusal)        }        return refusal    }    /// Tap ✓.    public func 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.    public func 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).    private func land(_ result: DictationResult) {        let anchor = self.anchor        self.anchor = nil        if let 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.    private static func anchor(in text: String, start: Int, end: Int) -> Anchor {        let length = text.utf16.count        let from = start < 0 ? length : min(max(start, 0), length)        let to = min(max(end < 0 ? length : end, from), length)        guard            let 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.            return Anchor(before: text, after: "")        }        return Anchor(before: String(text[..<left]), after: String(text[right...]))    }}