// 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.importCottonKitimportCottonValuesimportFoundationimportObservationimportSwiftUIextensionNotification.Name {/// Something sent to this person arrived, or a send moved: the inbox is asked again.publicstaticlet cottonSendArrived = Notification.Name("com.cottondb.send.arrived")}@MainActor @ObservablepublicfinalclassSendCenter {publicstaticlet session = SendCenter()/// The fan's card of what was sent, in an app with no chat (`cotton_send::SENT_CARD`).publicstaticlet sentCard = "sent"/// What was sent to this person, in the object's order, each with what its card says.publicprivate(set) var incoming: [SendItem] = []/// The sends whose act is being asked: their acts wait.publicprivate(set) var busy: Set<String> = []/// The inbox asked again; each send lands as its thread's item on the way.publicfunc refresh(core: (any CottonCalling)?) async {guardlet core else { return }guardlet 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.publicfunc follow(_ item: SendItem, core: (any CottonCalling)?) async {while !Task.isCancelled, incoming.first(where: { $0.id == item.id })?.copying ?? item.copying {try? awaitTask.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.publicfunc run(_ act: SendAct, on id: String, core: (any CottonCalling)?, toasts: ToastCenter?,open: (SendRecordRef) -> Void) async {guardlet core else { return }if act.id == "open", let opens = act.opens { returnopen(opens) } busy.insert(id)defer { busy.remove(id) }do {switch act.id {case"keep": _ = tryawait core.call(CottonMethod.sendKeep, JSONValue.object(["id": .string(id)]), as: SendMoved.self)case"decline": _ = tryawait core.callJSON(CottonMethod.sendDecline, JSONValue.object(["id": .string(id)]))case"undo": _ = tryawait core.call(CottonMethod.sendUndo, JSONValue.object(["id": .string(id)]), as: SendMoved.self)case"trust":guardlet trust = act.trust else { return } _ = tryawait 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.publicfunc trust(_ trust: SendTrust, core: (any CottonCalling)?, toasts: ToastCenter?) async {guardlet core else { return }do { _ = tryawait 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.publicfunc send(table: String, id: String, to person: SendPerson, core: (any CottonCalling)?, toasts: ToastCenter?) async {guardlet core else { return }do {let ask = JSONValue.object(["table": .string(table), "id": .string(id), "to": .string(person.value), "name": .string(person.words)])let made = tryawait core.call(CottonMethod.sendMake, ask, as: SendMade.self)guardlet receipt = made.receipt else { return } toasts?.show(receipt.words) { [weakself] inTask { awaitself?.takeBack(made.id, receipt: receipt, core: core, toasts: toasts) } } } catch { toasts?.show(ActionRefused.words(for: error), tone: .error) } }privatefunc takeBack(_ id: String, receipt: SendReceipt, core: any CottonCalling, toasts: ToastCenter?) async {do { _ = tryawait core.call(CottonMethod.sendUndo, JSONValue.object(["id": .string(id)]), as: SendMoved.self)iflet 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.publicstructSendShell: ViewModifier {let core: any CottonCalling @Environment(\.scenePhase) privatevar scenePhasepublicinit(core: any CottonCalling) { self.core = core }publicfunc body(content: Content) -> someView { content .onChange(of: scenePhase, initial: true) { _, phase inif phase == .active { refresh() } } .onReceive(NotificationCenter.default.publisher(for: .cottonPersonalDoor)) { note inif 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? awaitTask.sleep(for: .seconds(SendKnobs.frontSeconds))guard !Task.isCancelled else { return }awaitSendCenter.session.refresh(core: core) } } }privatefunc refresh() {let core = coreTask { awaitSendCenter.session.refresh(core: core) } }}extensionView {/// The app's inbox of sends, asked as `SendShell` says.publicfunc sendShell(core: any CottonCalling) -> someView { modifier(SendShell(core: core)) }}enumSendKnobs {/// How often a copy under way is asked after.staticlet followSeconds: Double = 2/// How often the inbox is asked while the app is in front.staticlet frontSeconds: Double = 30/// The longest side a send's card is drawn at, in points.staticlet cardWidth: CGFloat = 200/// A card's height over its width, as a held card stands.staticlet cardRatio: CGFloat = 1.42}