Cotton code
378 lines · 17.5 KB · SwiftRaw
// MONEY IN as a CHEQUE made out to you (the coordinator's brief, 30 Oct// 2026): a cheque leaf of pale blue-green security paper, torn from its book// along the perforation, lying bare on the money's pink terrazzo// (`FaceGround.terrazzo`). The leaf, its dark-blue rules, amount box and foot// band, and its shadow are PAINTED (`Media.xcassets`, cut and imported by// `scripts/import-money-materials.py`), no word on them; the face writes live// only what the card decides:////   who paid (`title`) printed at the leaf's head, as a firm's cheque carries//   its drawer's name, and signed in their hand on the signature rule;//   what it was for (`subtitle`, else `body`) pencilled under the head;//   the date (`date`) by hand on the date rule;//   PAY, by hand, the account it was paid into (`account`, by its name);//   RUPEES, the amount in words by hand over the two rules (`RupeeWords`);//   the amount typed in the box, "Rs" and two places;//   the record's short id typed in the foot band, as a cheque's serial;//   and the balance before and after it as the bank's rubber CREDITED//   stamp across the leaf's lower left corner, in violet, two small lines//   under it (BAL BEFORE, BAL AFTER): a stamp a bank applies to what it//   credits, never a field printed on the cheque, since the balance is the//   bank's to know, not the drawer's.//// The card's corner and state are pencilled at the top right. A tap on the// screen's sides cuts to the next card (`FaceStep.cut`). Every word but the// leaf's and the stamp's print (DATE, PAY, RUPEES, Rs, CREDITED, BAL BEFORE,// BAL AFTER) is the core's (`DeckCard`), or written from it.import CottonPaperimport CottonValuesimport CoreTextimport SwiftUIenum ChequeFaceKnobs {    // THE LEAF, as painted (`cheque-leaf`, 1480 by 732 pixels): its width    // over its height, its shadow's reach as a share of its width, and its    // rules, box and band as shares of it (x of the width, y of the height),    // measured off the painting by the cut (`cut.py` beside the layers).    static let aspect: CGFloat = 1480.0 / 732.0    static let shadowReach: CGFloat = 0.0405    static let dateRule = (y: CGFloat(0.1517), from: CGFloat(0.647), to: CGFloat(0.922))    static let payRule = (y: CGFloat(0.3511), from: CGFloat(0.0797), to: CGFloat(0.922))    static let wordRules = (first: CGFloat(0.5077), second: CGFloat(0.6221), from: CGFloat(0.0797), to: CGFloat(0.637))    static let box = CGRect(x: 0.6635, y: 0.4337, width: 0.2585, height: 0.1463)    static let signRule = (y: CGFloat(0.7654), from: CGFloat(0.5885), to: CGFloat(0.922))    static let band = (top: CGFloat(0.8443), bottom: CGFloat(0.9612))    /// How far along the words' first rule they start, past the printed RUPEES.    static let wordsLead: CGFloat = 0.1    /// The leaf in the card's room: the most of its width it takes.    static let fill: CGFloat = 0.97    /// The type, as shares of the leaf's width.    static let printSize: CGFloat = 0.022    static let headSize: CGFloat = 0.04    static let handSize: CGFloat = 0.06    static let wordsSize: CGFloat = 0.046    static let figureSize: CGFloat = 0.038    static let serialSize: CGFloat = 0.034    /// The serial's room in the foot band, clear of the stamp at its left.    static let serialFrom: CGFloat = 0.52    static let serialTo: CGFloat = 0.95    /// Where the drawer's printed name ends, clear of the printed DATE.    static let headTo: CGFloat = 0.56    static let pencilSize: CGFloat = 0.036    /// The stamp: its head's and its lines' size as shares of the leaf's    /// width, its middle's place on the leaf, and the turn it lies at.    static let stampHead: CGFloat = 0.042    static let stampLine: CGFloat = 0.028    static let stampCentre = CGPoint(x: 0.29, y: 0.81)    static let stampTurn: Double = -6}public struct TransactionChequeFace: View {    let card: DeckCard    public init(card: DeckCard) {        self.card = card    }    public var body: some View {        let knobs = ChequeFaceKnobs.self        GeometryReader { box in            let width = min(box.size.width * knobs.fill, box.size.height * knobs.fill * knobs.aspect)            let size = CGSize(width: width, height: width / knobs.aspect)            ZStack(alignment: .topLeading) {                MoneyPaper(name: "cheque-leaf", size: size, reach: knobs.shadowReach, standIn: MoneyMaterial.cheque.colour, corner: 0.006)                ChequeWriting(card: card, size: size)            }            .frame(width: size.width, height: size.height, alignment: .topLeading)            .accessibilityElement(children: .contain)            .accessibilityIdentifier("cheque")            .frame(width: box.size.width, height: box.size.height)        }    }}/// How the amount's words are set over the cheque's two rules.public enum ChequeWords {    /// `words` broken at whole words into at most two lines, each within    /// `width` in `font`; none for no words.    public static func lines(_ words: String, font: CTFont, width: CGFloat) -> [String] {        TornPageSetting.lines(words, font: font, width: width, limit: 2).map(\.words)    }    /// The face the words are written in, at `size` points.    static func font(_ size: CGFloat) -> CTFont {        _ = CottonFonts.signature(1)        return CTFontCreateWithName(CottonFonts.signatureFace as CFString, max(size, 1), nil)    }}private struct ChequeWriting: View {    let card: DeckCard    let size: CGSize    var body: some View {        let knobs = ChequeFaceKnobs.self        let w = size.width        let h = size.height        let amount = card.text("amount").flatMap(SaidAmount.init)        ZStack(alignment: .topLeading) {            Group {                printed                written(amount)                if let amount {                    typedAmount(amount)                }                if let serial = MoneyReading.serial(card) {                    Text(serial.map(String.init).joined(separator: " "))                        .font(CottonFonts.type(knobs.serialSize * w))                        .foregroundStyle(MoneyMaterial.print.colour)                        .tracking(0.3 * knobs.serialSize * w)                        .frame(width: (knobs.serialTo - knobs.serialFrom) * w, height: (knobs.band.bottom - knobs.band.top) * h)                        .placed(x: knobs.serialFrom * w, y: knobs.band.top * h)                        .accessibilityIdentifier("cheque-serial")                }            }            .blendMode(.multiply)            CreditedStamp(balances: MoneyReading.balances(card), width: w)                .position(x: knobs.stampCentre.x * w, y: knobs.stampCentre.y * h)            pencil        }        .frame(width: w, height: h, alignment: .topLeading)    }    /// The leaf's print: who it is from at its head, and the words its rules    /// stand by.    private var printed: some View {        let knobs = ChequeFaceKnobs.self        let w = size.width        let h = size.height        let ink = MoneyMaterial.print.colour        let print = CottonFonts.type(knobs.printSize * w)        return ZStack(alignment: .topLeading) {            if let title = card.text("title") {                FittedLine(words: title.uppercased(), font: CottonFonts.caslon(knobs.headSize * w), ink: ink, tracking: 0.08 * knobs.headSize * w, shrink: 0.6)                    .frame(width: (knobs.headTo - knobs.payRule.from) * w, alignment: .leading)                    .accessibilityIdentifier("deck-title")                    .facePart(.title)                    .placed(x: knobs.payRule.from * w, y: 0.07 * h)            }            label(ChequePrint.date, font: print, ink: ink, rule: knobs.dateRule.y, from: knobs.dateRule.from)            label(ChequePrint.pay, font: print, ink: ink, rule: knobs.payRule.y, from: knobs.payRule.from)            // The words' rule starts at the leaf's left: RUPEES stands on it,            // and the words are written after it.            Text(ChequePrint.rupees)                .font(print)                .foregroundStyle(ink)                .fixedSize()                .placed(x: knobs.wordRules.from * w, y: knobs.wordRules.first * h - knobs.printSize * w * 1.25)            Text(ChequePrint.rs)                .font(print)                .foregroundStyle(ink)                .placed(x: (knobs.box.minX + 0.012) * w, y: (knobs.box.minY + 0.02) * h)        }    }    /// A printed word standing just before where a rule starts, on it.    private func label(_ words: String, font: Font, ink: Color, rule: CGFloat, from: CGFloat) -> some View {        let w = size.width        return Text(words)            .font(font)            .foregroundStyle(ink)            .fixedSize()            .frame(width: 0.1 * w, alignment: .trailing)            .offset(x: from * w - 0.1 * w - 0.008 * w, y: rule * size.height - ChequeFaceKnobs.printSize * w * 1.25)    }    /// What the hand wrote: the date, whom to pay, the amount in words, and    /// the drawer's signature.    private func written(_ amount: SaidAmount?) -> some View {        let knobs = ChequeFaceKnobs.self        let w = size.width        let hand = MoneyMaterial.hand.colour        let wordsFont = ChequeWords.font(knobs.wordsSize * w)        let wordsWidth = (knobs.wordRules.to - knobs.wordRules.from - knobs.wordsLead - 0.01) * w        let words = amount.flatMap(MoneyReading.words).map { ChequeWords.lines($0, font: wordsFont, width: wordsWidth) } ?? []        return ZStack(alignment: .topLeading) {            if let date = card.text("date") {                onRule(date, size: knobs.handSize * 0.8 * w, rule: knobs.dateRule.y, from: knobs.dateRule.from + 0.01, to: knobs.dateRule.to, part: .when)            }            if let account = card.text("account") {                onRule(account, size: knobs.handSize * w, rule: knobs.payRule.y, from: knobs.payRule.from + 0.02, to: knobs.payRule.to)            }            ForEach(Array(words.enumerated()), id: \.offset) { index, line in                onRule(line, size: knobs.wordsSize * w, rule: index == 0 ? knobs.wordRules.first : knobs.wordRules.second,                       from: knobs.wordRules.from + (index == 0 ? knobs.wordsLead : 0.01), to: knobs.wordRules.to)            }            .accessibilityElement(children: .combine)            .accessibilityIdentifier("cheque-words")            if let title = card.text("title") {                onRule(title, size: knobs.handSize * 0.95 * w, rule: knobs.signRule.y, from: knobs.signRule.from + 0.02, to: knobs.signRule.to)                    .accessibilityIdentifier("cheque-signature")            }        }        .foregroundStyle(hand)    }    /// Words by hand with their baseline on a rule, from `from` to `to` of    /// the leaf's width, squeezed to the rule rather than cut; tagged as    /// `part` where it is written, when it is one.    private func onRule(_ words: String, size points: CGFloat, rule: CGFloat, from: CGFloat, to: CGFloat, part: FacePart? = nil) -> some View {        let w = size.width        return Text(words)            .font(CottonFonts.signature(points))            .lineLimit(1)            .minimumScaleFactor(0.5)            .frame(width: (to - from) * w, height: points * 1.3, alignment: .bottomLeading)            .modifier(TaggedIf(part: part))            .placed(x: from * w, y: rule * size.height - points * 1.3 + points * 0.28)    }    /// The amount typed in its box.    private func typedAmount(_ amount: SaidAmount) -> some View {        let knobs = ChequeFaceKnobs.self        let w = size.width        let h = size.height        return FittedLine(words: amount.typed, font: CottonFonts.type(knobs.figureSize * w), ink: MoneyMaterial.posting.colour, alignment: .trailing, shrink: 0.6)            .frame(width: (knobs.box.width - 0.06) * w, height: knobs.box.height * h)            .facePart(.amount)            .placed(x: (knobs.box.minX + 0.045) * w, y: knobs.box.minY * h)    }    /// What it was for, pencilled under the head; the corner and the state    /// at the top right.    private var pencil: some View {        let knobs = ChequeFaceKnobs.self        let w = size.width        let h = size.height        let points = knobs.pencilSize * w        return ZStack(alignment: .topLeading) {            if let purpose = MoneyReading.purpose(card) {                Text(purpose.words)                    .font(CottonFonts.hand(points))                    .foregroundStyle(MoneyMaterial.pencil.colour)                    .lineLimit(1)                    .minimumScaleFactor(0.6)                    .frame(width: (knobs.headTo - knobs.payRule.from) * w, alignment: .leading)                    .facePart(purpose.part)                    .placed(x: knobs.payRule.from * w, y: 0.17 * h)            }            if card.corner != nil || card.text("state") != nil {                HStack(spacing: 0.02 * w) {                    if let corner = card.corner { Text(corner).facePart(.corner) }                    if let state = card.text("state") { Text(state).facePart(.state) }                }                .font(CottonFonts.hand(points * 0.85))                .foregroundStyle(card.pressing ? MoneyMaterial.tab.colour : MoneyMaterial.pencil.colour)                .frame(width: (knobs.dateRule.to - knobs.dateRule.from) * w, alignment: .trailing)                .placed(x: knobs.dateRule.from * w, y: 0.04 * h)            }        }    }}/// The bank's rubber stamp: CREDITED, and under it the account's balance/// before and after, in violet, worn as a stamp is.private struct CreditedStamp: View {    let balances: (before: SaidAmount?, after: SaidAmount?)    let width: CGFloat    var body: some View {        let knobs = ChequeFaceKnobs.self        let head = knobs.stampHead * width        let line = knobs.stampLine * width        VStack(alignment: .leading, spacing: line * 0.25) {            Text(ChequePrint.credited)                .font(CottonFonts.type(head))                .tracking(head * 0.18)                .frame(maxWidth: .infinity)            if balances.before != nil || balances.after != nil {                Rectangle().frame(height: max(0.8, line * 0.08))                if let before = balances.before { row(ChequePrint.balanceBefore, before, line) }                if let after = balances.after { row(ChequePrint.balanceAfter, after, line) }            }        }        .fixedSize()        .padding(.horizontal, line * 0.7)        .padding(.vertical, line * 0.45)        .overlay(RoundedRectangle(cornerRadius: line * 0.4).inset(by: line * 0.05).stroke(lineWidth: max(1.2, line * 0.13)))        .foregroundStyle(MoneyMaterial.stamp.colour)        .mask(StampWear(seed: ChequePrint.credited))        .opacity(0.85)        .blendMode(.multiply)        .rotationEffect(.degrees(knobs.stampTurn))        .accessibilityElement(children: .combine)        .accessibilityIdentifier("cheque-stamp")    }    private func row(_ label: String, _ amount: SaidAmount, _ size: CGFloat) -> some View {        HStack(spacing: size * 0.8) {            Text(label)            Spacer(minLength: 0)            Text(MoneyReading.typed(amount))        }        .font(CottonFonts.type(size))    }}/// The cheque's and the bank stamp's own print: the words a cheque leaf and/// a bank's stamp carry whatever is written on them.enum ChequePrint {    static let date = "DATE"    static let pay = "PAY"    static let rupees = "RUPEES"    static let rs = "Rs"    static let credited = "CREDITED"    static let balanceBefore = ShellLines.line("cards", "faces.balance_before_short")    static let balanceAfter = ShellLines.line("cards", "faces.balance_after_short")}/// Money in as a cheque, by its id beside the transaction's own face, and/// the credits it is reviewed in: invented names only.public enum TransactionChequeFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .terrazzo    public static let face = Face(id: "transaction.cheque", specimens: [        Specimen("salary", salary), Specimen("refund", refund),    ], steps: .cut) { card, _, _ in        TransactionChequeFace(card: card)    }    static func credit(_ record: String, _ fields: [String: RecordValue]) -> DeckCard {        DeckCard(face: "transaction.cheque", corner: nil, pressing: false, pace: nil, plate: nil, fields: fields)            .reading { $0.record = record }    }    /// A month's salary from a studio: a lakh figure in words.    public static let salary = credit("5b2e8f10-3c4d-4a9e-b7f2-61d0c8a35b91", [        "title": .text("Larkspur Studio"),        "subtitle": .text("Salary for October"),        "amount": .text("\u{20B9}1,80,000"),        "account": .text("Northern Bank Savings"),        "facts": TransactionReceiptFaceCatalogue.balances("\u{20B9}3,12,400", "\u{20B9}4,92,400"),        "date": TransactionReceiptFaceCatalogue.when("Sat 31 Oct", "9:30 am"),    ])    /// A shop's refund, with paise.    public static let refund = credit("e81f4a27-9d05-4c3b-a6e8-2f7b90d14c06", [        "title": .text("Greenleaf Grocers"),        "subtitle": .text("Refund, a torn sack of rice"),        "amount": .text("\u{20B9}340.50"),        "account": .text("Northern Bank Savings"),        "facts": TransactionReceiptFaceCatalogue.balances("\u{20B9}1,24,500", "\u{20B9}1,24,840.50"),        "date": TransactionReceiptFaceCatalogue.when("Wed 28 Oct", "11:15 am"),    ])}/// A part's tag where there is a part to tag.private struct TaggedIf: ViewModifier {    let part: FacePart?    func body(content: Content) -> some View {        if let part {            content.facePart(part)        } else {            content        }    }}