Cotton code
590 lines · 24.4 KB · SwiftRaw
// mail.html's pieces, drawn once for every Post screen: the rule, the bar, the title, a band's heading, the faces// (people round, machines square), the mail row with its two swipes and its long press, the buttons, the chips, the// after-state that stays until he leaves the page, and the empty and refused lines. Nothing here decides a word.#if os(iOS)import CottonKitimport SwiftUIimport UIKit/// A 1 px rule across.struct PostRule: View {    var body: some View { Rectangle().fill(PostInk.rule).frame(height: PostInk.hair) }}/// `.ph h3`: a screen's title, in the reading face.struct PostTitle: View {    let text: String    var body: some View {        Text(text)            .font(PostType.title)            .foregroundStyle(PostInk.ink)            .fixedSize(horizontal: false, vertical: true)            .padding(.top, 6)            .padding(.bottom, 2)            .accessibilityAddTraits(.isHeader)    }}/// `.lead`: the line under a title.struct PostLead: View {    let text: String    var body: some View {        Text(text).font(PostType.sans(16)).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true).padding(.top, 4)    }}/// `.ph h4`: a band's heading, with what it counts at the end.struct PostSection: View {    let title: String    var end: String?    var body: some View {        HStack(alignment: .firstTextBaseline, spacing: 8) {            Text(title).font(PostType.section).foregroundStyle(PostInk.quiet)            Spacer(minLength: 8)            if let end, !end.isEmpty { Text(end).font(PostType.sans(13, .medium, relativeTo: .footnote)).foregroundStyle(PostInk.quiet) }        }        .padding(.top, 22)        .padding(.bottom, 4)        .accessibilityElement(children: .combine)        .accessibilityAddTraits(.isHeader)    }}/// `.note`: a quiet line.struct PostNote: View {    let text: String    var body: some View {        Text(text).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true).padding(.top, 12)    }}/// The core's words for why a screen could not be read, where the screen's content would stand.struct PostRefused: View {    let line: String    var body: some View {        Text(line)            .font(PostType.body)            .foregroundStyle(PostInk.quiet)            .fixedSize(horizontal: false, vertical: true)            .frame(maxWidth: .infinity, alignment: .leading)            .padding(.vertical, 18)            .accessibilityIdentifier("post-refused")    }}/// The franking mark: three wavy cancellation lines, as on a posted stamp. It draws itself when a mail truly leaves,/// and rests faintly on an empty Inbox; with reduced motion on, it simply appears.struct PostFranking: View {    var width: CGFloat = 84    var ink: Color = PostInk.accent    var draws = false    @State private var drawn: CGFloat = 0    @Environment(\.accessibilityReduceMotion) private var reduceMotion    var body: some View {        Canvas { context, size in            for line in 0..<3 {                var path = Path()                let y = size.height * (0.2 + 0.3 * CGFloat(line))                let wave = size.height * 0.09                path.move(to: CGPoint(x: 0, y: y))                let steps = 4                for step in 0..<steps {                    let x0 = size.width * CGFloat(step) / CGFloat(steps)                    let x1 = size.width * CGFloat(step + 1) / CGFloat(steps)                    path.addCurve(to: CGPoint(x: x1, y: y),                                  control1: CGPoint(x: x0 + (x1 - x0) / 3, y: y - wave),                                  control2: CGPoint(x: x0 + 2 * (x1 - x0) / 3, y: y + wave))                }                context.stroke(path.trimmedPath(from: 0, to: draws ? drawn : 1), with: .color(ink), style: StrokeStyle(lineWidth: max(1.6, size.height * 0.08), lineCap: .round))            }        }        .frame(width: width, height: width * 0.36)        .onAppear {            guard draws else { return }            if reduceMotion { drawn = 1 } else { withAnimation(.easeOut(duration: 0.7)) { drawn = 1 } }        }        .accessibilityHidden(true)    }}/// A face: a person round with an ink ring, a machine square with a faint one, each with its initials.struct PostFace: View {    let from: PostFrom    var size: CGFloat = 36    /// The face grows a little with the phone's text, never past 1.5 times, its initials always inside it.    @ScaledMetric(relativeTo: .body) private var grow: CGFloat = 1    var body: some View {        let person = from.isPerson        let size = self.size * min(grow, 1.5)        Text(from.shownInitials)            .font(Font(PostFonts.ui(.sans, size * 0.39, weight: person ? 700 : 600)))            .foregroundStyle(person ? PostInk.ink : PostInk.quiet)            .lineLimit(1)            .minimumScaleFactor(0.6)            .frame(width: size, height: size)            .background {                if person {                    Circle().strokeBorder(PostInk.ink, lineWidth: 1.3)                } else {                    RoundedRectangle(cornerRadius: size / 4, style: .continuous).strokeBorder(PostInk.faint, lineWidth: 1.3)                }            }            .accessibilityHidden(true)    }}/// `.r`: one mail. Unread is bold with an ink dot, never the accent; a tag shows only where the mail came to an address/// other than his usual one. Swipe right for Read or Unread, left for Archive (never Delete, Block or Unsubscribe); a/// long press holds the rest.struct PostRowView<Menu: View>: View {    let row: PostRow    var last = false    var face = true    var open: () -> Void    var swipeRight: (() -> Void)?    var swipeLeft: (() -> Void)?    @ViewBuilder var menu: () -> Menu    @State private var dx: CGFloat = 0    @Environment(\.dynamicTypeSize) private var type    private let reach: CGFloat = 84    var body: some View {        ZStack {            // What a swipe will do, under the row as it moves.            HStack {                if dx > 0 { swipeWord(row.unread ? PostWords.line("act.read") : PostWords.line("act.unread")) }                Spacer()                if dx < 0 { swipeWord(PostWords.line("act.archive")) }            }            .opacity(min(1, abs(dx) / reach))            Button(action: open) { content }                .buttonStyle(PostPressStyle())                .offset(x: dx)                .contextMenu { menu() }        }        .simultaneousGesture(swipeRight == nil && swipeLeft == nil ? nil : DragGesture(minimumDistance: 24)            .onChanged { drag in                guard abs(drag.translation.width) > abs(drag.translation.height) * 1.4 else { return }                let x = drag.translation.width                dx = x > 0 ? (swipeRight == nil ? 0 : min(x, reach * 1.4)) : (swipeLeft == nil ? 0 : max(x, -reach * 1.4))            }            .onEnded { _ in                let done = dx                withAnimation(.easeOut(duration: 0.2)) { dx = 0 }                if done >= reach { swipeRight?() } else if done <= -reach { swipeLeft?() }            })        .accessibilityElement(children: .combine)        .accessibilityLabel(Text(spoken))        .accessibilityAddTraits(.isButton)        .accessibilityActions {            if let swipeRight { Button(row.unread ? PostWords.line("act.read") : PostWords.line("act.unread"), action: swipeRight) }            if let swipeLeft { Button(PostWords.line("act.archive"), action: swipeLeft) }        }        .accessibilityIdentifier("post-row-\(row.id)")    }    private var spoken: String {        ([row.from.name, row.subject, row.line, row.when].compactMap { $0 } + (row.a11y ?? [])).joined(separator: ", ")    }    private func swipeWord(_ text: String) -> some View {        Text(text).font(PostType.sans(14, .semibold)).foregroundStyle(PostInk.quiet).padding(.horizontal, 6)    }    @ViewBuilder private var content: some View {        if type.isAccessibilitySize { stacked } else { across }    }    /// At the largest sizes the row stands in lines rather than clipping: who, what, then when.    private var stacked: some View {        VStack(alignment: .leading, spacing: 4) {            HStack(spacing: 8) {                if row.unread { Circle().fill(PostInk.ink).frame(width: 8, height: 8) }                Text(row.from.name).font(row.unread ? PostType.rowName : PostType.rowRead).foregroundStyle(PostInk.ink).lineLimit(2)            }            secondLine(lines: 3)            HStack(spacing: 8) {                if let act = row.act { Text(act).font(PostType.sans(14, .semibold)).foregroundStyle(PostInk.quiet) }                if let when = row.when { Text(when).font(PostType.end).foregroundStyle(PostInk.quiet) }                if let tag = row.account?.tag { PostTag(text: tag) }                if let mark = row.mark { PostTag(text: mark) }                if (row.attachments ?? 0) > 0 { Image(systemName: "paperclip").foregroundStyle(PostInk.quiet) }            }        }        .padding(.vertical, 12)        .frame(maxWidth: .infinity, alignment: .leading)        .contentShape(Rectangle())        .background(PostInk.ground)        .overlay(alignment: .bottom) { if !last { PostRule() } }    }    private var across: some View {        HStack(alignment: .center, spacing: 12) {            if face { PostFace(from: row.from) }            VStack(alignment: .leading, spacing: 2) {                HStack(spacing: 7) {                    if row.unread { Circle().fill(PostInk.ink).frame(width: 7, height: 7) }                    Text(row.from.name)                        .font(row.unread ? PostType.rowName : PostType.rowRead)                        .foregroundStyle(PostInk.ink)                        .lineLimit(1)                    if row.count > 1 {                        Text("\(row.count)").font(PostType.sans(13, relativeTo: .footnote)).foregroundStyle(PostInk.quiet)                    }                    if let tag = row.account?.tag { PostTag(text: tag) }                    if let mark = row.mark { PostTag(text: mark) }                }                secondLine(lines: 1)            }            Spacer(minLength: 8)            VStack(alignment: .trailing, spacing: 4) {                if let act = row.act {                    Text(act).font(PostType.sans(14, .semibold)).foregroundStyle(PostInk.quiet)                } else if let when = row.when {                    Text(when).font(PostType.end).foregroundStyle(PostInk.quiet).lineLimit(1)                }                if (row.attachments ?? 0) > 0 {                    Image(systemName: "paperclip").font(.system(size: 12, weight: .regular)).foregroundStyle(PostInk.quiet)                }            }        }        .padding(.vertical, 11)        .frame(maxWidth: .infinity, alignment: .leading)        .contentShape(Rectangle())        .background(PostInk.ground)        .overlay(alignment: .bottom) { if !last { PostRule() } }    }    /// `.r .s`: the subject in ink when unread, then its line, quiet.    private func secondLine(lines: Int) -> some View {        var words = AttributedString(row.subject)        words.foregroundColor = row.unread ? PostInk.ink : PostInk.quiet        words.font = row.unread ? PostType.sans(14, .semibold, relativeTo: .footnote) : PostType.small        if let line = row.line, !line.isEmpty {            var rest = AttributedString(" · \(line)")            rest.foregroundColor = row.unread ? PostInk.quiet : PostInk.faint            rest.font = PostType.small            words += rest        }        return Text(words).lineLimit(lines)    }}extension PostRowView where Menu == EmptyView {    init(row: PostRow, last: Bool = false, face: Bool = true, open: @escaping () -> Void) {        self.init(row: row, last: last, face: face, open: open, swipeRight: nil, swipeLeft: nil, menu: { EmptyView() })    }}/// A row that dims a little while pressed and never moves.struct PostPressStyle: ButtonStyle {    func makeBody(configuration: Configuration) -> some View {        configuration.label.opacity(configuration.isPressed ? 0.6 : 1)    }}/// `.tag`: a small outlined word ("studio", "Draft").struct PostTag: View {    let text: String    var body: some View {        Text(text)            .font(PostType.sans(11.5, .medium, relativeTo: .caption2))            .foregroundStyle(PostInk.quiet)            .lineLimit(1)            .padding(.horizontal, 6)            .padding(.vertical, 1)            .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(PostInk.rule, lineWidth: 1))    }}/// `.r.plain`: a row of words with its end, opening something.struct PostLinkRow: View {    let title: String    var line: String?    var end: String?    var last = false    var chevron = true    var id: String?    let action: () -> Void    var body: some View {        Button(action: action) {            HStack(alignment: .center, spacing: 12) {                VStack(alignment: .leading, spacing: 2) {                    Text(title).font(PostType.sans(16.5, .medium)).foregroundStyle(PostInk.ink).fixedSize(horizontal: false, vertical: true)                    if let line, !line.isEmpty {                        Text(line).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true)                    }                }                Spacer(minLength: 8)                if let end, !end.isEmpty {                    Text(end).font(PostType.end).foregroundStyle(PostInk.quiet).multilineTextAlignment(.trailing)                }                if chevron { Image(systemName: "chevron.right").font(.system(size: 13, weight: .regular)).foregroundStyle(PostInk.quiet) }            }            .padding(.vertical, 12)            .frame(maxWidth: .infinity, alignment: .leading)            .contentShape(Rectangle())            .overlay(alignment: .bottom) { if !last { PostRule() } }        }        .buttonStyle(PostPressStyle())        .accessibilityIdentifier(id ?? "post-link-\(title)")    }}/// `.btn`: the one accent button on a screen (`go`), an outlined one, or a quiet one.struct PostButton: View {    enum Weight { case go, outline, quiet }    let label: String    var line: String?    var weight: Weight = .outline    var id: String?    let action: () -> Void    var body: some View {        Button(action: action) {            VStack(spacing: 1) {                Text(label).font(PostType.button)                if let line { Text(line).font(PostType.sans(12, .medium, relativeTo: .caption)) }            }            .multilineTextAlignment(.center)            .foregroundStyle(weight == .go ? PostInk.onAccent : PostInk.ink)            .padding(.horizontal, 14)            .padding(.vertical, 8)            .frame(maxWidth: .infinity, minHeight: 50)            .background(RoundedRectangle(cornerRadius: 16, style: .continuous).fill(weight == .go ? PostInk.accent : .clear))            .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous)                .strokeBorder(weight == .go ? PostInk.accent : weight == .quiet ? PostInk.rule : PostInk.ink, lineWidth: PostInk.stroke))            .contentShape(Rectangle())        }        .buttonStyle(PostPressStyle())        .accessibilityIdentifier(id ?? "post-button-\(label)")    }}/// A word that acts, in the accent ("Undo", "See the rules") or in ink.struct PostWordButton: View {    let label: String    var accent = true    var id: String?    let action: () -> Void    var body: some View {        Button(action: action) {            Text(label)                .font(PostType.sans(15, .bold))                .foregroundStyle(accent ? PostInk.accent : PostInk.ink)                .padding(.vertical, 6)                .contentShape(Rectangle())        }        .buttonStyle(PostPressStyle())        .accessibilityIdentifier(id ?? "post-word-\(label)")    }}/// A chip: chosen in ink with a 1.5 px ring, the rest quiet on a rule.struct PostChip: View {    let label: String    let on: Bool    var id: String?    /// Its unread count, said quietly after the label (Mail's chips); none when nil.    var count: String? = nil    let action: () -> Void    var body: some View {        Button(action: action) {            HStack(spacing: 5) {                Text(label)                    .font(PostType.sans(15, on ? .bold : .regular, relativeTo: .subheadline))                    .foregroundStyle(on ? PostInk.ink : PostInk.quiet)                if let count {                    Text(count).font(PostType.sans(13.5, relativeTo: .caption)).foregroundStyle(PostInk.quiet)                }            }                .lineLimit(1)                .fixedSize()                .padding(.horizontal, 12)                .padding(.vertical, 7)                .overlay(Capsule().strokeBorder(on ? PostInk.ink : PostInk.rule, lineWidth: on ? PostInk.stroke : 1))                .contentShape(Capsule())        }        .buttonStyle(PostPressStyle())        .accessibilityElement(children: .combine)        .accessibilityAddTraits(on ? [.isButton, .isSelected] : .isButton)        .accessibilityIdentifier(id ?? "post-chip-\(label)")    }}/// `.bar`: Back with the screen it returns to, and words that act at the end.struct PostBar<End: View>: View {    var back: String?    var onBack: (() -> Void)?    @ViewBuilder var end: () -> End    var body: some View {        HStack(spacing: 10) {            if let back, let onBack {                Button(action: onBack) {                    HStack(spacing: 2) {                        Image(systemName: "chevron.left").font(.system(size: 17, weight: .regular))                        Text(back).font(PostType.sans(16)).lineLimit(1)                    }                    .foregroundStyle(PostInk.ink)                    .frame(minHeight: 44)                    .contentShape(Rectangle())                }                .buttonStyle(PostPressStyle())                .accessibilityIdentifier("post-back")            }            Spacer(minLength: 8)            end()        }        .frame(minHeight: 44)    }}extension PostBar where End == EmptyView {    init(back: String?, onBack: (() -> Void)?) {        self.init(back: back, onBack: onBack, end: { EmptyView() })    }}/// The after-state: what an act really did, with Undo, and his mailbox's line under it. It stays on screen until he/// leaves the page or acts again; it is never a toast that goes. A ruled band in ink, the one accent its Undo.struct PostAfterView: View {    let model: PostModel    @Binding var after: PostAfter?    @State private var refused: String?    var body: some View {        if let shown = after {            VStack(alignment: .leading, spacing: 4) {                Rectangle().fill(PostInk.accent).frame(height: 1.5)                Text(shown.line).font(PostType.sans(16, .bold)).foregroundStyle(PostInk.ink).padding(.top, 10)                if let mailbox = shown.mailbox {                    HStack(alignment: .firstTextBaseline, spacing: 6) {                        Image(systemName: mailbox.state == "done" ? "checkmark" : mailbox.state == "failed" ? "exclamationmark.triangle" : "clock")                            .font(.system(size: 12))                        Text(mailbox.line).font(PostType.small).fixedSize(horizontal: false, vertical: true)                    }                    .foregroundStyle(mailbox.state == "failed" ? PostInk.ink : PostInk.quiet)                }                if let refused { Text(refused).font(PostType.small).foregroundStyle(PostInk.quiet) }                HStack(spacing: 18) {                    if let undo = shown.undo {                        PostWordButton(label: undo, id: "post-after-undo") {                            Task {                                switch await model.undo(shown) {                                case .read(let undone): after = undone                                case .refused(let line): refused = line                                }                            }                        }                    }                    if let retry = shown.mailbox?.retry {                        PostWordButton(label: retry, accent: false, id: "post-after-retry") {                            Task { if let again = await model.again(shown) { after = again } }                        }                    }                }                .padding(.top, 2)            }            .padding(.bottom, 10)            .overlay(alignment: .bottom) { PostRule() }            .accessibilityElement(children: .contain)            .accessibilityIdentifier("post-after")            // While his mailbox has not caught up, the line is read again, so "will follow" turns into "Also archived".            .task(id: shown.after) {                var now = shown                for _ in 0..<12 where now.mailbox?.state == "waiting" {                    try? await Task.sleep(for: .seconds(5))                    guard let again = await model.again(now) else { return }                    now = again                    if after?.after == again.after { after = again }                }            }        }    }}/// The empty state of a place: a fact, not a party. The franking mark rests over an empty Inbox.struct PostEmpty: View {    let line: String    var franked = false    /// While his mail is still coming: Account's count under the line ("Syncing 1,200 of 3,108") and its thin bar.    var first: PostFirstSync? = nil    var body: some View {        VStack(spacing: 14) {            if franked { PostFranking(width: 84, ink: PostInk.accent.opacity(0.85)) }            // A slow or missed answer while his mail is coming keeps the loading words and the count; the miss is the            // small line under them, never the headline (the owner, 26 Nov 2026).            let headline = first.flatMap { $0.state == "unreached" && line == $0.line ? $0.bringing : nil } ?? line            Text(headline)                .font(PostType.serif(22, .medium, relativeTo: .title2))                .foregroundStyle(PostInk.ink)                .multilineTextAlignment(.center)                .fixedSize(horizontal: false, vertical: true)            if let seen = first?.seen, let count = seen.line, !count.isEmpty, count != headline {                Text(count)                    .font(PostType.sans(14, relativeTo: .subheadline))                    .foregroundStyle(PostInk.quiet)                    .multilineTextAlignment(.center)                if let percent = seen.percent {                    ProgressView(value: Double(min(max(percent, 0), 100)), total: 100)                        .tint(PostInk.accent)                        .frame(maxWidth: 180)                        .accessibilityHidden(true)                }            }            if let trying = first?.trying, headline != line {                Text(trying)                    .font(PostType.small)                    .foregroundStyle(PostInk.quiet)                    .multilineTextAlignment(.center)            }        }        .frame(maxWidth: .infinity)        .padding(.vertical, 60)        .accessibilityElement(children: .combine)        .accessibilityIdentifier("post-empty")    }}/// A file's kind as its extension, in a small outlined page.struct PostFileMark: View {    let name: String    var body: some View {        let ext = (name as NSString).pathExtension.uppercased()        Text(ext.isEmpty ? "—" : String(ext.prefix(4)))            .font(PostType.sans(9, .bold, relativeTo: .caption2))            .foregroundStyle(PostInk.ink)            .frame(width: 34, height: 40, alignment: .bottom)            .padding(.bottom, 4)            .overlay(RoundedRectangle(cornerRadius: 5).strokeBorder(PostInk.ink, lineWidth: 1.2))            .accessibilityHidden(true)    }}/// A row of chips that scrolls across when it does not fit.struct PostChips<Content: View>: View {    /// The chip chosen (its `.id`), scrolled into view when the row appears and when it changes: a kept choice far    /// along the row is seen on the next launch.    var selected: String? = nil    @ViewBuilder var content: () -> Content    var body: some View {        ScrollViewReader { proxy in            ScrollView(.horizontal, showsIndicators: false) {                HStack(spacing: 8) { content() }.padding(.horizontal, PostInk.side).padding(.vertical, 2)            }            .onAppear { if let selected { proxy.scrollTo(selected, anchor: .center) } }            .onChange(of: selected) { _, now in if let now { withAnimation { proxy.scrollTo(now, anchor: .center) } } }        }        .padding(.horizontal, -PostInk.side)    }}#endif