Cotton code
222 lines · 10.2 KB · SwiftRaw
// Messages as the chat's own slips, bare on its blotter. No data is read// here: missing times, senders, unread count or subject stay absent.import CottonPaperimport CottonValuesimport SwiftUI/// The last six messages, oldest first. A card with no local history uses/// its preview: an unassigned cream slip with no invented metadata.public enum ThreadSlipsReading {    public struct Slip: Identifiable, Equatable, Sendable {        public let id: String        public let words: String        /// Nil for a preview whose card does not say who wrote it.        public let mine: Bool?        public let time: String?        public let sender: String?        init(_ line: ThreadHistory.Line) {            id = line.id; words = line.words; mine = line.mine            time = line.time; sender = line.sender        }        init(preview: String) {            id = "last-preview"; words = preview; mine = nil            time = nil; sender = nil        }    }    public static func lines(_ card: DeckCard) -> [Slip] {        var lines = (card.thread?.earlier ?? []).suffix(5).map(Slip.init)        if let last = card.thread?.last {            lines.append(Slip(last))        } else if let words = card.text("body") {            lines.append(Slip(preview: words))        }        return lines    }}/// Keep the whole message window before giving up a slip: the chat's/// paper and type stay at their own size; only the air between slips closes.private struct SlipsFit: Identifiable {    let count: Int    let gap: CGFloat    var id: String { "\(count)-\(gap)" }    static let choices = [6, 5, 4, 3, 2, 1].flatMap { count in        [CGFloat(12), 6, 0].map { SlipsFit(count: count, gap: $0) }    }}public struct ThreadSlipsFace<Portrait: View>: View {    let card: DeckCard    let portrait: Portrait?    @Environment(\.theme) private var theme    public init(card: DeckCard, portrait: Portrait?) {        self.card = card        self.portrait = portrait    }    public var body: some View {        GeometryReader { box in            VStack(alignment: .leading, spacing: 0) {                head                if let subject = card.text("subject") {                    Text(subject).font(CottonFonts.type(12)).foregroundStyle(lightInk)                        .fixedSize(horizontal: false, vertical: true)                        .padding(.top, 6).facePart(.subtitle)                }                // Close the air before dropping a whole earlier slip.                // The shared paper's size and the words never shrink.                ViewThatFits(in: .vertical) {                    ForEach(SlipsFit.choices) { fit in                        slips(fit.count, width: box.size.width, gap: fit.gap)                    }                }                .padding(.top, 14)                .frame(maxHeight: .infinity, alignment: .top)            }            .padding(.horizontal, 6)            .padding(.top, 10)            .padding(.bottom, 6)        }    }    private var lightInk: Color { theme.sheet(.cream) }    private var group: Bool { !card.entries("people").isEmpty }    private var head: some View {        HStack(spacing: 10) {            if group {                HStack(spacing: -8) {                    ForEach(Array(card.entries("people").prefix(3).enumerated()), id: \.offset) { _, person in                        FaceMount(name: person["name"]?.text ?? "", picture: person["picture"]?.text, size: 28, typed: true)                    }                }.facePart(.people)            } else {                Group {                    if let portrait { portrait } else { InitialsMount(name: card.text("title") ?? "", typed: true) }                }                .frame(width: 44, height: 44).clipShape(Circle())                .overlay(Circle().stroke(lightInk, lineWidth: 1))                .facePart(.picture)            }            if let name = card.text("title") {                Text(name).font(CottonFonts.caslon(24)).foregroundStyle(lightInk)                    .lineLimit(2).minimumScaleFactor(0.8)                    .accessibilityIdentifier("deck-title").facePart(.title)            }            if let unread = card.corner {                Text(unread).font(CottonFonts.signature(20)).foregroundStyle(lightInk)                    .lineLimit(1).fixedSize().facePart(.corner)            }        }        .fixedSize(horizontal: false, vertical: true)    }    private func slips(_ count: Int, width: CGFloat, gap: CGFloat) -> some View {        VStack(spacing: gap) {            ForEach(Array(ThreadSlipsReading.lines(card).suffix(count))) { line in                VStack(alignment: line.mine == true ? .trailing : .leading, spacing: 3) {                    if group, let sender = line.sender {                        Text(sender.uppercased()).font(CottonFonts.type(10))                            .foregroundStyle(lightInk).lineLimit(1)                    }                    ChatSlip(seed: line.id, dye: line.mine == true ? .blue : .cream) {                        Text(line.words).paperBody(15).lineSpacing(3)                            .fixedSize(horizontal: false, vertical: true)                    }                    if let time = line.time {                        Text(time).font(CottonFonts.signature(18)).foregroundStyle(lightInk)                            .lineLimit(1).padding(.horizontal, 4)                    }                }                .frame(maxWidth: max(1, (width - 12) * 0.80), alignment: line.mine == true ? .trailing : .leading)                .frame(maxWidth: .infinity, alignment: line.mine == true ? .trailing : .leading)            }        }        .fixedSize(horizontal: false, vertical: true)        .facePart(.body)    }}public enum ThreadSlipsFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .pegboard    public static let face = Face(id: "thread.slips", specimens: [        Specimen("pair", pair, picture: "rolodex-ananya"),        Specimen("group", group),        Specimen("no-picture", pair),        Specimen("group-no-pictures", groupNoPictures),        Specimen("email", email, picture: "invitation-guest-a"),        Specimen("one-message", one, picture: "rolodex-friend"),        Specimen("six", six, picture: "rolodex-friend"),        Specimen("long", long, picture: "rolodex-ananya"),    ], steps: .cut) { card, picture, _ in        ThreadSlipsFace(card: card, portrait: picture)    }    private static func card(_ name: String, _ lines: [ThreadHistory.Line], corner: String? = nil,                             subject: String? = nil, people: [RecordValue] = []) -> DeckCard {        var fields: [String: RecordValue] = ["title": .text(name), "people": .list(people)]        if let subject { fields["subject"] = .text(subject) }        if let last = lines.last { fields["body"] = .text(last.words) }        var card = DeckCard(face: "thread.slips", corner: corner, pressing: false, pace: nil, plate: nil, fields: fields)        card.thread = ThreadHistory(earlier: Array(lines.dropLast()), last: lines.last)        return card    }    public static let pair = card("Ananya Rao", [        .init(id: "slips-pair-1", words: "All clear. Bringing the lemon rice", mine: false, time: "11:06 am"),        .init(id: "slips-pair-2", words: "Perfect, I'll do the salad", mine: true, time: "11:40 am"),        .init(id: "slips-pair-3", words: "Call me when free", mine: false, time: "12:01 pm"),        .init(id: "slips-pair-4", words: "See you at 8?", mine: false, time: "12:06 pm"),    ], corner: "14 unread")    public static let group = card("Flat 4B", [        .init(id: "slips-group-1", words: "The key is with me", mine: false, time: "9:12 am", sender: "Tara"),        .init(id: "slips-group-2", words: "I'll bring tea", mine: true, time: "9:14 am", sender: "You"),        .init(id: "slips-group-3", words: "Bread is ready", mine: false, time: "9:16 am", sender: "Dev"),        .init(id: "slips-group-4", words: "Meet downstairs?", mine: false, time: "9:20 am", sender: "Nila"),    ], people: [        .object(["name": .text("Tara"), "picture": .text("invitation-guest-a")]),        .object(["name": .text("Dev"), "picture": .text("rolodex-friend")]),        .object(["name": .text("Nila"), "picture": .text("rolodex-ananya")]),    ])    public static var groupNoPictures: DeckCard {        var card = group        card.fields["people"] = .list(card.entries("people").map { entry in            var person = entry            person["picture"] = .text("")            return .object(person)        })        return card    }    public static let email = card("Tara Sen", [        .init(id: "slips-email-1", words: "The blue room is free on Sunday.", mine: false, time: "10:04 am"),        .init(id: "slips-email-2", words: "Lovely. I'll bring the drawings.", mine: true, time: "10:28 am"),    ], subject: "Sunday's drawing class")    public static let one = card("Dev Shah", [        .init(id: "slips-one", words: "The kettle is on.", mine: false, time: "8:05 am"),    ])    public static let six = card("Dev Shah", [        .init(id: "slips-six-1", words: "Tea?", mine: false, time: "8:01 am"),        .init(id: "slips-six-2", words: "Yes", mine: true, time: "8:02 am"),        .init(id: "slips-six-3", words: "At mine?", mine: false, time: "8:03 am"),        .init(id: "slips-six-4", words: "Sure", mine: true, time: "8:04 am"),        .init(id: "slips-six-5", words: "Ready", mine: false, time: "8:05 am"),        .init(id: "slips-six-6", words: "Coming", mine: true, time: "8:06 am"),    ])    public static let long = card("Ananya Rao", [        .init(id: "slips-long-1", words: "All set", mine: false, time: "5:10 pm"),        .init(id: "slips-long-2", words: "On my way", mine: true, time: "5:12 pm"),        .init(id: "slips-long-3", words: "Take your time", mine: false, time: "5:14 pm"),        .init(id: "slips-long-4", words: "Bring the blue book\nand the little map\nfrom the kitchen.\nThe path by the lake\nis closed this evening,\nso take the long way\npast the old station.\nI will wait by the gate\nwith the picnic basket.\nThere is no need to rush.\nThe evening train\nwill not leave until\nwe have found our seats\nand put the bags away.", mine: false, time: "5:18 pm"),    ])}