Cotton code
328 lines · 15.4 KB · SwiftRaw
// THE ONE SHARE SHEET (assets/design/shared/CONTACTS-ANSWERS.md section 10; PEOPLE-DESIGN d.1, d.2): every app shares// through the same methods with its own `app` and `thing` (Albums an album, Secrets a secret, Days one event, Cinemas a// list). `share.sheet` gives the Circle to pick from (a person who cannot be picked says why, and a row may offer the// safety-number check, `circle.check`), the roles and, for Secrets, how long; as the pick changes `share.plan` gives// the button's words and what will happen; `share.do` shares. After that `share.with` says who has it, each with the// acts the core gives (a role, Stop). Every word is the core's. A call the vault must open for (Secrets) is asked// again with this device's key behind Face ID when the core says the vault is shut.#if os(iOS)import CottonKitimport SwiftUI@MainActor@Observablefinal class ShareSheetModel {    let app: String    let thing: JSONValue    private(set) var sheet: JSONValue?    private(set) var plan: JSONValue?    private(set) var with: JSONValue?    private(set) var said: String?    private(set) var refused: String?    private(set) var busy = false    /// The people picked, by contact id or number, in the order picked.    private(set) var picked: [String] = []    var role: String?    var until: String?    var date = Date().addingTimeInterval(7 * 86_400)    /// The safety number opened from a row.    var check: JSONValue?    @ObservationIgnored let core: any CottonCalling    @ObservationIgnored private let vault = VaultAccess()    /// What the app does once shared, with the `thing` `share.do` answered (Albums adds the photos to the album it founded).    @ObservationIgnored var after: ((JSONValue) async -> Void)?    init(core: any CottonCalling, app: String, thing: JSONValue) {        self.core = core        self.app = app        self.thing = thing    }    nonisolated static func key(_ row: JSONValue) -> String { row["person"]?.string ?? row["number"]?.string ?? "" }    func read() async {        guard let answer = await call("share.sheet", ["app": .string(app), "thing": thing]) else { return }        sheet = answer        role = role ?? answer["roles"]?.rows.first { $0["on"]?.yes == true }?["id"]?.string ?? answer["roles"]?.rows.first?["id"]?.string        until = until ?? answer["until"]?.rows.first { $0["on"]?.yes == true }?["id"]?.string        await replan()    }    func toggle(_ row: JSONValue) async {        let key = Self.key(row)        if let at = picked.firstIndex(of: key) { picked.remove(at: at) } else { picked.append(key) }        await replan()    }    private var asked: [String: JSONValue] {        var request: [String: JSONValue] = ["app": .string(app), "thing": thing, "people": .array(picked.map { .string($0) })]        if let role { request["role"] = .string(role) }        if let until { request["until"] = .string(until == "date" ? Self.day(date) : until) }        if app == "days" { request["timezone"] = .string(TimeZone.current.identifier) }        return request    }    func replan() async {        guard !picked.isEmpty else { plan = nil; return }        plan = await call("share.plan", asked, quiet: true)    }    /// Share with the people picked; what it is shared with stands after.    func go() async {        guard let done = await call("share.do", asked) else { return }        said = done["said"]?.string        with = done["with"]        picked = []        plan = nil        if let after, let shared = done["thing"] {            busy = true            await after(shared)            busy = false        }    }    func readWith() async {        with = await call("share.with", ["app": .string(app), "thing": thing], quiet: true)    }    /// A row's act (a role, Stop): its answer is the new `share.with`, with a sentence.    func run(_ act: CoreAct) async {        var request: [String: JSONValue] = [:]        if case .object(let fields) = act.request { request = fields }        if app == "days", act.method.hasPrefix("share.") { request["timezone"] = .string(TimeZone.current.identifier) }        guard let answer = await call(act.method, request) else { return }        if act.method == "circle.check" || act.method.hasPrefix("circle.check") || act.method == "circle.key.accept" {            check = answer            await read()            return        }        said = answer["said"]?.string        if answer["rows"] != nil { with = answer } else { await readWith() }    }    private func call(_ method: String, _ request: [String: JSONValue], quiet: Bool = false) async -> JSONValue? {        busy = true        defer { busy = false }        if !quiet { refused = nil }        do {            let answer = try await core.callJSON(method, JSONValue.object(request))            if let error = answer["error"]?.string {                refused = error                return nil            }            return answer        } catch let error as CottonCallError where error.code == "vault_locked" {            switch await vault.handing(method, through: core, { key in JSONValue.object(request.merging(["privateKey": .string(key)]) { a, _ in a }) }) {            case .answered(let answer):                if let error = answer["error"]?.string { refused = error; return nil }                return answer            case .refused(let words): refused = words            default: break            }        } catch let error as CottonCallError {            refused = error.message        } catch {            Log.write("share: \(method) — \(error)")        }        return nil    }    private static func day(_ date: Date) -> String {        let format = DateFormatter()        format.calendar = Calendar(identifier: .gregorian)        format.locale = Locale(identifier: "en_US_POSIX")        format.dateFormat = "yyyy-MM-dd"        return format.string(from: date)    }}/// The sheet: who to share with, how, for how long, then the button the plan words; who has it after.struct ShareSheetView: View {    let core: any CottonCalling    let app: String    let thing: JSONValue    /// How the app closes the sheet, when it presents it itself; the presentation's own dismiss otherwise.    var close: (() -> Void)?    /// What the app does once shared (see `ShareSheetModel.after`).    var after: ((JSONValue) async -> Void)?    @State private var model: ShareSheetModel?    @State private var circle = false    @Environment(\.dismiss) private var dismiss    var body: some View {        NavigationStack {            List {                if let model, let sheet = model.sheet {                    if let said = model.said { Text(verbatim: said).accessibilityIdentifier("share-said") }                    if let refused = model.refused { Text(verbatim: refused).foregroundStyle(.red).accessibilityIdentifier("share-refused") }                    if case .object(let empty)? = sheet["empty"] {                        Section {                            Text(verbatim: empty["title"]?.string ?? "").font(.headline)                            Text(verbatim: empty["message"]?.string ?? "").foregroundStyle(.secondary)                            Button(ShellLines.line("circle", "add.title")) { circle = true }                        }                    }                    Section {                        ForEach(sheet["people"]?.rows ?? [], id: \.self) { row in person(row, model: model) }                    }                    if (sheet["roles"]?.rows.count ?? 0) > 1 {                        Section {                            Picker("", selection: Binding(get: { model.role ?? "" }, set: { model.role = $0; Task { await model.replan() } })) {                                ForEach(sheet["roles"]?.rows ?? [], id: \.self) { role in                                    Text(verbatim: role["words"]?.string ?? "").tag(role["id"]?.string ?? "")                                }                            }                            .pickerStyle(.segmented)                            .accessibilityIdentifier("share-role")                        }                    }                    if let until = sheet["until"]?.rows, !until.isEmpty {                        Section {                            Picker("", selection: Binding(get: { model.until ?? "" }, set: { model.until = $0; Task { await model.replan() } })) {                                ForEach(until, id: \.self) { choice in                                    Text(verbatim: choice["words"]?.string ?? "").tag(choice["id"]?.string ?? "")                                }                            }                            .pickerStyle(.menu)                            .accessibilityIdentifier("share-until")                            if model.until == "date" {                                DatePicker("", selection: Binding(get: { model.date }, set: { model.date = $0; Task { await model.replan() } }), in: Date()..., displayedComponents: .date)                                    .labelsHidden()                            }                        }                    }                    if let lines = model.plan?["lines"]?.rows, !lines.isEmpty {                        Section {                            ForEach(lines, id: \.self) { line in Text(verbatim: line.string ?? "").font(.callout) }                        }                    }                    Section {                        Button((model.plan?["go"] ?? sheet["go"])?["words"]?.string ?? "") { Task { await model.go() } }                            .buttonStyle(.borderedProminent)                            .frame(maxWidth: .infinity)                            .disabled(model.busy || model.picked.isEmpty)                            .accessibilityIdentifier("share-go")                        if let foot = sheet["foot"]?.string { Text(verbatim: foot).font(.footnote).foregroundStyle(.secondary) }                    }                    if let with = model.with { withSection(with, model: model) }                } else if let refused = model?.refused {                    Text(verbatim: refused).foregroundStyle(.secondary)                } else {                    ProgressView().frame(maxWidth: .infinity)                }            }            .navigationTitle(model?.sheet?["title"]?.string ?? "")            .navigationBarTitleDisplayMode(.inline)            .toolbar {                ToolbarItem(placement: .cancellationAction) {                    Button { if let close { close() } else { dismiss() } } label: { Image(systemName: "xmark") }.accessibilityIdentifier("share-close")                }            }            .sheet(item: Binding(get: { model?.check.map(ShareCheck.init) }, set: { if $0 == nil { model?.check = nil } })) { opened in                NavigationStack { ShareCheckView(check: opened.value, model: model) }            }            .sheet(isPresented: $circle) {                NavigationStack { CircleListView(core: core) }                    .onDisappear { Task { await model?.read() } }            }        }        .task {            let model = self.model ?? ShareSheetModel(core: core, app: app, thing: thing)            model.after = after            self.model = model            await model.read()            await model.readWith()        }        .accessibilityIdentifier("share-sheet")    }    /// One person from the Circle: picked or not; one who cannot be picked says why, and may offer the check.    @ViewBuilder private func person(_ row: JSONValue, model: ShareSheetModel) -> some View {        let key = ShareSheetModel.key(row)        let can = row["can"]?.yes ?? false        let on = model.picked.contains(key)        HStack(spacing: 12) {            Button { Task { await model.toggle(row) } } label: {                HStack(spacing: 12) {                    Image(systemName: on ? "checkmark.circle.fill" : (row["has"]?.yes == true ? "checkmark.circle" : "circle"))                        .foregroundStyle(can ? Color.accentColor : .secondary)                    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)            .disabled(!can || model.busy)            if let call = row["call"], let method = call["method"]?.string {                Button(ShellLines.line("circle", "check.title")) {                    Task { await model.run(CoreAct(.object(["id": .string("check"), "words": .string(""), "call": .object(["method": .string(method), "request": call["request"] ?? .null])]))!) }                }                .buttonStyle(.bordered)                .font(.footnote)                .accessibilityIdentifier("share-check-\(key)")            }        }        .accessibilityIdentifier("share-person-\(key)")    }    @ViewBuilder private func withSection(_ with: JSONValue, model: ShareSheetModel) -> some View {        Section(with["title"]?.string ?? "") {            ForEach(with["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) }                    let acts = CoreAct.all(row["acts"])                    if !acts.isEmpty {                        HStack {                            ForEach(acts) { act in                                Button(act.words, role: act.red ? .destructive : nil) { Task { await model.run(act) } }                                    .buttonStyle(.bordered)                                    .disabled(model.busy)                            }                        }                        .font(.subheadline)                    }                }            }        }        .accessibilityIdentifier("share-with")    }}private struct ShareCheck: Identifiable {    let value: JSONValue    var id: String { value["words"]?.string ?? "check" }}/// The safety number opened from a row of the sheet: compare, They match, or a changed key's Accept.private struct ShareCheckView: View {    let check: JSONValue    let model: ShareSheetModel?    var body: some View {        ScrollView {            VStack(spacing: 18) {                Text(verbatim: check["words"]?.string ?? "")                    .font(.system(size: 28, weight: .semibold, design: .monospaced))                    .multilineTextAlignment(.center)                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)                }            }            .padding(24)        }        .navigationTitle(check["title"]?.string ?? "")        .navigationBarTitleDisplayMode(.inline)    }}#endif