Cotton code
367 lines · 16.9 KB · SwiftRaw
// The owner's chosen personnel file (30 Oct 2026, people-2/3-file-colleague):// painted manila folder, clipped square print and laminated work ID, bare on// the rolodex's blue felt. All writing and both portraits are live. Only the// person's own facts belong here; the foot is plain paper and the reached// line. Materials: scripts/import-person-file-materials.py.import CottonPaperimport CottonValuesimport CoreTextimport SwiftUI/// The words the card actually supplied, with no inferred workplace or date.public struct PersonFileWords: Equatable, Sendable {    public let name: String    public let tab: String    public let workplace: String?    public let role: String?    public let phones: [String]    public let emails: [String]    public let birthday: String?    public let summary: String?    public let corner: String?    public let reached: String?    public init(_ card: DeckCard) {        name = card.text("title")?.split(whereSeparator: \.isWhitespace).joined(separator: " ") ?? ""        let parts = name.split(separator: " ")        tab = parts.count > 1 ? "\(parts.last!), \(parts.dropLast().joined(separator: " "))".uppercased() : name.uppercased()        workplace = card.text("place") ?? card.text("org")        // The core joins role, org and city in the subtitle; the role is its        // first part, the workplace its own slot (as the passport reads them).        role = card.text("subtitle")?.components(separatedBy: ShellLines.line("cards", "join")).first        // reach is filled by the shell; standalone resolved cards may carry        // their numbers and email addresses in slots instead.        phones = Self.contacts(card.reach.phones, or: card.words("phones") + card.words("phone"))        emails = Self.contacts(card.reach.emails, or: card.words("emails"))        // The core's date slot can carry a birthday; the current person        // mapping supplies only a nearby birthday in its corner instead.        birthday = card.text("date")        summary = card.text("body")        corner = card.corner.flatMap { $0.isEmpty ? nil : $0 }        reached = card.text("reached")    }    // Until the kit supplies a workplace slot, a role-only card can draw    // that role on its ID. No subtitle and no workplace means no ID at all.    public var hasID: Bool { workplace != nil || role != nil }    private static func contacts(_ reach: [String], or slots: [String]) -> [String] {        var seen = Set<String>()        let filled = reach.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }        return (filled.isEmpty ? slots : filled)            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }            .filter { !$0.isEmpty && seen.insert($0).inserted }    }}private enum FileKnobs {    static let lead: CGFloat = 0.09    static let room: CGFloat = 0.80    static let printSide: CGFloat = 0.39    static let factSize: CGFloat = 0.035    static let lineStep: CGFloat = 0.057    static let badgeWidth: CGFloat = 0.21    // Measured after keying and cropping the paintings.    static let badgeAspect: CGFloat = 270.0 / 758    static let badgePhoto = CGRect(x: 0.13, y: 0.47, width: 0.74, height: 0.264)}/// A name in Caslon, facts in Courier Prime, and a single typed reached line.public struct PersonFileFace: View {    let card: DeckCard    let photo: FacePicture?    public init(card: DeckCard, photo: FacePicture?) {        self.card = card        self.photo = photo    }    public var body: some View {        GeometryReader { box in            let layout = FileLayout(PersonFileWords(card))            let width = min(box.size.width * 0.96, box.size.height * 0.95 / layout.height)            FileObject(card: card, photo: photo, layout: layout, width: width)                .frame(width: width, height: width * layout.height)                .frame(width: box.size.width, height: box.size.height)        }    }}/// Measurements use a one-point-wide file, so text and materials scale/// together. A fuller record needs a taller sheet; no empty fact rows.private struct FileLayout {    struct Fact {        let label: String        let words: String        let part: FacePart    }    let words: PersonFileWords    let names: [String]    let nameSize: CGFloat    let facts: [Fact]    let summary: [String]    let summaryLabel: String?    let factsTop: CGFloat    let summaryTop: CGFloat    let height: CGFloat    init(_ words: PersonFileWords) {        self.words = words        _ = CottonFonts.caslon(1)        _ = CottonFonts.type(1)        // Measure at 1000 points to keep CoreText's line breaking precise.        let name = Self.name(words.name)        names = name.lines        nameSize = name.size        var rows: [Fact] = words.phones.map { Fact(label: ShellLines.line("cards", "faces.phone"), words: $0, part: .call) }        rows += words.emails.map { Fact(label: ShellLines.line("cards", "faces.email"), words: $0, part: .email) }        if let birthday = words.birthday { rows.append(Fact(label: ShellLines.line("cards", "faces.birthday"), words: birthday, part: .when)) }        if let corner = words.corner { rows.append(Fact(label: "", words: corner, part: .when)) }        facts = rows        // Summary is not rewritten into an invented date or relationship.        summaryLabel = ShellLines.line("cards", "faces.known_since")        summary = words.summary.map {            TornPageSetting.lines($0, font: CTFontCreateWithName(CottonFonts.typeFace as CFString, 35, nil), width: 800, limit: Int.max).map(\.words)        } ?? []        factsTop = max(0.71, 0.57 + CGFloat(max(names.count, 1)) * nameSize * 1.17)        summaryTop = factsTop + CGFloat(rows.count) * FileKnobs.lineStep + 0.015        let summaryRoom = summary.isEmpty ? 0 : CGFloat(summary.count + (summaryLabel == nil ? 0 : 1)) * FileKnobs.lineStep        height = max(1.00, summaryTop + summaryRoom + (words.reached == nil ? 0.10 : 0.17))    }    private static func name(_ name: String) -> (lines: [String], size: CGFloat) {        let words = name.split(whereSeparator: \.isWhitespace)        var points: CGFloat = 90        var lines: [String] = []        // Take the name down until its words fit whole, on at most three        // lines. Never split a surname or drop the tail of a long name.        while points >= 8 {            let font = CTFontCreateWithName(CottonFonts.caslonFace as CFString, points, nil)            lines = TornPageSetting.lines(name, font: font, width: 610, limit: Int.max).map(\.words)            if lines.count <= 3 && lines.flatMap({ $0.split(whereSeparator: \.isWhitespace) }) == words { break }            points *= 0.95        }        return (lines, points / 1000)    }}private struct FileObject: View {    let card: DeckCard    let photo: FacePicture?    let layout: FileLayout    let width: CGFloat    private var ink: Color { PeopleMaterial.ink.colour }    var body: some View {        let w = width        let h = w * layout.height        ZStack(alignment: .topLeading) {            layer("folder-shadow", width: w * 1.16, height: h + w * 0.16)                .offset(x: -w * 0.08, y: -w * 0.08)            layer("folder", width: w, height: h)            line(layout.words.tab, size: w * 0.032, width: w * 0.40)                .facePart(.title)                .offset(x: w * 0.55, y: h * 0.022)            FilePrint(photo: photo, initials: CardPerson.initials(card.text("title") ?? ""), side: w * FileKnobs.printSide)                .rotationEffect(.degrees(-3))                .facePart(.picture)                .offset(x: w * 0.075, y: w * 0.105)            layer("clip", width: w * 0.040, height: w * 0.176)                .shadow(color: .black.opacity(0.25), radius: w * 0.003, x: w * 0.003, y: w * 0.004)                .offset(x: w * 0.12, y: w * 0.065)            if layout.words.hasID {                FileID(words: layout.words, photo: photo, initials: CardPerson.initials(card.text("title") ?? ""), width: w * FileKnobs.badgeWidth)                    .rotationEffect(.degrees(5), anchor: .top)                    .offset(x: w * 0.74, y: w * 0.075)            }            VStack(alignment: .leading, spacing: 0) {                ForEach(Array(layout.names.enumerated()), id: \.offset) { _, name in                    Text(name).font(CottonFonts.caslon(w * layout.nameSize))                        .lineLimit(1).minimumScaleFactor(0.65)                        .frame(width: w * 0.61, height: w * layout.nameSize * 1.17, alignment: .leading)                }            }            .foregroundStyle(ink).blendMode(.multiply)            .accessibilityIdentifier("face-name")            .facePart(.title)            .offset(x: w * FileKnobs.lead, y: w * 0.51)            if !layout.names.isEmpty {                Rectangle().fill(ink.opacity(0.65))                    .frame(width: w * 0.61, height: max(0.35, w * 0.0012))                    .blendMode(.multiply).accessibilityHidden(true)                    .offset(x: w * FileKnobs.lead, y: w * (0.53 + CGFloat(layout.names.count) * layout.nameSize * 1.17))            }            ForEach(Array(layout.facts.enumerated()), id: \.offset) { index, fact in                HStack(alignment: .firstTextBaseline, spacing: 0) {                    if !fact.label.isEmpty {                        line(fact.label, size: w * FileKnobs.factSize, width: w * 0.27)                            .modifier(MessagePart(on: fact.part == .call && card.reach.message))                    }                    line(fact.words, size: w * FileKnobs.factSize, width: w * (fact.label.isEmpty ? FileKnobs.room : 0.53))                        .facePart(fact.part)                }                .offset(x: w * FileKnobs.lead, y: w * (layout.factsTop + CGFloat(index) * FileKnobs.lineStep))            }            if !layout.summary.isEmpty {                VStack(alignment: .leading, spacing: 0) {                    if let label = layout.summaryLabel {                        line(label, size: w * FileKnobs.factSize, width: w * FileKnobs.room)                            .frame(height: w * FileKnobs.lineStep, alignment: .topLeading)                    }                    ForEach(Array(layout.summary.enumerated()), id: \.offset) { _, words in                        line(words, size: w * FileKnobs.factSize, width: w * FileKnobs.room)                            .frame(height: w * FileKnobs.lineStep, alignment: .topLeading)                    }                }                .facePart(.body)                .offset(x: w * FileKnobs.lead, y: w * layout.summaryTop)            }            if let reached = layout.words.reached {                line(reached, size: w * 0.027, width: w * FileKnobs.room)                    .accessibilityIdentifier("person-file-reached")                    .facePart(.when)                    .offset(x: w * FileKnobs.lead, y: h - w * 0.12)            }        }        .frame(width: w, height: h, alignment: .topLeading)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("person-file")    }    private func line(_ words: String, size: CGFloat, width: CGFloat) -> some View {        Text(words).font(CottonFonts.type(size)).foregroundStyle(ink)            .lineLimit(1).minimumScaleFactor(0.35)            .frame(width: width, alignment: .leading)            .blendMode(.multiply)    }}/// Photographic paper carries typed initials when no portrait is given.private struct FilePrint: View {    let photo: FacePicture?    let initials: String?    let side: CGFloat    var body: some View {        ZStack {            CottonMedia.image("rolodex-print", scale: 3)?.resizable()                .frame(width: side, height: side)                .accessibilityHidden(true)            if let photo {                photo.frame(width: side * 0.88, height: side * 0.87).clipped()            } else if let initials {                Text(initials).font(CottonFonts.type(side * 0.25))                    .foregroundStyle(PeopleMaterial.ink.colour).blendMode(.multiply)            }        }        .frame(width: side, height: side)        .shadow(color: .black.opacity(0.22), radius: side * 0.012, x: side * 0.008, y: side * 0.014)    }}private struct FileID: View {    let words: PersonFileWords    let photo: FacePicture?    let initials: String?    let width: CGFloat    var body: some View {        let w = width        let h = w / FileKnobs.badgeAspect        let window = FileKnobs.badgePhoto        ZStack(alignment: .topLeading) {            layer("badge-shadow", width: w * (314.0 / 270), height: h * (802.0 / 758))                .offset(x: -w * 22 / 270, y: -w * 22 / 270)            layer("badge", width: w, height: h)            if let photo {                photo.frame(width: window.width * w, height: window.height * h).clipped()                    .facePart(.picture)                    .offset(x: window.minX * w, y: window.minY * h)            } else if let initials {                Text(initials).font(CottonFonts.type(w * 0.22))                    .foregroundStyle(PeopleMaterial.ink.colour).blendMode(.multiply)                    .frame(width: window.width * w, height: window.height * h)                    .offset(x: window.minX * w, y: window.minY * h)            }            VStack(alignment: .leading, spacing: w * 0.045) {                if let workplace = words.workplace {                    Text(workplace).facePart(.place)                }                if let role = words.role {                    Text(role).facePart(.subtitle)                }            }            .font(CottonFonts.type(w * 0.125))            .foregroundStyle(PeopleMaterial.ink.colour)            .lineLimit(2).minimumScaleFactor(0.55)            .frame(width: w * 0.78, height: h * 0.20, alignment: .topLeading)            .blendMode(.multiply)            .offset(x: w * 0.12, y: h * 0.77)        }        .frame(width: w, height: h, alignment: .topLeading)        .accessibilityIdentifier("person-file-id")    }}private struct MessagePart: ViewModifier {    let on: Bool    @ViewBuilder func body(content: Content) -> some View {        if on { content.facePart(.message) } else { content }    }}private func layer(_ name: String, width: CGFloat, height: CGFloat) -> some View {    CottonMedia.image("person-file-\(name)", scale: 3)?.resizable().interpolation(.high)        .frame(width: width, height: height).accessibilityHidden(true)}/// Invented Indian people, impossible phone numbers and example.org mail.public enum PersonFileFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .amethystDesk    public static let face = Face(id: "person.file", specimens: [        Specimen("colleague", colleague, picture: "rolodex-ananya"),        Specimen("friend", friend, picture: "rolodex-friend"),        Specimen("acquaintance", acquaintance),        Specimen("long-name", longName, picture: "portrait"),        Specimen("no-picture", noPicture),    ], steps: .cut) { card, picture, _ in        PersonFileFace(card: card, photo: picture)    }    private static func person(_ fields: [String: RecordValue], phones: [String] = [], emails: [String] = []) -> DeckCard {        var card = DeckCard(face: "person.file", corner: nil, pressing: false, pace: nil, plate: nil, fields: fields)        card.reach = CardReach(phones: phones, emails: emails, call: !phones.isEmpty, message: !phones.isEmpty, email: !emails.isEmpty)        return card    }    public static let colleague = person([        "title": .text("Aditi Sen"), "place": .text("Copperleaf Studio"), "subtitle": .text("Design lead"),        "date": .text("2 November"),        "body": .text("2023, work. We make the studio's books together."),        "reached": .text("Last spoke 9 days ago · 12:03 pm on WhatsApp"),    ], phones: ["+91 90000 00021"], emails: ["aditi@example.org"])    public static let friend = person([        "title": .text("Kabir Menon"), "date": .text("14 March"),        "body": .text("2019, the neighbourhood reading group."),        "reached": .text("Last spoke yesterday on WhatsApp"),    ], phones: ["+91 90000 00022"], emails: ["kabir@example.org"])    public static let acquaintance = person(["title": .text("Nikhil Sethi")], phones: ["+91 90000 00023"])    public static let longName = person([        "title": .text("Arundhati Venkatalakshmi Krishnamurthy"),        "place": .text("Coastal Arts Institute"), "subtitle": .text("Research fellow"),        "body": .text("Met at the summer print workshop."),        "reached": .text("Last spoke 3 months ago on email"),    ], phones: ["+91 90000 00024"], emails: ["arundhati@example.org"])    public static let noPicture = person([        "title": .text("Devika Kapur"), "place": .text("Paperboat Press"), "subtitle": .text("Editor"),        "date": .text("8 June"), "body": .text("2021, the first book fair."),        "reached": .text("Last spoke 6 weeks ago on WhatsApp"),    ], phones: ["+91 90000 00025"], emails: ["devika@example.org"])}