Cotton code
428 lines · 16.7 KB · SwiftRaw
// An event's end and its people on the iPhone (assets/design/days CONTRACT §14, §15, §18 steps 1 to 3), drawn from// the core's answers in the pen look as Android's EndsRow, PeopleRow, PeoplePicker and TellLine do. Every word is the// core's: the row titles, the chips, what each person's answer says, what saving would tell them.import CottonKitimport Foundation#if os(iOS)import SwiftUI#endif// MARK: - The answers/// `days.item`'s `ends` on a timed event (§14): the end and length read back, and the five chips.struct DaysEnds: Equatable, Sendable {    struct Choice: Equatable, Sendable {        var key: String        var minutes: Int?        var label: String        var on: Bool    }    var title: String    var says: String    var choices: [Choice]    /// The chip that stands.    var standing: String? { choices.first(where: \.on)?.key }}/// How the event's end is changed (§14): a length after the start, No end, or a picked clock time.enum DaysLength: Equatable, Sendable {    case minutes(Int)    case none    var json: Any {        switch self {        case .minutes(let n): return n        case .none: return "none"        }    }}/// One person on an event (`people.rows`, §15), or one found to add (`days.people_find`).struct DaysPerson: Equatable, Identifiable, Sendable {    var key: String    var name: String    var detail: String?    var via: String?    var answerWords: String?    var organizer = false    var email: String?    var number: String?    var id: String { key }    /// As `days.change { people }` and `days.tell` take a chip.    var json: [String: Any] {        var out: [String: Any] = ["key": key, "name": name]        if let email { out["email"] = email }        if let number { out["number"] = number }        return out    }}/// `days.item`'s `people` on an event (§15).struct DaysPeople: Equatable, Sendable {    var title: String    var add: String    var canChange: Bool    var rows: [DaysPerson]    /// No way to tell someone yet: its line, and Connect (the section 13 connect) when it offers one.    var blocked: String?    #if os(iOS)    var connect: DaysGoogle.Connect?    #endif}/// `days.tell` (§15): what saving the chips as they stand would tell whom.struct DaysTold: Equatable, Sendable {    var lines: [String]    var blocked: String?}/// An invitation received (`days.item`'s `invitation`, §17): who sent it, and the three answers, the one standing.struct DaysInvitation: Equatable, Sendable {    struct Choice: Equatable, Sendable {        var key: String        var label: String    }    var says: String    var answer: String?    var choices: [Choice]}/// What `days.change` said back (§15, §16): a merged note's line, what the people were told, and whether/// something now waits to go to Google or to someone on Cotton.struct DaysChanged: Equatable, Sendable {    var said: String?    var tells: [String] = []    var waiting = false}/// What a send pass said (`days.send_to_google`, then `days.invitations`; §16, §17): lines for Days' foot, and the/// line with Connect when Google must be asked once more.struct DaysSent: Equatable, Sendable {    var said: [String] = []    var reconnect: String?    #if os(iOS)    var connect: DaysGoogle.Connect?    #endif}/// `google_needs_write` (§16): the grant cannot write, so the sheet stays with what was typed, the core's message,/// and Connect (its notice says why).struct DaysNeedsWrite: Equatable, Sendable {    var message: String    #if os(iOS)    var connect: DaysGoogle.Connect?    #endif    /// The refusal, when a save was refused for it; nil for any other.    static func of(_ error: Error) -> DaysNeedsWrite? {        guard let refused = error as? CottonCallError, refused.code == "google_needs_write" else { return nil }        var out = DaysNeedsWrite(message: refused.message)        #if os(iOS)        if case .object(let details)? = refused.details, let act = details["connect"],           let data = try? JSONEncoder().encode(act) {            out.connect = try? JSONDecoder().decode(DaysGoogle.Connect.self, from: data)        }        #endif        return out    }}extension DaysRead {    static func ends(_ x: Object?) -> DaysEnds? {        guard let x, let title = s(x, "title") else { return nil }        return DaysEnds(title: title, says: s(x, "says") ?? "",                        choices: objects(x, "choices").compactMap { c in                            s(c, "key").map { DaysEnds.Choice(key: $0, minutes: i(c, "minutes"), label: s(c, "label") ?? $0, on: b(c, "on")) }                        })    }    static func person(_ x: Object) -> DaysPerson? {        guard let key = s(x, "key") else { return nil }        return DaysPerson(key: key, name: s(x, "name") ?? key, detail: s(x, "detail"), via: s(x, "via"),                          answerWords: s(x, "answerWords"), organizer: b(x, "organizer"), email: s(x, "email"), number: s(x, "number"))    }    static func people(_ x: Object?) -> DaysPeople? {        guard let x, let title = s(x, "title") else { return nil }        let blocked = o(x, "blocked")        var people = DaysPeople(title: title, add: s(x, "add") ?? "", canChange: b(x, "canChange"),                                rows: objects(x, "rows").compactMap(person), blocked: blocked.flatMap { s($0, "line") })        #if os(iOS)        people.connect = blocked.flatMap { o($0, "connect") }.flatMap(decoded)        #endif        return people    }    static func invitation(_ x: Object?) -> DaysInvitation? {        guard let x, let says = s(x, "says") else { return nil }        return DaysInvitation(says: says, answer: s(x, "answer"),                              choices: objects(x, "choices").compactMap { c in s(c, "key").map { DaysInvitation.Choice(key: $0, label: s(c, "label") ?? $0) } })    }    static func changed(_ x: Object) -> DaysChanged {        DaysChanged(said: s(x, "said"), tells: strings(x, "tells"), waiting: s(x, "google") == "waiting")    }    static func sent(_ x: Object) -> DaysSent {        let reconnect = o(x, "reconnect")        var out = DaysSent(said: strings(x, "said"), reconnect: reconnect.flatMap { s($0, "line") })        #if os(iOS)        out.connect = reconnect.flatMap { o($0, "connect") }.flatMap(decoded)        #endif        return out    }    /// A part of an answer the shared reader already decodes (section 13's connect).    static func decoded<T: Decodable>(_ x: Object) -> T? {        guard let data = try? JSONSerialization.data(withJSONObject: x) else { return nil }        return try? JSONDecoder().decode(T.self, from: data)    }}extension DaysBook {    /// A book that does not find people (an invented one in a test) finds none and tells nothing.    func peopleFind(_ words: String, eventId: String?) async throws -> [DaysPerson] { [] }    func tell(eventId: String, people: [DaysPerson]) async throws -> DaysTold { DaysTold(lines: []) }    /// A book that says nothing back (an invented one) changes and answers that nothing waits.    func changed(table: String, id: String, occurrenceAt: String?, _ change: DaysChange) async throws -> DaysChanged {        try await self.change(table: table, id: id, occurrenceAt: occurrenceAt, change)        return DaysChanged()    }    /// A book with nothing to send (an invented one) sends nothing.    func send() async throws -> DaysSent { DaysSent() }    func answer(_ id: String, _ answer: String) async throws {}}#if os(iOS)// MARK: - ENDS, under TIME/// The ENDS row (§18 step 1): the title with the end and length read back quiet at its right, the five chips/// wrapping at large text; Pick a time opens a field for the clock time.struct DaysEndsRow: View {    let ends: DaysEnds    @Binding var chosen: String?    @Binding var picked: String    var body: some View {        VStack(alignment: .leading, spacing: 0) {            HStack(alignment: .firstTextBaseline) {                PenFieldLabel(words: ends.title)                Spacer(minLength: 12)                Text(ends.says).font(PenType.small).foregroundStyle(Pen.quiet).multilineTextAlignment(.trailing)                    .accessibilityIdentifier("days-ends-says")            }            PenFlow(spacing: 8, lineSpacing: 8) {                ForEach(ends.choices, id: \.key) { choice in                    PenChip(words: choice.label, on: chosen == choice.key) { chosen = choice.key }                        .accessibilityIdentifier("days-ends-\(choice.key)")                }            }            if chosen == "pick" {                TextField("", text: $picked)                    .font(PenType.words).foregroundStyle(Pen.ink).tint(Pen.pen)                    .keyboardType(.numbersAndPunctuation)                    .frame(minHeight: 44)                    .padding(.top, 6)                    .onChange(of: picked) { _, now in                        let kept = String(now.filter { $0.isNumber || $0 == ":" }.prefix(5))                        if kept != now { picked = kept }                    }                    .accessibilityLabel(ends.title)                    .accessibilityIdentifier("days-ends-time")                DottedRule()            }        }    }    /// What Save sends for the row, or nil when nothing changed: a length, No end, or the picked time as `end`.    static func change(_ ends: DaysEnds, chosen: String?, picked: String, end: String?) -> (length: DaysLength?, end: String?) {        guard let chosen else { return (nil, nil) }        if chosen == "pick" {            guard picked.range(of: #"^\d{1,2}:\d{2}$"#, options: .regularExpression) != nil, picked != end else { return (nil, nil) }            return (nil, picked)        }        guard chosen != ends.standing else { return (nil, nil) }        if chosen == "none" { return (DaysLength.none, nil) }        guard let minutes = ends.choices.first(where: { $0.key == chosen })?.minutes else { return (nil, nil) }        return (.minutes(minutes), nil)    }}// MARK: - PEOPLE, under ENDS/// The PEOPLE row (§18 step 2): each person a small capsule with their name and answer; a tap takes one off (never/// the organizer); Add people opens the picker in this same sheet. The blocked line and Connect under the chips.struct DaysPeopleRow: View {    let people: DaysPeople    @Binding var chips: [DaysPerson]    let onAdd: () -> Void    let onConnect: (DaysGoogle.Connect) -> Void    var body: some View {        VStack(alignment: .leading, spacing: 0) {            PenFieldLabel(words: people.title)            PenFlow(spacing: 8, lineSpacing: 8) {                ForEach(chips) { person in                    DaysPersonChip(person: person) {                        guard people.canChange, !person.organizer else { return }                        chips.removeAll { $0.key == person.key }                    }                }                if people.canChange && !people.add.isEmpty {                    PenChip(words: people.add, tap: onAdd).accessibilityIdentifier("days-people-add")                }            }            if let blocked = people.blocked {                Text(blocked).font(PenType.small).foregroundStyle(Pen.quiet).padding(.top, 8)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("days-people-blocked")                if let connect = people.connect {                    PenChip(words: connect.label) { onConnect(connect) }.padding(.top, 6)                }            }        }    }}/// One person: the name, and their answer small beside it.struct DaysPersonChip: View {    let person: DaysPerson    let tap: () -> Void    var body: some View {        Button(action: tap) {            HStack(spacing: 6) {                Text(person.name).font(PenType.chip).foregroundStyle(Pen.ink)                if let answer = person.answerWords {                    Text(answer).font(PenType.small).foregroundStyle(Pen.quiet)                }            }            .padding(.horizontal, 11)            .padding(.vertical, 5)            .frame(minHeight: 32)            .overlay(Capsule().strokeBorder(Pen.ink, lineWidth: Pen.stroke))            .contentShape(Capsule())        }        .buttonStyle(PenPress())        .accessibilityLabel([person.name, person.answerWords].compactMap { $0 }.joined(separator: ", "))        .accessibilityIdentifier("days-person-\(person.key)")    }}/// Add people (§18 step 2), in the same sheet: a field, and the core's matches as the person types; a pick adds a chip.struct DaysPeoplePicker: View {    let model: DaysModel    let people: DaysPeople    let eventId: String    let have: [DaysPerson]    let onPick: (DaysPerson) -> Void    /// Close: back to the event in the same sheet (no navigation, so no bar back).    let onDone: () -> Void    @State private var words = ""    @State private var found: [DaysPerson] = []    @FocusState private var typing: Bool    var body: some View {        VStack(alignment: .leading, spacing: 0) {            PenFieldLabel(words: people.add)            TextField("", text: $words)                .font(PenType.words).foregroundStyle(Pen.ink).tint(Pen.pen)                .textInputAutocapitalization(.never)                .autocorrectionDisabled()                .keyboardType(.emailAddress)                .focused($typing)                .frame(minHeight: 44)                .accessibilityLabel(people.add)                .accessibilityIdentifier("days-people-field")            DottedRule()            ForEach(found.filter { one in !have.contains { $0.key == one.key } }) { person in                Button { onPick(person) } label: {                    VStack(alignment: .leading, spacing: 2) {                        Text(person.name).font(PenType.words).foregroundStyle(Pen.ink)                        if let detail = person.detail, detail != person.name {                            Text(detail).font(PenType.small).foregroundStyle(Pen.quiet)                        }                    }                    .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)                    .contentShape(Rectangle())                }                .buttonStyle(PenPress())                .accessibilityIdentifier("days-people-found-\(person.key)")                DottedRule()            }            PenButton(words: DaysWords.line("add.close")) { onDone() }.padding(.top, 16)        }        .padding(.top, 14)        .onAppear { typing = true }        .task(id: words) {            try? await Task.sleep(for: .milliseconds(words.isEmpty ? 0 : 180))            guard !Task.isCancelled else { return }            found = (try? await model.book.peopleFind(words, eventId: eventId)) ?? []        }    }}/// An invitation received (§18 step 5): the three answers as capsules, the one standing filled.struct DaysInvitationRow: View {    let invitation: DaysInvitation    let standing: String?    let onAnswer: (String) -> Void    var body: some View {        PenFlow(spacing: 8, lineSpacing: 8) {            ForEach(invitation.choices, id: \.key) { choice in                PenChip(words: choice.label, on: choice.key == standing) { onAnswer(choice.key) }                    .accessibilityIdentifier("days-change-answer-\(choice.key)")            }        }        .padding(.top, 14)    }}/// Google refused to write with this grant (§18 step 4): the core's message in ink, and Connect, which opens the/// section 13 notice over the sheet.struct DaysNeedsWriteLine: View {    let refused: DaysNeedsWrite    let onConnect: (DaysGoogle.Connect) -> Void    var body: some View {        VStack(alignment: .leading, spacing: 0) {            Text(refused.message).font(PenType.small).foregroundStyle(Pen.ink)                .fixedSize(horizontal: false, vertical: true)                .accessibilityIdentifier("days-change-needs-write")            if let connect = refused.connect {                PenChip(words: connect.label) { onConnect(connect) }                    .padding(.top, 8)                    .accessibilityIdentifier("days-change-connect")            }        }        .padding(.top, 18)    }}/// What saving would tell (§18 step 3), quiet, above Save.struct DaysTellLines: View {    let told: DaysTold    var body: some View {        VStack(alignment: .leading, spacing: 4) {            ForEach(told.lines, id: \.self) { line in                Text(line).font(PenType.small).foregroundStyle(Pen.quiet).fixedSize(horizontal: false, vertical: true)            }            if let blocked = told.blocked {                Text(blocked).font(PenType.small).foregroundStyle(Pen.quiet).fixedSize(horizontal: false, vertical: true)            }        }        .padding(.top, 14)        .accessibilityElement(children: .combine)        .accessibilityIdentifier("days-tell")    }}#endif