Cotton code
159 lines · 7.1 KB · SwiftRaw
// What was sent to this person and what became of what they sent, asked of// the core (`send.inbox`) on launch, on coming back, on a door opening and// on a chat socket's `send` frame; and the acts a send's card offers, each// asked of the core as it said them. Every app draws it: Messages in the// thread with the sender, an app with no chat on its Sent to you card.import CottonKitimport CottonValuesimport Foundationimport Observationimport SwiftUIextension Notification.Name {    /// Something sent to this person arrived, or a send moved: the inbox is asked again.    public static let cottonSendArrived = Notification.Name("com.cottondb.send.arrived")}@MainActor @Observablepublic final class SendCenter {    public static let session = SendCenter()    /// The fan's card of what was sent, in an app with no chat (`cotton_send::SENT_CARD`).    public static let sentCard = "sent"    /// What was sent to this person, in the object's order, each with what its card says.    public private(set) var incoming: [SendItem] = []    /// The sends whose act is being asked: their acts wait.    public private(set) var busy: Set<String> = []    /// The inbox asked again; each send lands as its thread's item on the way.    public func refresh(core: (any CottonCalling)?) async {        guard let core else { return }        guard let inbox = try? await core.call(CottonMethod.sendInbox, JSONValue.object([:]), as: SendInbox.self) else { return }        incoming = inbox.in    }    /// While a Keep's bytes copy, the inbox is asked again every few seconds    /// until it has landed, so the card's progress moves.    public func follow(_ item: SendItem, core: (any CottonCalling)?) async {        while !Task.isCancelled, incoming.first(where: { $0.id == item.id })?.copying ?? item.copying {            try? await Task.sleep(for: .seconds(SendKnobs.followSeconds))            await refresh(core: core)        }    }    /// One of a card's acts, as the core said it. What it refuses is said;    /// Open opens the record it names.    public func run(_ act: SendAct, on id: String, core: (any CottonCalling)?, toasts: ToastCenter?,                    open: (SendRecordRef) -> Void) async {        guard let core else { return }        if act.id == "open", let opens = act.opens { return open(opens) }        busy.insert(id)        defer { busy.remove(id) }        do {            switch act.id {            case "keep":                _ = try await core.call(CottonMethod.sendKeep, JSONValue.object(["id": .string(id)]), as: SendMoved.self)            case "decline":                _ = try await core.callJSON(CottonMethod.sendDecline, JSONValue.object(["id": .string(id)]))            case "undo":                _ = try await core.call(CottonMethod.sendUndo, JSONValue.object(["id": .string(id)]), as: SendMoved.self)            case "trust":                guard let trust = act.trust else { return }                _ = try await core.callJSON(CottonMethod.sendTrust, JSONValue.object(["number": .string(trust.number), "trusted": .bool(trust.trusted)]))            default:                return            }        } catch {            toasts?.show(ActionRefused.words(for: error), tone: .error)        }        await refresh(core: core)    }    /// A person's trust set from the Send tier's hold.    public func trust(_ trust: SendTrust, core: (any CottonCalling)?, toasts: ToastCenter?) async {        guard let core else { return }        do {            _ = try await core.callJSON(CottonMethod.sendTrust, JSONValue.object(["number": .string(trust.number), "trusted": .bool(trust.trusted)]))        } catch {            toasts?.show(ActionRefused.words(for: error), tone: .error)        }    }    /// A record sent to one of the person's people, and the receipt it    /// leaves: its Undo takes the send back while it is not yet kept.    public func send(table: String, id: String, to person: SendPerson, core: (any CottonCalling)?, toasts: ToastCenter?) async {        guard let core else { return }        do {            let ask = JSONValue.object(["table": .string(table), "id": .string(id), "to": .string(person.value), "name": .string(person.words)])            let made = try await core.call(CottonMethod.sendMake, ask, as: SendMade.self)            guard let receipt = made.receipt else { return }            toasts?.show(receipt.words) { [weak self] in                Task { await self?.takeBack(made.id, receipt: receipt, core: core, toasts: toasts) }            }        } catch {            toasts?.show(ActionRefused.words(for: error), tone: .error)        }    }    private func takeBack(_ id: String, receipt: SendReceipt, core: any CottonCalling, toasts: ToastCenter?) async {        do {            _ = try await core.call(CottonMethod.sendUndo, JSONValue.object(["id": .string(id)]), as: SendMoved.self)            if let undone = receipt.undone { toasts?.show(undone) }        } catch {            toasts?.show(ActionRefused.words(for: error), tone: .error)        }    }}/// Every app asks its inbox on coming forward, when its door opens, when/// a send is heard of (`cottonSendArrived`) and on a slow clock while it is/// in front (an app with no chat has no socket to hear of one: a send made/// while Books was open stood unseen until it came forward again), so what/// was sent lands on its thread (Messages) or its Sent to you card.public struct SendShell: ViewModifier {    let core: any CottonCalling    @Environment(\.scenePhase) private var scenePhase    public init(core: any CottonCalling) { self.core = core }    public func body(content: Content) -> some View {        content            .onChange(of: scenePhase, initial: true) { _, phase in                if phase == .active { refresh() }            }            .onReceive(NotificationCenter.default.publisher(for: .cottonPersonalDoor)) { note in                if note.userInfo?["open"] as? Bool == true { refresh() }            }            .onReceive(NotificationCenter.default.publisher(for: .cottonSendArrived)) { _ in refresh() }            .task(id: scenePhase) {                guard scenePhase == .active else { return }                while !Task.isCancelled {                    try? await Task.sleep(for: .seconds(SendKnobs.frontSeconds))                    guard !Task.isCancelled else { return }                    await SendCenter.session.refresh(core: core)                }            }    }    private func refresh() {        let core = core        Task { await SendCenter.session.refresh(core: core) }    }}extension View {    /// The app's inbox of sends, asked as `SendShell` says.    public func sendShell(core: any CottonCalling) -> some View { modifier(SendShell(core: core)) }}enum SendKnobs {    /// How often a copy under way is asked after.    static let followSeconds: Double = 2    /// How often the inbox is asked while the app is in front.    static let frontSeconds: Double = 30    /// The longest side a send's card is drawn at, in points.    static let cardWidth: CGFloat = 200    /// A card's height over its width, as a held card stands.    static let cardRatio: CGFloat = 1.42}