Cotton code
498 lines · 20.8 KB · SwiftRaw
// The DOCUMENT face (Documents, references `documents.png` and// `documents-bill.png`): the cream card in its notched frame with the// document's first page clipped to it by a paperclip at its top left, turned// a hair. A page wider than tall (a card, an ID) lies across the top with the// words under it; a page taller than wide (a bill, a letter) stands at the// left, its tag and title beside it, the house watercolour at the foot. The words: the group the// document stands in on a torn paper tag, the title typed heavy, then — each// on its dashed rule — the kind and page count, when it was received in the// hand, and who it is from, each phrased line's words ("Received", "From")// set small in pencil as its label; its state ("Not read yet") stamped in// red. A document whose bytes are not on this phone shows a// blank page with typed lines, so the card never waits. Tapping the page// opens the reader. Every word is the core's (`DeckCard`).import CottonPaperimport CottonValuesimport SwiftUIpublic enum DocumentFaceKnobs {    /// The most a title beside the standing page holds before it takes the    /// card's width, and the longest word that column can wrap.    static let columnMostCharacters = 44    static let columnLongestWord = 11    /// The standing page's most height, as a share of the card's, with the    /// title under it.    static let standingShareUnderTitle: CGFloat = 0.46    static let inset = EdgeInsets(top: 26, leading: 22, bottom: 22, trailing: 22)    /// A page at least this much wider than tall lies across the card.    static let wide: CGFloat = 1.15    /// A standing page's share of the card's width.    static let standingShare: CGFloat = 0.6    static let pageTurn: Double = -1.6    static let clip = CGSize(width: 15, height: 44)    static let titleSize: CGFloat = 28    /// The most a lying page's title shrinks to stay whole on its lines.    static let titleShrink: CGFloat = 0.72    /// A lying page's most height, as a share of the room, so the words    /// and the stamp under it always fit.    static let lyingShare: CGFloat = 0.47    static let labelSize: CGFloat = 13    /// Between a fact's label and its words.    static let labelGap: CGFloat = 12    static let rule = StrokeStyle(lineWidth: 0.9, dash: [2, 3])    static let columnTitleSize: CGFloat = 23    static let lineSize: CGFloat = 14    static let dateHand: CGFloat = 23    static let tagSize: CGFloat = 13    static let lineGap: CGFloat = 9    /// A blank page's shape, while the first page is not drawn.    public static let blankAspect: CGFloat = 0.72    /// Below this height the foot's picture is left out.    static let smallestArt: CGFloat = 70}public struct DocumentFace<Page: View>: View {    let card: DeckCard    /// The first page filling its frame, drawn by whoever holds the    /// document's bytes; nil draws a blank page.    let page: Page?    /// The first page's width over its height.    var pageAspect: CGFloat = DocumentFaceKnobs.blankAspect    public init(card: DeckCard, page: Page?, pageAspect: CGFloat = DocumentFaceKnobs.blankAspect) {        self.card = card        self.page = page        self.pageAspect = pageAspect    }    public var body: some View {        GeometryReader { sheet in            let room = CGSize(                width: sheet.size.width - DocumentFaceKnobs.inset.leading - DocumentFaceKnobs.inset.trailing,                height: sheet.size.height - DocumentFaceKnobs.inset.top - DocumentFaceKnobs.inset.bottom            )            Group {                if pageAspect >= DocumentFaceKnobs.wide {                    lying(room)                } else {                    standing(room)                }            }            .padding(DocumentFaceKnobs.inset)        }        .onCardPaper(DocumentFaceCatalogue.stock.laid(card.pace))    }    /// A wide page across the top, the words under it.    private func lying(_ room: CGSize) -> some View {        let width = min(room.width * 0.94, room.height * DocumentFaceKnobs.lyingShare * pageAspect)        // The words are laid first; the page takes what room they leave, up        // to its own size, so a long title never pushes the stamp off.        return VStack(alignment: .leading, spacing: 0) {            ClippedPage(page: page)                .aspectRatio(pageAspect, contentMode: .fit)                .accessibilityElement(children: .ignore)                .accessibilityLabel(card.text("title") ?? "")                .facePart(.picture)                .frame(maxWidth: width, maxHeight: width / pageAspect)                .frame(maxWidth: .infinity)                .padding(.top, 6)            Group {                HStack(alignment: .top, spacing: 10) {                    if let title = card.text("title") {                        HeavyType(words: title, size: DocumentFaceKnobs.titleSize)                            .lineLimit(3)                            .minimumScaleFactor(DocumentFaceKnobs.titleShrink)                            .accessibilityIdentifier("deck-title")                            .facePart(.title)                    }                    Spacer(minLength: 0)                    if let group = card.text("group") { GroupTag(words: group).padding(.top, 4).facePart(.group) }                }                .padding(.top, 20)                facts                    .padding(.top, 6)                HStack(alignment: .bottom) {                    stamp                    Spacer(minLength: 0)                    corner                }            }            .layoutPriority(1)        }        .frame(maxHeight: .infinity, alignment: .top)    }    /// A tall page at the left with the tag and title beside it, the facts    /// under them across the card, and the house watercolour in the room    /// left at the foot.    /// A title too long for the column beside the standing page.    static func wantsTheWidth(_ title: String) -> Bool {        title.count > DocumentFaceKnobs.columnMostCharacters            || title.split(whereSeparator: \.isWhitespace).contains { $0.count > DocumentFaceKnobs.columnLongestWord }    }    private func standing(_ room: CGSize) -> some View {        let width = room.width * DocumentFaceKnobs.standingShare        // A title under the page takes room from the page, never the foot.        let wide = card.text("title").map(Self.wantsTheWidth) ?? false        let height = min(width / pageAspect, room.height * (wide ? DocumentFaceKnobs.standingShareUnderTitle : 0.62))        return VStack(alignment: .leading, spacing: 0) {            HStack(alignment: .top, spacing: 14) {                pagePrint(width: height * pageAspect, height: height)                    .padding(.top, 8)                VStack(alignment: .leading, spacing: 0) {                    if let group = card.text("group") {                        GroupTag(words: group)                            .frame(maxWidth: .infinity, alignment: .trailing)                            .padding(.bottom, 20)                    }                    if let title = card.text("title"), !Self.wantsTheWidth(title) {                        HeavyType(words: title, size: DocumentFaceKnobs.columnTitleSize)                            .lineLimit(4)                            .minimumScaleFactor(0.7)                            .accessibilityIdentifier("deck-title")                            .facePart(.title)                    }                }                .padding(.top, 4)            }            // A title the column beside the page cannot hold whole — a long            // one, or one word too long to wrap (an invoice number) — takes            // the card's width under the page.            if let title = card.text("title"), Self.wantsTheWidth(title) {                HeavyType(words: title, size: DocumentFaceKnobs.columnTitleSize)                    .lineLimit(3)                    .minimumScaleFactor(0.8)                    .padding(.top, 12)                    .accessibilityIdentifier("deck-title")            }            facts                .padding(.top, 14)            ZStack(alignment: .bottomLeading) {                GeometryReader { foot in                    // Drawn only where it can be seen for what it is.                    if foot.size.height >= DocumentFaceKnobs.smallestArt {                        FaceArt(name: "face-art-house")                            .frame(width: min(room.width * 0.62, foot.size.height * 1.5), height: foot.size.height, alignment: .bottomTrailing)                            .frame(width: foot.size.width, height: foot.size.height, alignment: .bottomTrailing)                    }                }                VStack(alignment: .leading, spacing: 6) {                    stamp                    corner                }            }            .frame(maxHeight: .infinity, alignment: .bottom)            .padding(.top, 8)        }    }    private func pagePrint(width: CGFloat, height: CGFloat) -> some View {        ClippedPage(page: page)            .frame(width: width, height: height)            .accessibilityElement(children: .ignore)            .accessibilityLabel(card.text("title") ?? "")            .facePart(.picture)    }    /// The facts, each on its dashed rule: kind and pages; when it was    /// received, by hand; who it is from. A fact the core phrased through its    /// line ("Received {said}", "From {said}") is drawn as that line's words    /// small in pencil and what was said beside them.    private var facts: some View {        Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: DocumentFaceKnobs.labelGap, verticalSpacing: DocumentFaceKnobs.lineGap) {            if let kind = card.text("subtitle") {                rule                GridRow { typed(kind).gridCellColumns(2) }            }            if let received = card.text("date") {                rule                fact(received, line: ShellLines.line("cards", "field.received", ["said": PhrasedFact.mark]), hand: true)            }            if let source = card.text("source") {                rule                fact(source, line: ShellLines.line("cards", "field.issuer", ["said": PhrasedFact.mark]), hand: false)            }        }    }    /// A rule across the card, which also holds the facts to its width.    private var rule: some View {        DashedRule()    }    /// One fact's row: the line's words as its label when the core phrased    /// it so, else the words whole across the row.    @ViewBuilder private func fact(_ words: String, line: String, hand: Bool) -> some View {        if let parted = PhrasedFact.part(words, line: line) {            GridRow {                Text(parted.label)                    .font(CottonFonts.type(DocumentFaceKnobs.labelSize))                    .lineLimit(1)                    .fixedSize()                    .faceInk(.pencil)                // The words take the row's slack, so they sit by their label.                said(parted.said, hand: hand)                    .frame(maxWidth: .infinity, alignment: .leading)            }        } else {            GridRow { said(words, hand: hand).gridCellColumns(2) }        }    }    @ViewBuilder private func said(_ words: String, hand: Bool) -> some View {        if hand {            Text(HandRun.tail(words))                .font(CottonFonts.hand(DocumentFaceKnobs.dateHand))                .lineLimit(2)                .faceInk(.ink)        } else {            typed(words)        }    }    /// The document's state the person should see ("Not read yet"),    /// stamped in red.    @ViewBuilder private var stamp: some View {        if let state = card.text("state") {            Text(state)                .font(CottonFonts.type(DocumentFaceKnobs.tagSize - 1))                .lineLimit(1)                .faceInk(.red)                .padding(.horizontal, 8)                .padding(.vertical, 4)                .overlay(RoundedRectangle(cornerRadius: 2).stroke(lineWidth: 1.4).faceInk(.red))                .rotationEffect(.degrees(-5))                .padding(.top, 8)                .accessibilityIdentifier("face-state")        }    }    @ViewBuilder private var corner: some View {        if let corner = card.corner {            CornerSlip(words: corner, size: DocumentFaceKnobs.tagSize - 1.5)                .padding(.top, 8)        }    }    private func typed(_ words: String) -> some View {        Text(words)            .font(CottonFonts.type(DocumentFaceKnobs.lineSize))            .lineLimit(2)            .faceInk(.ink)    }}/// A fact the core phrased through one of its lines ("Received {said}"),/// parted back into the line's own words and what was said in it. Nil when/// the words were not phrased by that line.enum PhrasedFact {    /// Stands for what is said while the line is read for its words.    static let mark = "\u{FFFC}"    /// `line` is the line read with `mark` as what was said.    static func part(_ words: String, line: String) -> (label: String, said: String)? {        let halves = line.components(separatedBy: mark)        guard halves.count == 2, words.hasPrefix(halves[0]), words.hasSuffix(halves[1]),              words.count > halves[0].count + halves[1].count        else { return nil }        let said = String(words.dropFirst(halves[0].count).dropLast(halves[1].count)).trimmingCharacters(in: .whitespaces)        let label = (halves[0] + halves[1]).trimmingCharacters(in: .whitespaces)        return said.isEmpty || label.isEmpty ? nil : (label, said)    }}/// A rule of short dashes in pencil between a card's facts.public struct DashedRule: View {    @Environment(\.theme) private var theme    public init() {}    public var body: some View {        Line()            .stroke(theme.print(.pencil).opacity(0.5), style: DocumentFaceKnobs.rule)            .frame(height: 1)            .blendMode(theme.printBlend)            .accessibilityHidden(true)    }    private struct Line: Shape {        func path(in rect: CGRect) -> Path {            Path { $0.move(to: CGPoint(x: rect.minX, y: rect.midY)); $0.addLine(to: CGPoint(x: rect.maxX, y: rect.midY)) }        }    }}/// The first page as a print clipped to the card: its picture (or a blank/// page with typed lines), a shadow where it lifts, turned a hair, and a/// paperclip over its top edge.private struct ClippedPage<Page: View>: View {    let page: Page?    @Environment(\.theme) private var theme    var body: some View {        ZStack(alignment: .topLeading) {            ZStack {                Rectangle().fill(theme.faceStocks.printMount)                if let page {                    Color.clear.overlay(page).clipped()                } else {                    BlankPage().padding(.horizontal, 12).padding(.vertical, 16)                }            }            .shadow(color: theme.colors.shadow.color.opacity(0.28), radius: 3.5, x: 0, y: 2.5)            WirePaperClip()                .frame(width: DocumentFaceKnobs.clip.width, height: DocumentFaceKnobs.clip.height)                .rotationEffect(.degrees(-8))                .offset(x: 10, y: -DocumentFaceKnobs.clip.height * 0.4)        }        .rotationEffect(.degrees(DocumentFaceKnobs.pageTurn))        .accessibilityHidden(true)    }}/// A page whose picture is not here: a heading bar and typed lines in pencil.public struct BlankPage: View {    @Environment(\.theme) private var theme    private let lines: [CGFloat] = [0.55, 0, 1, 0.92, 0.97, 0.6, 0, 1, 0.88, 0.95, 0.4]    public init() {}    public var body: some View {        GeometryReader { page in            VStack(alignment: .leading, spacing: page.size.height / CGFloat(lines.count * 2)) {                ForEach(Array(lines.enumerated()), id: \.offset) { index, share in                    Rectangle()                        .fill(theme.print(.pencil).opacity(share == 0 ? 0 : (index == 0 ? 0.45 : 0.22)))                        .frame(width: page.size.width * max(share, 0.1), height: index == 0 ? 3.5 : 2)                }            }        }        .blendMode(theme.printBlend)    }}/// A steel paperclip: the wire drawn dark, its highlight drawn over it.struct WirePaperClip: View {    @Environment(\.theme) private var theme    var body: some View {        ZStack {            PaperClip()                .stroke(theme.print(.ink).opacity(0.62), style: StrokeStyle(lineWidth: 2.6, lineCap: .round, lineJoin: .round))            PaperClip()                .stroke(theme.colors.paper.color.opacity(0.55), style: StrokeStyle(lineWidth: 0.9, lineCap: .round, lineJoin: .round))                .offset(x: -0.5, y: -0.5)        }        .shadow(color: theme.colors.shadow.color.opacity(0.35), radius: 0.8, x: 0.8, y: 1.2)    }}/// A paperclip seen from above: the wire's outer loop and its inner one.struct PaperClip: Shape {    func path(in rect: CGRect) -> Path {        let w = rect.width, h = rect.height        let outer = w * 0.5, inner = w * 0.3        var path = Path()        // From the inner wire's end, down, round the bottom, up the outer        // right side, round the top, down the outer left side, round the        // bottom's inner bend and up to the inner loop's end.        path.move(to: CGPoint(x: rect.minX + w * 0.2, y: rect.minY + h * 0.3))        path.addLine(to: CGPoint(x: rect.minX + w * 0.2, y: rect.maxY - inner - h * 0.08))        path.addArc(center: CGPoint(x: rect.minX + w * 0.5, y: rect.maxY - inner - h * 0.08), radius: inner, startAngle: .degrees(180), endAngle: .degrees(0), clockwise: true)        path.addLine(to: CGPoint(x: rect.minX + w * 0.8, y: rect.minY + outer))        path.addArc(center: CGPoint(x: rect.midX, y: rect.minY + outer * 0.6 + 1), radius: w * 0.4, startAngle: .degrees(0), endAngle: .degrees(180), clockwise: true)        path.addLine(to: CGPoint(x: rect.minX + w * 0.1, y: rect.maxY - outer))        path.addArc(center: CGPoint(x: rect.midX, y: rect.maxY - outer), radius: w * 0.4, startAngle: .degrees(180), endAngle: .degrees(0), clockwise: true)        path.addLine(to: CGPoint(x: rect.minX + w * 0.9, y: rect.minY + h * 0.42))        return path    }}/// The group a record stands in, typed on a torn tag of pink paper.struct GroupTag: View {    let words: String    @Environment(\.theme) private var theme    var body: some View {        Text(words)            .font(CottonFonts.type(DocumentFaceKnobs.tagSize))            .lineLimit(1)            .faceInk(.ink)            .padding(.horizontal, 14)            .padding(.vertical, 7)            .background(                PaperSurface(dye: .pink, edge: .torn, seed: "tag-\(words)")                    .saturation(1.7)                    .shadow(color: theme.colors.shadow.color.opacity(0.18), radius: 1.5, x: 0, y: 1)            )            .rotationEffect(.degrees(2))            .accessibilityIdentifier("face-group")    }}/// The document face, by the kind's name, and the cards it is reviewed in:/// its file's first page where the app draws one (`faceFilePage`), else the/// blank page it shows while the bytes are not on the phone.public enum DocumentFaceCatalogue {    public static let stock: FaceStock = .framed    public static let ground: FaceGround = .paper    public static let face = Face(id: "document", specimens: [        Specimen("form-16", document), Specimen("bill", bill), Specimen("boarding-pass", postcard),    ]) { card, _, taps in        DocumentFileCard(card: card)    }    public static let document = DeckCard(        face: .document,        corner: "Needed for ITR",        fields: [            "title": .text("Form 16 — FY 2025-26"),            "subtitle": .text("PDF • 4 pages"),            "date": .text("Received 12 Jun 2026"),            "source": .text("From Studio Iyer"),        ]    )    public static let bill = DeckCard(        face: .document,        fields: [            "title": .text("Electricity bill"),            "subtitle": .text("PDF \u{00B7} 1 page"),            "date": .text("Received 18 Oct 2026"),            "source": .text("From Example Power Company"),            "group": .text("Home"),        ]    )    public static let postcard = DeckCard(        face: .document,        corner: "Boards in 4 hours",        fields: [            "title": .text("Boarding pass BLR to DEL"),            "subtitle": .text("PDF \u{00B7} 1 page"),            "date": .text("Received 2 days ago"),            "group": .text("Travel"),            "state": .text("Not read yet"),        ]    )}/// The corner's "why now" on a slip of pink paper (images 2a and 2b).struct CornerSlip: View {    let words: String    let size: CGFloat    @Environment(\.theme) private var theme    var body: some View {        Text(words)            .font(CottonFonts.type(size))            .faceInk(.red)            .padding(.horizontal, 8)            .padding(.vertical, 5)            .background(RoundedRectangle(cornerRadius: 2.5).fill(theme.faceStocks.cornerSlip).blendMode(theme.printBlend))            .accessibilityIdentifier("face-corner")    }}