Cotton code
238 lines · 10.7 KB · SwiftRaw
// ADDING (pen.html "Adding"): one line above the keyboard, typed or spoken.// As the words come the book reads the day and time from them// (`days.read_line`) and shows them as a pill to correct; the few marks// whose words match are offered, tap one or ignore them; send adds it// (`days.add`) and the line is clear for the next. As Android's `AddBar.kt`.#if os(iOS)import CottonKitimport CottonVoiceimport SwiftUI@MainActor @Observablefinal class DaysAdding {    var words = ""    var understood = DaysReadLine.empty    var mark: String?    /// The day and time the person set on the pill (When); `nil`, as the words said them.    var picked: DaysPillPick?    var sending = false    @ObservationIgnored let dictation: ComposerVoice?    init(core: (any CottonCalling)?) {        dictation = core.map { core in            ComposerVoice(core: core) { VoicePlanRequest(surface: "days.add", table: "todo", column: "title", mode: .dictate) }        }    }    var listening: Bool {        switch dictation?.phase {        case .listening?, .preparing?, .settling?: true        default: false        }    }}/// What the person set on the pill: a day (nil: no day, a to-do for Sometime) and a time (nil: no time).struct DaysPillPick: Equatable, Sendable {    var day: String?    var time: String?    /// The words to send once the pill is corrected: a day or time set to none    /// drops the words that said it (the `said` stretches), so the core reads    /// none (`days.add` takes a day or time to put in, never one to take out).    static func words(_ words: String, read: DaysReadLine, pick: DaysPillPick?) -> String {        guard let pick else { return words }        let drop = read.said.filter { ($0.what == "day" && pick.day == nil) || ($0.what == "time" && pick.time == nil) }        // The core counts characters as Unicode scalars (Rust's `chars`).        var out = Array(words.unicodeScalars)        for s in drop.sorted(by: { $0.from > $1.from }) where s.from >= 0 && s.from <= s.to && s.to <= out.count {            out.removeSubrange(s.from..<s.to)        }        var kept = String.UnicodeScalarView()        kept.append(contentsOf: out)        return String(kept).replacingOccurrences(of: #"\s+"#, with: " ", options: .regularExpression).trimmingCharacters(in: .whitespaces)    }    /// A typed clock as the contract writes it: 24-hour, no leading zero (9:00, 19:00); nil when it is not one.    static func clock(_ typed: String) -> String? {        guard typed.range(of: #"^([01]?\d|2[0-3]):[0-5]\d$"#, options: .regularExpression) != nil else { return nil }        let parts = typed.split(separator: ":")        return "\(Int(parts[0]) ?? 0):\(parts[1])"    }}struct DaysAddBar: View {    @Bindable var model: DaysModel    @Bindable var adding: DaysAdding    @FocusState private var focused: Bool    private var whereFrom: String { model.place == .days ? "days" : "sometime" }    var body: some View {        VStack(alignment: .leading, spacing: 12) {            HStack(alignment: .top, spacing: 8) {                TextField("", text: shownWords, prompt: Text(DaysWords.line("add.hint")).foregroundColor(Pen.faint), axis: .vertical)                    .font(PenType.words)                    .foregroundStyle(Pen.ink)                    .tint(Pen.pen)                    .lineLimit(1...4)                    .focused($focused)                    .submitLabel(.send)                    .onChange(of: adding.words) { _, now in                        if now.hasSuffix("\n") {                            adding.words = String(now.dropLast())                            send()                        }                    }                    .accessibilityLabel(DaysWords.line("add.hint"))                Button { model.adding = false } label: {                    Image(systemName: "xmark")                        .font(.system(size: 13, weight: .regular))                        .foregroundStyle(Pen.quiet)                        .frame(width: 30, height: 30)                        .contentShape(Rectangle())                }                .buttonStyle(PenPress())                .accessibilityLabel(DaysWords.line("add.close"))            }            let offered = adding.understood.marks.filter(DrawnMark.drawn)            if !offered.isEmpty {                DaysMarksRow(ids: offered, chosen: $adding.mark)            }            HStack(spacing: 10) {                if let pill = pillWords {                    PenChip(words: pill, on: true, name: DaysWords.line("add.pill_name", ["words": pill])) {                        focused = false                        let now = adding.picked ?? DaysPillPick(day: adding.understood.day, time: adding.understood.time)                        model.sheet = .when(now) { [adding] pick in adding.picked = pick }                    }                }                Spacer(minLength: 4)                if let dictation = adding.dictation { mic(dictation) }                Button(action: send) {                    Image(systemName: "arrow.up")                        .font(.system(size: 15, weight: .regular))                        .foregroundStyle(Pen.onPen)                        .frame(width: 34, height: 34)                        .background(Circle().fill(canSend ? Pen.pen : Pen.rule))                        .frame(width: 44, height: 44)                        .contentShape(Circle())                }                .buttonStyle(PenPress())                .disabled(!canSend)                .accessibilityLabel(DaysWords.line("add.send"))            }        }        .padding(.vertical, 12)        .padding(.horizontal, 14)        .background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(Pen.sheet))        .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(Pen.ink, lineWidth: Pen.stroke))        // A tap on the bar (its words, marks, mic, Add) keeps the keyboard up for the next line.        .keyboardStaysOnTap()        .padding(.horizontal, Pen.side)        .padding(.top, 8)        .padding(.bottom, 12)        .onAppear { focused = true }        .task(id: "\(adding.words)|\(whereFrom)|\(model.dayInView ?? "")") { await read() }    }    /// While the microphone listens, its live words stand in the field.    private var shownWords: Binding<String> {        Binding(get: { adding.listening ? (adding.dictation?.shown ?? adding.words) : adding.words },                set: { adding.words = $0; if adding.listening { adding.dictation?.fieldChanged($0) } })    }    private var canSend: Bool { !adding.words.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !adding.sending }    private var pillWords: String? {        guard let picked = adding.picked else {            if let pill = adding.understood.pill { return pill }            return adding.words.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : DaysWords.line("add.no_day")        }        let d = picked.day.map(model.clock.calendar.short) ?? DaysWords.line("add.no_day")        if let time = picked.time { return DaysWords.line("add.pill", ["day": d, "time": time]) }        return DaysWords.line("add.pill_day", ["day": d])    }    private func read() async {        let words = adding.words        try? await Task.sleep(for: .milliseconds(120))        guard !Task.isCancelled else { return }        if words.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {            adding.understood = .empty        } else {            do { adding.understood = try await model.book.readLine(words, where: whereFrom, dayInView: model.dayInView) } catch {                model.tell((error as? DaysRefused)?.message ?? ActionRefused.words(for: error))            }        }        if let mark = adding.mark, !adding.understood.marks.contains(mark) { adding.mark = nil }    }    private func send() {        guard canSend else { return }        adding.sending = true        let words = adding.words        Task {            if adding.listening, let dictation = adding.dictation { _ = await dictation.stop() }            await model.attempt {                let pick = adding.picked                // No day set by hand: the core's Sometime ("where" sometime), as adding from Sometime does.                let place = model.place == .sometime || (pick != nil && pick?.day == nil) ? "sometime" : "days"                let added = try await model.book.add(DaysPillPick.words(words, read: adding.understood, pick: pick), where: place,                                                   dayInView: model.dayInView, day: pick.map { $0.day }, time: pick?.time, mark: adding.mark,                                                   group: model.group?.id)                adding.words = ""                adding.mark = nil                adding.picked = nil                adding.understood = .empty                await model.read()                if let day = added?.day, model.place == .days { model.jumpTo = day }            }            adding.sending = false        }    }    private func mic(_ dictation: ComposerVoice) -> some View {        Button {            Task {                if adding.listening {                    adding.words = await dictation.stop()                } else {                    // Before the phone is asked, and after it refused, a card says why first (DaysRoot).                    await dictation.start(text: adding.words, selection: nil)                    if dictation.ask == nil, let refusal = dictation.refusal { model.tell(refusal) }                }            }        } label: {            Image(systemName: adding.listening ? "mic.fill" : "mic")                .font(.system(size: 18, weight: .light))                .foregroundStyle(adding.listening ? Pen.pen : Pen.ink)                .frame(width: 44, height: 44)                .contentShape(Rectangle())        }        .buttonStyle(PenPress())        .accessibilityLabel(DaysWords.line("add.dictate"))    }}/// A drawn mark offered (`.pick`): 38 pt, a rule-coloured outline, pen-soft once chosen.struct DaysMarkPick: View {    let id: String    let on: Bool    let tap: () -> Void    var body: some View {        Button(action: tap) {            DrawnMark(id: id, size: 26)                .frame(width: 38, height: 38)                .background(RoundedRectangle(cornerRadius: 10).fill(on ? Pen.penSoft : Color.clear))                .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(on ? Pen.pen : Pen.rule, lineWidth: Pen.stroke))                .contentShape(RoundedRectangle(cornerRadius: 10))        }        .buttonStyle(PenPress())        .accessibilityLabel(DaysWords.line("add.mark_name", ["mark": DrawnMark.name(id)]))        .accessibilityAddTraits(on ? .isSelected : [])    }}#endif