Cotton code
279 lines · 11.7 KB · SwiftRaw
// The EMAIL face (one thread; references `email.png`, `email-rich.png`, the// email cases and the house references 9/39, 10/40, 74 and 75), on the// core's places (KINDS, 0a0a099c3): an envelope — its flap folded down// across the top of the framed card to a red wax seal with a sprig. Under it// who it is from (`subtitle`) under the core's "From", a red dot when it is// unread, and the people on it as small mounts; on a dashed rule the subject// typed heavy with the day by hand at its right; the snippet a page at a// time; and on the foot's rule how many emails, under the core's own label,// and the sum the mail names (an invoice's). A thread with a picture// attached (a boarding pass) mounts it under the subject. Every word is the// core's (`DeckCard`).import CottonPaperimport CottonValuesimport SwiftUIenum EmailFaceKnobs {    static let inset = EdgeInsets(top: 0, leading: 26, bottom: 20, trailing: 24)    /// The seal picture's width as a share of the flap's.    static let sealShare: CGFloat = 0.62    /// The picture's folds: their slope, and the seal's centre in the    /// picture as shares of its width and height (`face-art-seal`).    static let foldSlope: CGFloat = 0.49    static let sealCentre = CGPoint(x: 0.503, y: 0.617)    static let sealAspect: CGFloat = 390.0 / 243.0    /// Below the seal, to the sender.    static let top: CGFloat = 12    static let fromSize: CGFloat = 16    static let subjectSize: CGFloat = 18    /// The subject's lines, and the most it shrinks to keep its words whole.    static let subjectLines = 3    static let subjectShrink: CGFloat = 0.8    static let bodySize: CGFloat = 13.5    static let bodyLeading: CGFloat = 6    static let dateHand: CGFloat = 21    static let dateTurn: Double = -3    static let footSize: CGFloat = 13    static let amountSize: CGFloat = 17    static let unread: CGFloat = 9    static let mount: CGFloat = 28    /// A mount tucked over the one before it.    static let mountTuck: CGFloat = -12    /// Between a fact and the dashed rule either side of it.    static let ruleGap: CGFloat = 10    static let rowGap: CGFloat = 10    static let pictureShare: CGFloat = 0.24    static let pictureTurn: Double = -1.5}public struct EmailFace<Picture: View>: View {    let card: DeckCard    /// A picture the thread carries (a boarding pass), filling its frame.    var picture: Picture?    @Environment(\.theme) private var theme    public init(card: DeckCard, picture: Picture?) {        self.card = card        self.picture = picture    }    public var body: some View {        GeometryReader { sheet in            VStack(alignment: .leading, spacing: 0) {                EnvelopeTop(width: sheet.size.width - 20)                    .padding(.horizontal, 10)                    .padding(.top, 10)                content(sheet.size)                    .padding(EmailFaceKnobs.inset)            }        }        .onCardPaper(EmailFaceCatalogue.stock.laid(card.pace))    }    private func content(_ size: CGSize) -> some View {        VStack(alignment: .leading, spacing: 0) {            sender                .padding(.top, EmailFaceKnobs.top)            if let subject = card.text("title") {                DashedRule()                    .padding(.vertical, EmailFaceKnobs.ruleGap)                subjectRow(subject)            }            DashedRule()                .padding(.top, EmailFaceKnobs.ruleGap)            if let picture {                MountedPrint(photo: picture)                    .frame(height: size.height * EmailFaceKnobs.pictureShare)                    .rotationEffect(.degrees(EmailFaceKnobs.pictureTurn))                    .padding(.top, EmailFaceKnobs.rowGap + 2)                    .facePart(.picture)            }            if let snippet = card.text("body").map(EmailSnippet.plain), !snippet.isEmpty {                FacePages(text: snippet, size: EmailFaceKnobs.bodySize, leading: EmailFaceKnobs.bodyLeading)                    .padding(.top, EmailFaceKnobs.rowGap + 2)                    .facePart(.body)            } else {                Spacer(minLength: 0)            }            foot        }    }    /// Who it is from under the core's "From", the unread dot before them,    /// and the people on it as small mounts at the right.    private var sender: some View {        HStack(alignment: .bottom, spacing: 8) {            VStack(alignment: .leading, spacing: FacePartsKnobs.labelGap) {                if let from = card.label("source") { FaceLabel(words: from) }                HStack(alignment: .center, spacing: 8) {                    if card.fields["unread"] == .bool(true) {                        Circle()                            .fill(theme.print(.red))                            .frame(width: EmailFaceKnobs.unread, height: EmailFaceKnobs.unread)                            .accessibilityLabel(ShellLines.line("faces", "unread"))                    }                    if let from = card.text("subtitle") {                        Text(from)                            .font(CottonFonts.type(EmailFaceKnobs.fromSize))                            .lineLimit(1)                            .minimumScaleFactor(EmailFaceKnobs.subjectShrink)                            .faceInk(.ink)                            .facePart(.subtitle)                    }                }            }            .layoutPriority(1)            Spacer(minLength: 4)            HStack(spacing: 0) {                ForEach(Array(card.entries("people").enumerated()), id: \.offset) { index, entry in                    FaceMount(name: entry["name"]?.text ?? "", picture: entry["picture"]?.text, size: EmailFaceKnobs.mount)                        .padding(.leading, index == 0 ? 0 : EmailFaceKnobs.mountTuck)                }            }            .facePart(.people)            if let more = card.text("people_more") { footWords(more) }        }    }    /// The subject typed heavy, its words whole on its lines, and the day    /// written by hand at its right.    private func subjectRow(_ subject: String) -> some View {        HStack(alignment: .firstTextBaseline, spacing: 12) {            HeavyType(words: subject, size: EmailFaceKnobs.subjectSize)                .lineLimit(EmailFaceKnobs.subjectLines)                .minimumScaleFactor(EmailFaceKnobs.subjectShrink)                .fixedSize(horizontal: false, vertical: true)                .frame(maxWidth: .infinity, alignment: .leading)                .accessibilityIdentifier("deck-title")                .facePart(.title)            if let day = card.text("date") {                Text(HandRun.tail(day))                    .font(CottonFonts.hand(EmailFaceKnobs.dateHand))                    .lineLimit(1)                    .fixedSize()                    .faceInk(.ink)                    .rotationEffect(.degrees(EmailFaceKnobs.dateTurn))                    .facePart(.when)            }        }    }    /// On the foot's rule: how many emails under the core's label, once    /// there is more than the one on the card, and the sum the mail names.    @ViewBuilder private var foot: some View {        let count = card.text("count").flatMap { (Int($0.filter(\.isNumber)) ?? 2) > 1 ? $0 : nil }        let amount = card.text("amount")        if count != nil || amount != nil {            DashedRule()                .padding(.top, EmailFaceKnobs.ruleGap)            HStack(alignment: .firstTextBaseline, spacing: 10) {                if let count {                    if let label = card.label("count") { FaceLabel(words: label) }                    footWords(count)                }                Spacer(minLength: 8)                if let amount {                    Text(amount)                        .font(CottonFonts.type(EmailFaceKnobs.amountSize))                        .lineLimit(1)                        .faceInk(.ink)                        .facePart(.amount)                }            }            .padding(.top, EmailFaceKnobs.ruleGap - 2)        }    }    private func footWords(_ words: String) -> some View {        Text(words)            .font(CottonFonts.type(EmailFaceKnobs.footSize))            .lineLimit(1)            .faceInk(.ink)    }}public enum EmailSnippet {    /// The snippet without a mail's stand-ins for what it could not carry    /// (`[image: Google]`, the plain part of an HTML mail), and the blank    /// lines they leave.    public static func plain(_ snippet: String) -> String {        snippet            .replacingOccurrences(of: #"\[image:[^\]]*\]"#, with: "", options: .regularExpression)            .replacingOccurrences(of: #"\n[ \t]*\n([ \t]*\n)+"#, with: "\n\n", options: .regularExpression)            .trimmingCharacters(in: .whitespacesAndNewlines)    }}/// The envelope's flap folded down to the wax seal: the drawn folds meet at/// the seal's centre along the picture's own folds, so the two are one line.struct EnvelopeTop: View {    let width: CGFloat    @Environment(\.theme) private var theme    static func depth(width: CGFloat) -> CGFloat { EmailFaceKnobs.foldSlope * width / 2 }    var body: some View {        let depth = Self.depth(width: width)        let art = width * EmailFaceKnobs.sealShare        let artHeight = art / EmailFaceKnobs.sealAspect        let below = artHeight * (1 - EmailFaceKnobs.sealCentre.y)        ZStack(alignment: .topLeading) {            EnvelopeFlap()                .fill(theme.colors.shadow.color.opacity(0.05))                .frame(width: width, height: depth)            EnvelopeFlap()                .stroke(theme.print(.pencil).opacity(0.4), lineWidth: 0.9)                .frame(width: width, height: depth)            FaceArt(name: "face-art-seal")                .frame(width: art, height: artHeight)                .offset(x: width / 2 - art * EmailFaceKnobs.sealCentre.x, y: depth - artHeight * EmailFaceKnobs.sealCentre.y)        }        .frame(width: width, height: depth + below, alignment: .topLeading)        .blendMode(theme.printBlend)    }}/// An envelope's flap folded down: the top edge and the two folds meeting/// at the middle.struct EnvelopeFlap: Shape {    func path(in rect: CGRect) -> Path {        var path = Path()        path.move(to: CGPoint(x: rect.minX, y: rect.minY))        path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))        path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))        return path    }}/// The email face, by the kind's name, and the cards it is reviewed in.public enum EmailFaceCatalogue {    public static let stock: FaceStock = .framed    public static let ground: FaceGround = .paper    public static let face = Face(id: "email", specimens: [Specimen("contract-note", contractNote), Specimen("offers", offers)]) { card, picture, _ in        EmailFace(card: card, picture: picture)    }    public static let contractNote = DeckCard(face: .email, fields: [        "subtitle": .text("Priya at Example Broking"),        "title": .text("Your contract note for 22 Oct"),        "date": .text("Thu 22 Oct"),        "body": .text("Your contract note is ready. Please find the details attached. Thank you for trading with us."),        "count": .text("3"),        "unread": .bool(true),        "amount": .text("\u{20B9}499"),        "people": .list([            .object(["name": .text("Priya Example")]),            .object(["name": .text("Arjun Rao")]),        ]),    ])    public static let offers = DeckCard(face: .email, fields: [        "subtitle": .text("Offers at Some Shop"),        "title": .text("70 percent off today only"),        "date": .text("Thu 22 Oct"),        "body": .text("Save 70 percent on your favourites. Today only, shop before midnight. Discover our latest offers in store."),        "count": .text("1,204"),        "unread": .bool(false),    ])}