Cotton code
303 lines · 12.9 KB · SwiftRaw
// GOOGLE CALENDAR IN DAYS (assets/design/days/CONTRACT.md §13, as Android's// `DaysSurface.kt` and `ui/Settings.kt`): which Google account is connected// and how its events are coming, Disconnect asking first, and the notice that// stands before Google's consent page (GOOGLE.md §4: immediately before// consent, with an affirmative Continue to Google). Every word is the core's// (`days.google`); Connect stands only while nothing is connected.#if os(iOS)import CottonKitimport SwiftUI/// `days.google`'s answer.struct DaysGoogle: Decodable, Equatable, Sendable {    struct Account: Decodable, Equatable, Sendable, Identifiable {        let email: String        let says: String        /// Google stopped letting Days read it, or did not answer: `says` in the pen's ink.        var trouble = false        let disconnect: Disconnect?        var id: String { email }        private enum CodingKeys: String, CodingKey { case email, says, trouble, disconnect }        init(from decoder: Decoder) throws {            let c = try decoder.container(keyedBy: CodingKeys.self)            email = try c.decode(String.self, forKey: .email)            says = try c.decodeIfPresent(String.self, forKey: .says) ?? ""            trouble = try c.decodeIfPresent(Bool.self, forKey: .trouble) ?? false            disconnect = try c.decodeIfPresent(Disconnect.self, forKey: .disconnect)        }    }    struct Disconnect: Decodable, Equatable, Sendable, Identifiable {        let account: String        let label: String        let asks: String        let yes: String        var id: String { account }    }    struct Connect: Decodable, Equatable, Sendable, Identifiable {        let id: String        let tool: String        let label: String        let notice: Notice    }    struct Notice: Decodable, Equatable, Sendable {        let title: String        let body: String        let go: String        let notNow: String    }    /// "Also keep my Days events in Google Calendar" (CONTRACT §16), while an account stands.    struct Keep: Decodable, Equatable, Sendable {        let label: String        let line: String        let on: Bool    }    var line: String = ""    var accounts: [Account] = []    var connect: Connect?    var unavailable: String?    /// Signed out: Sign in, offered right on the page so it is never a dead end (store pass, 24 Nov 2026).    var signIn: String?    var keep: Keep?    private enum CodingKeys: String, CodingKey { case line, accounts, connect, unavailable, keep, signIn }    init(line: String = "", accounts: [Account] = [], connect: Connect? = nil, unavailable: String? = nil) {        self.line = line        self.accounts = accounts        self.connect = connect        self.unavailable = unavailable    }    init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        line = try c.decodeIfPresent(String.self, forKey: .line) ?? ""        accounts = try c.decodeIfPresent([Account].self, forKey: .accounts) ?? []        connect = try c.decodeIfPresent(Connect.self, forKey: .connect)        unavailable = try c.decodeIfPresent(String.self, forKey: .unavailable)        signIn = try c.decodeIfPresent(String.self, forKey: .signIn)        keep = try c.decodeIfPresent(Keep.self, forKey: .keep)    }    /// The first day's line: it offers the calendar in words only while Connect stands.    static func firstDayLine(connect: Connect?) -> String {        connect == nil ? "empty.line_alone" : "empty.line"    }    /// The act Continue to Google runs: the Calendar tool's own (`tools.act`), which answers the page to open.    var connectAct: CardAction? {        connect.map { CardAction(id: $0.id, label: $0.label, kind: "tool", tool: $0.tool) }    }}/// `days.google_disconnect`'s answer.struct DaysGoogleDisconnected: Decodable, Sendable {    let account: String    let removed: Int    let said: String}extension DaysModel {    private struct GoogleAsk: Encodable, Sendable { let timezone: String }    private struct DisconnectAsk: Encodable, Sendable { let account: String }    private struct KeepAsk: Encodable, Sendable { let on: Bool }    /// Asked when Days opens, on every change, after Disconnect, and when Days comes back to the front.    /// A failed ask keeps what was last said.    func readGoogle() async {        guard let core else { return }        if let answer = try? await core.call("days.google", GoogleAsk(timezone: clock.zone().identifier), as: DaysGoogle.self) {            google = answer        }    }    /// Connect, from Settings or the first day: its notice first, never Google's page at once.    func askToConnect() {        noticing = google?.connect    }    /// "Also keep my Days events in Google Calendar" turned on or off (`days.google_keep`); turned on, they go now.    func keepInGoogle(_ on: Bool) async {        guard let core else { return }        await attempt { _ = try await core.call("days.google_keep", KeepAsk(on: on), as: JSONValue.self) }        await readGoogle()        if on { await sendAway() }    }    /// What waits for Google or for someone on Cotton goes (`days.send_to_google`, then `days.invitations`; CONTRACT    /// §16, §17), as Android's DaysSurface sendAway: after a change that says so, on coming to the front, and after a    /// sync (`unlessWithin`: not again within that many seconds of the last). What it says is said at Days' foot; when    /// Google must be asked once more, its line with Connect, which opens the notice first.    func sendAway(unlessWithin seconds: TimeInterval? = nil) async {        if let seconds, let at = sentAt, clock.now().timeIntervalSince(at) < seconds { return }        guard !sending else { return }        sending = true        let sent = try? await book.send()        sending = false        sentAt = clock.now()        guard let sent else { return }        if !sent.said.isEmpty { tell(sent.said.joined(separator: "\n")) }        if let line = sent.reconnect {            if let connect = sent.connect {                tell(line, act: connect.label) { [weak self] in self?.noticing = connect }            } else {                tell(line)            }        }        if !sent.said.isEmpty { await read() }    }    /// Disconnect, after its ask: the core says what left, then Days and Google are read again.    func disconnectGoogle(_ account: String) async {        guard let core else { return }        await attempt {            let done = try await core.call("days.google_disconnect", DisconnectAsk(account: account), as: DaysGoogleDisconnected.self)            tell(done.said)        }        await read()        await readGoogle()    }}/// Settings › Google calendars: the core's line, each account with how its events are coming and Disconnect,/// Connect while it stands, or why nothing can be connected and, signed out, Sign in right there.struct DaysGoogleGroup: View {    @Bindable var model: DaysModel    /// Settings' own reading: the account's Sign in, run here as the card at the top runs it.    var home: SettingsHome? = nil    @Environment(\.openURL) private var openURL    @Environment(\.nativeKeptFlow) private var nativeFlow    @Environment(\.rekeyThisDevice) private var rekey    var body: some View {        VStack(alignment: .leading, spacing: 0) {            Text(model.google?.line.nonEmpty ?? DaysWords.line("settings.calendars_line"))                .font(PenType.small).foregroundStyle(Pen.quiet)                .padding(.top, 8).padding(.bottom, 4)                .fixedSize(horizontal: false, vertical: true)            ForEach(model.google?.accounts ?? []) { account in                ViewThatFits(in: .horizontal) {                    HStack(alignment: .center, spacing: 12) {                        words(account)                        Spacer(minLength: 8)                        disconnect(account)                    }                    VStack(alignment: .leading, spacing: 10) {                        words(account)                        disconnect(account)                    }                }                .padding(.top, 10)                .accessibilityIdentifier("days-google-account")            }            if let connect = model.google?.connect {                PenButton(words: connect.label) { model.askToConnect() }                    .padding(.top, 10)                    .accessibilityIdentifier("days-settings-connect")            }            // "Also keep my Days events in Google Calendar" (CONTRACT §16), off until the person turns it on.            if let keep = model.google?.keep {                PenChip(words: keep.label, on: keep.on) { Task { await model.keepInGoogle(!keep.on) } }                    .padding(.top, 14)                    .accessibilityIdentifier("days-google-keep")                Text(keep.line).font(PenType.small).foregroundStyle(Pen.quiet)                    .padding(.top, 6)                    .fixedSize(horizontal: false, vertical: true)            }            if let unavailable = model.google?.unavailable {                Text(unavailable).font(PenType.small).foregroundStyle(Pen.quiet)                    .padding(.top, 10)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("days-google-unavailable")            }            if let label = model.google?.signIn,               let act = home?.answer?.account?.actions.first(where: { $0.id == "account_sign_in" }) {                PenButton(words: label) {                    Task { await SettingsActs(core: model.core, openURL: openURL, nativeFlow: nativeFlow, rekey: rekey, said: { model.tell($0) }).run(act) }                }                .padding(.top, 10)                .accessibilityIdentifier("days-google-sign-in")            }        }        .padding(.bottom, 6)    }    private func words(_ account: DaysGoogle.Account) -> some View {        VStack(alignment: .leading, spacing: 2) {            Text(account.email).font(PenType.words).foregroundStyle(Pen.ink)            if !account.says.isEmpty {                Text(account.says).font(PenType.small)                    .foregroundStyle(account.trouble ? Pen.pen : Pen.quiet)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("days-google-says")            }        }        .accessibilityElement(children: .combine)    }    @ViewBuilder    private func disconnect(_ account: DaysGoogle.Account) -> some View {        if let act = account.disconnect {            PenButton(words: act.label) { model.disconnecting = act }                .accessibilityIdentifier("days-google-disconnect")        }    }}/// A notice in the pen look, over a scrim: a title, what it means, and its buttons; a tap outside dismisses./// The notice before Google's page (Not now, Continue to Google) and Disconnect's ask (its one yes) are both this.struct PenNoticeCard: View {    var title: String?    let words: String    var notNow: String?    let go: String    let tag: String    let onGo: () -> Void    let onDismiss: () -> Void    var body: some View {        ZStack {            Color.black.opacity(0.28).ignoresSafeArea()                .onTapGesture(perform: onDismiss)                .accessibilityHidden(true)            ScrollView {                VStack(alignment: .leading, spacing: 14) {                    if let title {                        Text(title).font(PenType.month).foregroundStyle(Pen.ink)                            .fixedSize(horizontal: false, vertical: true)                            .accessibilityAddTraits(.isHeader)                    }                    Text(words).font(PenType.words).foregroundStyle(Pen.ink)                        .fixedSize(horizontal: false, vertical: true)                    PenFlow(spacing: 10, lineSpacing: 10) {                        if let notNow {                            PenButton(words: notNow, tap: onDismiss).accessibilityIdentifier("\(tag)-not-now")                        }                        PenButton(words: go, go: true, tap: onGo).accessibilityIdentifier("\(tag)-go")                    }                    .frame(maxWidth: .infinity, alignment: .trailing)                }                .padding(22)                .background(RoundedRectangle(cornerRadius: 28, style: .continuous).fill(Pen.sheet))                .overlay(RoundedRectangle(cornerRadius: 28, style: .continuous).strokeBorder(Pen.rule, lineWidth: Pen.stroke))                .padding(.horizontal, 20)                .frame(maxWidth: .infinity, minHeight: 0)            }            .scrollBounceBehavior(.basedOnSize)            .fixedSize(horizontal: false, vertical: true)            .accessibilityElement(children: .contain)            .accessibilityIdentifier("\(tag)-notice")            .accessibilityAddTraits(.isModal)        }        .accessibilityAction(.escape, onDismiss)    }}private extension String {    var nonEmpty: String? { isEmpty ? nil : self }}#endif