Cotton code
159 lines · 6.6 KB · SwiftRaw
// A send drawn as the real card: the root record's face with its fields, as// the object read them off the payload (`card`), its pictures fetched through// the send before Keep (`send.picture`), and under it what the core says of// it — whom from, its state, how far its copy has come — and its acts, each// asked of the core as it said them. The thread with the sender draws it in// Messages; an app with no chat draws it on its Sent to you card.import CottonFacesimport CottonKitimport CottonPaperimport CottonValuesimport SwiftUI#if canImport(UIKit)    import ImageIO    import UIKit#endifstruct SendCard: View {    let item: SendItem    /// The card's words and acts: the item's own unless the thread's row holds newer.    var shows: SendShows? = nil    @Environment(\.cottonCore) private var core    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(\.tableDefinitions) private var definitions    private var center: SendCenter { .session }    private var said: SendShows? { shows ?? item.shows }    var body: some View {        VStack(alignment: .leading, spacing: 8) {            if let from = said?.from {                Text(from).paperMeta().accessibilityIdentifier("send-from-\(item.id)")            }            face                .frame(width: SendKnobs.cardWidth, height: SendKnobs.cardWidth * SendKnobs.cardRatio)                .clipShape(RoundedRectangle(cornerRadius: 8))                .environment(\.facePictureDrawer) { key, edge in AnyView(SendPicture(send: item.id, key: key, edge: edge)) }                .allowsHitTesting(false)                .accessibilityIdentifier("send-card-\(item.id)")            if let line = said?.line {                Text(line).paperMeta().accessibilityIdentifier("send-line-\(item.id)")            }            if let fraction = said?.progress?.fraction {                ProgressView(value: fraction).frame(width: SendKnobs.cardWidth)                    .accessibilityIdentifier("send-progress-\(item.id)")            }            acts        }        .task(id: item.copying) { if item.copying { await center.follow(item, core: core) } }        .accessibilityElement(children: .contain)    }    @ViewBuilder private var face: some View {        if let value = item.card, case .success(let card)? = DeckCard.read(RecordValue(value)), let face = FaceRegistry.face(card.face) {            face.view(card, picture: nil, taps: FaceTaps())        } else {            RoundedRectangle(cornerRadius: 8).fill(PaperDye.cream.fill)                .overlay { Text(item.title ?? "").paperTitle().padding() }        }    }    /// The core's acts in its order, the primary first as it said.    private var acts: some View {        HStack(spacing: 14) {            ForEach(said?.acts ?? []) { act in                PaperTypedButton(act.words, destructive: act.red == true) {                    Task { await center.run(act, on: item.id, core: core, toasts: toasts, open: open) }                }                .disabled(center.busy.contains(item.id))                .accessibilityIdentifier("send-\(act.id)-\(item.id)")            }        }    }    /// The record a send landed as, or the one already held, opened where its deck stands.    private func open(_ record: SendRecordRef) {        navigator?.open(table: record.table, id: record.id, definition: definitions[record.table])    }}/// A picture an offer names (its cover), fetched once through the send and/// drawn at the card's size; nothing while it comes.struct SendPicture: View {    let send: String    let key: String    let edge: CGFloat    @Environment(\.cottonCore) private var core    #if canImport(UIKit)        @State private var image: UIImage?    #endif    var body: some View {        Group {            #if canImport(UIKit)                if let image {                    Image(uiImage: image).resizable().scaledToFill()                } else {                    Color.clear                }            #else                Color.clear            #endif        }        .task(id: key) { await load() }    }    private func load() async {        #if canImport(UIKit)            guard let core else { return }            let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("send-pictures", isDirectory: true)            let ask = JSONValue.object(["id": .string(send), "key": .string(key), "dir": .string(dir.path)])            guard let path = try? await core.callJSON(CottonMethod.sendPicture, ask)["path"]?.string else { return }            image = Self.picture(at: URL(fileURLWithPath: path), edge: edge)        #endif    }    #if canImport(UIKit)        /// Decoded at the card's size by ImageIO, never the whole file into memory.        private static func picture(at file: URL, edge: CGFloat) -> UIImage? {            guard let source = CGImageSourceCreateWithURL(file as CFURL, nil),                  let drawn = CGImageSourceCreateThumbnailAtIndex(source, 0, [                      kCGImageSourceCreateThumbnailFromImageAlways: true,                      kCGImageSourceCreateThumbnailWithTransform: true,                      kCGImageSourceThumbnailMaxPixelSize: max(1, Int(edge * 3)),                  ] as CFDictionary)            else { return nil }            return UIImage(cgImage: drawn)        }    #endif}/// The Sent to you card's page, in an app with no chat tool: what was sent/// to this person, each as its real card with its acts, the newest first/// (send-walk, 13 Nov 2026: oldest first, a new arrival stood below the fold/// under the hovering fan). Messages draws them in the thread, in its order.struct SentPage: View {    @Environment(\.cottonCore) private var core    @Environment(\.scenePhase) private var scenePhase    private var center: SendCenter { .session }    var body: some View {        ScrollView {            LazyVStack(alignment: .leading, spacing: 28) {                ForEach(center.incoming.reversed()) { item in                    SendCard(item: item)                }            }            .padding(.horizontal, 16)            .padding(.vertical, 24)            .frame(maxWidth: .infinity, alignment: .leading)        }        .accessibilityIdentifier("sent-page")        .task { await center.refresh(core: core) }        .onReceive(NotificationCenter.default.publisher(for: .cottonSendArrived)) { _ in Task { await center.refresh(core: core) } }        .onChange(of: scenePhase) { _, phase in if phase == .active { Task { await center.refresh(core: core) } } }    }}