Cotton code
402 lines · 17.7 KB · SwiftRaw
// THE CIRCLE (assets/design/shared/CONTACTS-ANSWERS.md section 9; PEOPLE-DESIGN b.4, c): the people he and they both// accepted on Cotton. Drawn whole from the core's answers: `circle.list` (the sections and their acts), `circle.add.page`// (search his contacts, Ask or Invite, or a number), `circle.invite` (the link handed to the system share sheet; Stop),// `circle.remove.plan` (what ends, in the core's words, before Remove or Block), and `circle.check` (the safety number// to compare, its QR, They match, a changed key to accept). Every word is the core's; every button calls the method// its answer names. Signed out, a `signedOut` answer stands in place of the page.#if os(iOS)import CoreImage.CIFilterBuiltinsimport CottonKitimport SwiftUIextension JSONValue {    /// A flag that is true only when the core says so.    var yes: Bool { if case .bool(true) = self { true } else { false } }}/// An act as the core gives it: `{id, words, primary?, red?, confirm?, call: {method, request}}`.struct CoreAct: Identifiable, Hashable {    let id: String    let words: String    let primary: Bool    let red: Bool    let confirm: String?    let method: String    let request: JSONValue    init?(_ value: JSONValue) {        guard let words = value["words"]?.string, let method = value["call"]?["method"]?.string else { return nil }        id = value["id"]?.string ?? method        self.words = words        primary = value["primary"]?.yes ?? false        red = value["red"]?.yes ?? false        confirm = value["confirm"]?.string        self.method = method        request = value["call"]?["request"] ?? .object([:])    }    static func all(_ value: JSONValue?) -> [CoreAct] { (value?.rows ?? []).compactMap(CoreAct.init) }}/// One page the Circle opens over itself, by the method that answered it.enum CirclePage: Identifiable {    case add, plan(JSONValue), check(JSONValue), invite(JSONValue)    var id: String {        switch self {        case .add: "add"        case .plan: "plan"        case .check: "check"        case .invite: "invite"        }    }}@MainActor@Observablefinal class CircleModel {    private(set) var list: JSONValue?    private(set) var said: String?    private(set) var refused: String?    private(set) var busy = false    var page: CirclePage?    let core: any CottonCalling    init(core: any CottonCalling) { self.core = core }    func read() async {        do { list = try await core.callJSON("circle.list") } catch let error as CottonCallError {            refused = error.message        } catch {            Log.write("circle: the list could not be read — \(error)")            refused = String(describing: error)        }    }    /// Call what an act names; its answer goes where its kind says: a page over the list, or the list with a sentence.    func run(_ method: String, _ request: JSONValue) async {        guard !busy else { return }        busy = true        defer { busy = false }        refused = nil        do {            let answer = try await core.callJSON(method, request)            take(answer, from: method)        } catch let error as CottonCallError {            refused = error.message        } catch {            refused = String(describing: error)        }    }    func run(_ act: CoreAct) async { await run(act.method, act.request) }    private func take(_ answer: JSONValue, from method: String) {        if let error = answer["error"]?.string { refused = error; return }        if case .object(let out)? = answer["signedOut"] { refused = out["message"]?.string; return }        switch method {        case "circle.remove.plan": page = .plan(answer); return        case "circle.check", "circle.check.confirm", "circle.check.scan", "circle.key.accept": page = .check(answer); return        case "circle.invite": page = .invite(answer); return        case "circle.add.page": page = .add; return        default: break        }        said = answer["said"]?.string        if case .object? = answer["list"] { list = answer["list"] }        // An act taken from a page over the list (Remove, Ask, Stop) closes it: the sentence and the list say what changed.        if said != nil { page = nil }    }}/// Your Circle: the core's sections, each row with its acts, Add someone at the foot.struct CircleListView: View {    let core: any CottonCalling    @State private var model: CircleModel?    @State private var confirming: CoreAct?    var body: some View {        List {            if let model, let list = model.list {                if case .object(let out)? = list["signedOut"] {                    Section {                        Text(verbatim: out["title"]?.string ?? "").font(.headline)                        Text(verbatim: out["message"]?.string ?? "").foregroundStyle(.secondary)                    }                } else {                    Section {                        Text(verbatim: list["intro"]?.string ?? "").font(.callout).foregroundStyle(.secondary)                        if let gone = list["unreachable"]?.string { Text(verbatim: gone).foregroundStyle(.secondary) }                        if let said = model.said { Text(verbatim: said).accessibilityIdentifier("circle-said") }                        if let refused = model.refused { Text(verbatim: refused).foregroundStyle(.red).accessibilityIdentifier("circle-refused") }                    }                    ForEach(list["sections"]?.rows ?? [], id: \.self) { section in                        Section(section["title"]?.string ?? "") {                            ForEach(section["rows"]?.rows ?? [], id: \.self) { row in                                CircleRow(row: row, model: model) { confirming = $0 }                            }                        }                    }                    if let add = list["add"], let words = add["words"]?.string {                        Section {                            Button(words) { model.page = .add }                                .accessibilityIdentifier("circle-add")                        }                    }                }            } else if let refused = model?.refused {                // The list did not come: the core's words say why, never a spinner that never ends.                Text(verbatim: refused).foregroundStyle(.secondary).accessibilityIdentifier("circle-refused")            } else {                ProgressView().frame(maxWidth: .infinity)            }        }        .navigationTitle(model?.list?["title"]?.string ?? "")        .navigationBarTitleDisplayMode(.inline)        .confirmationDialog(confirming?.confirm ?? "", isPresented: Binding(get: { confirming != nil }, set: { if !$0 { confirming = nil } }), titleVisibility: .visible) {            if let act = confirming, let model {                Button(act.words, role: act.red ? .destructive : nil) { Task { await model.run(act) } }            }        }        .sheet(item: Binding(get: { model?.page }, set: { model?.page = $0 })) { page in            if let model {                NavigationStack { CirclePageView(page: page, model: model) }            }        }        .task {            let model = self.model ?? CircleModel(core: core)            self.model = model            await model.read()        }        .accessibilityIdentifier("circle-list")    }}/// One person: the initials, the name and the core's line, then the row's acts. A person in the Circle opens their/// safety number (`circle.check`).private struct CircleRow: View {    let row: JSONValue    let model: CircleModel    let confirm: (CoreAct) -> Void    var body: some View {        VStack(alignment: .leading, spacing: 8) {            Button {                guard row["state"]?.string == "in" else { return }                let by: JSONValue = row["person"]?.string.map { .object(["person": .string($0)]) } ?? .object(["number": row["number"] ?? .null])                Task { await model.run("circle.check", by) }            } label: {                HStack(spacing: 12) {                    Text(verbatim: row["initials"]?.string ?? "")                        .font(.footnote.weight(.semibold))                        .frame(width: 36, height: 36)                        .background(Color.secondary.opacity(0.15), in: Circle())                    VStack(alignment: .leading, spacing: 2) {                        Text(verbatim: row["words"]?.string ?? "")                        if let detail = row["detail"]?.string { Text(verbatim: detail).font(.footnote).foregroundStyle(.secondary) }                    }                    Spacer()                }                .contentShape(Rectangle())            }            .buttonStyle(.plain)            let acts = CoreAct.all(row["acts"])            if !acts.isEmpty {                HStack(spacing: 10) {                    ForEach(acts) { act in                        let button = Button(act.words, role: act.red ? .destructive : nil) {                            if act.confirm != nil { confirm(act) } else { Task { await model.run(act) } }                        }                        .disabled(model.busy)                        .accessibilityIdentifier("circle-act-\(act.id)-\(row["id"]?.string ?? "")")                        if act.primary { button.buttonStyle(.borderedProminent) } else { button.buttonStyle(.bordered) }                    }                }                .font(.subheadline)            }        }        .padding(.vertical, 4)    }}/// A page over the list, drawn from the answer that opened it.private struct CirclePageView: View {    let page: CirclePage    let model: CircleModel    @Environment(\.dismiss) private var dismiss    var body: some View {        Group {            switch page {            case .add: CircleAddView(model: model)            case .plan(let plan): CirclePlanView(plan: plan, model: model)            case .check(let check): CircleCheckView(check: check, model: model)            case .invite(let invite): CircleInviteView(invite: invite, model: model)            }        }        .toolbar {            ToolbarItem(placement: .cancellationAction) {                Button { dismiss() } label: { Image(systemName: "xmark") }.accessibilityIdentifier("circle-page-close")            }        }    }}/// Add someone: his contacts by search, each with Ask and Invite; a number no contact holds.private struct CircleAddView: View {    let model: CircleModel    @State private var answer: JSONValue?    @State private var query = ""    @State private var number = ""    var body: some View {        List {            if let page = answer {                if let refused = model.refused { Text(verbatim: refused).foregroundStyle(.red) }                Section {                    if let empty = page["empty"]?.string { Text(verbatim: empty).foregroundStyle(.secondary) }                    ForEach(page["rows"]?.rows ?? [], id: \.self) { row in                        VStack(alignment: .leading, spacing: 6) {                            Text(verbatim: row["words"]?.string ?? "")                            if let detail = row["detail"]?.string { Text(verbatim: detail).font(.footnote).foregroundStyle(.secondary) }                            HStack {                                ForEach(CoreAct.all(row["acts"])) { act in                                    Button(act.words) { Task { await model.run(act) } }.buttonStyle(.bordered).disabled(model.busy)                                }                            }                            .font(.subheadline)                        }                    }                }                if let field = page["number"], let method = field["call"]?["method"]?.string {                    Section(field["words"]?.string ?? "") {                        TextField(field["placeholder"]?.string ?? "", text: $number)                            .keyboardType(.phonePad)                            .textContentType(.telephoneNumber)                            .accessibilityIdentifier("circle-add-number")                        // The number's own Ask: the Circle's word for it (`circle` acts.ask).                        Button(ShellLines.line("circle", "acts.ask")) { Task { await model.run(method, .object(["number": .string(number)])) } }                            .disabled(model.busy || number.isEmpty)                            .accessibilityIdentifier("circle-add-ask-number")                    }                }                if let foot = page["foot"]?.string { Section { Text(verbatim: foot).font(.footnote).foregroundStyle(.secondary) } }            } else {                ProgressView().frame(maxWidth: .infinity)            }        }        .searchable(text: $query, prompt: Text(verbatim: answer?["search"]?["placeholder"]?.string ?? ""))        .navigationTitle(answer?["title"]?.string ?? "")        .navigationBarTitleDisplayMode(.inline)        .task(id: query) {            answer = try? await model.core.callJSON("circle.add.page", JSONValue.object(["query": .string(query)]))        }    }}/// Before Remove or Block: what ends, app by app, and what stays, in the core's words; then its acts.private struct CirclePlanView: View {    let plan: JSONValue    let model: CircleModel    var body: some View {        List {            if let refused = model.refused { Text(verbatim: refused).foregroundStyle(.red) }            Section {                ForEach(plan["ends"]?.rows ?? [], id: \.self) { end in                    VStack(alignment: .leading, spacing: 2) {                        Text(verbatim: end["words"]?.string ?? end.string ?? "").font(.headline)                        if let detail = end["detail"]?.string { Text(verbatim: detail).foregroundStyle(.secondary) }                    }                }            }            Section {                ForEach(plan["stays"]?.rows ?? [], id: \.self) { stay in                    Text(verbatim: stay.string ?? stay["words"]?.string ?? "").foregroundStyle(.secondary)                }            }            Section {                ForEach(CoreAct.all(plan["acts"])) { act in                    Button(act.words, role: act.red ? .destructive : nil) { Task { await model.run(act) } }                        .disabled(model.busy)                        .accessibilityIdentifier("circle-plan-\(act.id)")                }            }        }        .navigationTitle(plan["title"]?.string ?? "")        .navigationBarTitleDisplayMode(.inline)    }}/// The safety number to compare, large and grouped as given, its QR for the other phone, and They match (or a changed/// key's old and new code, and Accept).private struct CircleCheckView: View {    let check: JSONValue    let model: CircleModel    var body: some View {        ScrollView {            VStack(spacing: 18) {                if let refused = model.refused { Text(verbatim: refused).foregroundStyle(.red) }                Text(verbatim: check["words"]?.string ?? "")                    .font(.system(size: 28, weight: .semibold, design: .monospaced))                    .multilineTextAlignment(.center)                    .accessibilityIdentifier("circle-check-words")                if let qr = check["qr"]?.string, let image = CircleQR.image(qr) {                    Image(uiImage: image).interpolation(.none).resizable().scaledToFit().frame(maxWidth: 220)                        .accessibilityHidden(true)                }                if let message = check["message"]?.string { Text(verbatim: message).multilineTextAlignment(.center).foregroundStyle(.secondary) }                if let was = check["was"]?.string, let now = check["now"]?.string {                    Text(verbatim: "\(was) → \(now)").font(.body.monospaced())                }                ForEach(CoreAct.all(check["acts"])) { act in                    Button(act.words) { Task { await model.run(act) } }                        .buttonStyle(.borderedProminent)                        .disabled(model.busy)                        .accessibilityIdentifier("circle-check-\(act.id)")                }            }            .padding(24)        }        .navigationTitle(check["title"]?.string ?? "")        .navigationBarTitleDisplayMode(.inline)    }}/// An invitation: the link handed to the system share sheet from his own messages (Cotton sends nothing); Stop.private struct CircleInviteView: View {    let invite: JSONValue    let model: CircleModel    var body: some View {        VStack(alignment: .leading, spacing: 16) {            if let message = invite["message"]?.string { Text(verbatim: message) }            if let share = invite["share"]?.string ?? invite["link"]?.string {                ShareLink(item: share) { Label(invite["link"]?.string ?? share, systemImage: "square.and.arrow.up").lineLimit(2) }                    .accessibilityIdentifier("circle-invite-share")            }            if let ends = invite["ends"]?.string { Text(verbatim: ends).font(.footnote).foregroundStyle(.secondary) }            if let stop = invite["stop"].flatMap(CoreAct.init) {                Button(stop.words, role: .destructive) { Task { await model.run(stop) } }                    .accessibilityIdentifier("circle-invite-stop")            }            Spacer()        }        .padding(24)        .navigationTitle(invite["title"]?.string ?? "")        .navigationBarTitleDisplayMode(.inline)    }}/// The core's QR text drawn as a code for the other phone's camera.enum CircleQR {    static func image(_ text: String) -> UIImage? {        let filter = CIFilter.qrCodeGenerator()        filter.message = Data(text.utf8)        filter.correctionLevel = "M"        guard let output = filter.outputImage?.transformed(by: CGAffineTransform(scaleX: 8, y: 8)),              let cg = CIContext().createCGImage(output, from: output.extent) else { return nil }        return UIImage(cgImage: cg)    }}#endif