Cotton code
451 lines · 22.3 KB · SwiftRaw
// The PERSON as a ROLODEX CARD (the coordinator's pick for People, 29 Oct// 2026, after the owner's "most of your things look good"; the person picture// `objects-2/people/1-rolodex`): a cream card held upright on a 1960s rotary// card file, its two notches seated over the rail under two steel rings,// the fan of cards behind with their faded tabs, the cradle's knurled knobs// either side, standing bare on the people's amethyst desk// (`FaceGround.amethystDesk`) with no paper and no rule of the deck's. The file// and its turn are the shared rolodex (`Rolodex`, Shared/Rolodex.swift); the// blank photographic print is PAINTED (`rolodex-print`); the face types live// on the front card only what the card decides:////   the portrait in the print's window, pasted at the card's top left; a//   card with no photograph keeps the blank print, its initials pencilled//   on it.//   the NAME struck heavy on the typewriter above the first rule, right of//   the print: one line, two when it must, the type taken down a little//   before a third would be wanted, and a name longer still stops at the//   second line's last whole word.//   on the four rules under it, typed: the number, the email, the corner's//   "why now" (a birthday this week, or how long since you spoke — red when//   it is a birthday or owed) and the subtitle (role, organisation, city, as//   the core joins them). A line squeezes to its rule rather than break.//   at the foot, pencilled in the script hand across the card: when you last//   spoke, and where.//// A line the card does not carry is a bare rule: never a placeholder word.// Each line is its part (`facePart`): the print the picture, the name the// title, the number the call, the email the email, the corner the when, the// subtitle the subtitle, the foot the message. Stepped by a tap beside its// parts, it turns about its rail (`FaceStep.turns`); the shell supplies// the window of neighbours and signed travel, then commits the selection at// rest.//// Every word is the core's (`DeckCard`: the fields, the corner, the ways it// reaches the person), the same card the person's own face draws.import CottonPaperimport CottonValuesimport CoreTextimport SwiftUIenum RolodexFaceKnobs {    // THE PRINT (`rolodex-print`): its window as shares of it; where it is    // pasted on the card and its side, as shares of the card's width (its    // top as a share of the card's height); the turn it was pasted at.    static let window = CGRect(x: 0.0593, y: 0.0651, width: 0.9397 - 0.0593, height: 0.937 - 0.0651)    static let printLeft: CGFloat = 0.058    static let printTop: CGFloat = 0.04    static let printSide: CGFloat = 0.32    static let printTurn: Double = -1.2    /// The pencilled initials on a blank print, as a share of its window.    static let initials: CGFloat = 0.42    // THE WRITING, as shares of the card: print on an object scales with the    // object, never with Dynamic Type. The name and the facts start this far    // in (right of the print) and stop this far from the right edge; the    // foot runs from its own lead.    static let lead: CGFloat = 0.45    static let trail: CGFloat = 0.04    static let footLead: CGFloat = 0.06    /// The name's type, as a share of the card's height; the least it is    /// taken down to before it stops at a whole word; its last line's    /// baseline above the first rule; its lines' step, in its size.    static let nameSize: CGFloat = 0.098    static let nameLeast: CGFloat = 0.72    static let nameLines = 2    static let nameOver: CGFloat = 0.085    static let nameStep: CGFloat = 1.08    /// The struck-heavy name's second strike, in its size.    static let strike: CGFloat = 0.025    /// A fact's type and its baseline above its rule.    static let lineSize: CGFloat = 0.064    static let lineOver: CGFloat = 0.022    /// The foot's script and its baseline.    static let footSize: CGFloat = 0.08    static let footBase: CGFloat = 0.815    /// A typed letter's top over its baseline, in its size: what must clear    /// the print for a line to start under it.    static let ascent: CGFloat = 0.75}/// A person's card as the rolodex types it: the name's lines and the size/// they are struck at, and the facts on the rules under it, each nil where/// the card has none (a bare rule).public struct RolodexCard: Equatable, Sendable {    public var name: [String]    /// The name's type, as a share of the card's height.    public var nameSize: CGFloat    public var number: String?    public var email: String?    public var corner: String?    /// The corner is typed in the ribbon's red: a birthday, or owed.    public var cornerRed: Bool    public var subtitle: String?    public var foot: String?    /// What a blank print carries: the name's initials.    public var initials: String?    /// The facts under the print are typed from its left edge    /// (`RolodexSetting.factRoom`).    public var wide: Bool    /// The facts under the name, in their order down the rules.    public var facts: [String?] { [number, email, corner, subtitle] }}/// How a person's card is typed on the rolodex.public enum RolodexSetting {    /// `card` typed on a front card `size` points.    public static func set(_ card: DeckCard, size: CGSize) -> RolodexCard {        let name = card.text("title").map { $0.split(whereSeparator: \.isNewline).joined(separator: " ").trimmingCharacters(in: .whitespaces) } ?? ""        let (lines, share) = nameLines(name, width: room(size).width, height: size.height)        let corner = card.corner.flatMap { $0.isEmpty ? nil : $0 }        let birthday = corner.flatMap { SaidRun.cut($0, by: "corner.birthday") } != nil        var typed = RolodexCard(            name: lines, nameSize: share,            number: first(card.reach.phones),            email: first(card.reach.emails),            corner: corner, cornerRed: corner != nil && (birthday || card.pressing),            subtitle: card.text("subtitle"),            foot: card.text("reached"),            initials: CardPerson.initials(name),            wide: false)        let column = room(size).width        typed.wide = typed.facts.indices.contains { place in            guard underPrint(place, size: size), let words = typed.facts[place] else { return false }            return factWidth(words, height: size.height) > column        }        return typed    }    private static func first(_ values: [String]) -> String? {        values.lazy.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.first { !$0.isEmpty }    }    /// The writing's room across a card `size` points: where the name and    /// the facts start and how wide they may run.    static func room(_ size: CGSize) -> (lead: CGFloat, width: CGFloat) {        let knobs = RolodexFaceKnobs.self        return (knobs.lead * size.width, (1 - knobs.trail - knobs.lead) * size.width)    }    /// A fact's baseline, by its place under the name (0 the number, 1 the    /// email, 2 the corner, 3 the subtitle), on a card `size` points: just    /// above its rule.    public static func factBaseline(_ place: Int, size: CGSize) -> CGFloat {        let knobs = RolodexFaceKnobs.self        return (RolodexKnobs.rules[place + 1] - knobs.lineOver) * size.height    }    /// The fact at `place` stands under the print: its letters clear the    /// print's foot.    public static func underPrint(_ place: Int, size: CGSize) -> Bool {        let knobs = RolodexFaceKnobs.self        let foot = knobs.printTop * size.height + knobs.printSide * size.width        return factBaseline(place, size: size) - knobs.ascent * knobs.lineSize * size.height > foot    }    /// Where the fact at `place` starts and how wide it may run: in the    /// column beside the print, or, on a card whose facts under the print    /// do not all fit the column (`wide`), those facts from the print's    /// left edge, together, as a typist starts the lines below a photograph    /// further left; a line too long even for that is squeezed.    public static func factRoom(_ place: Int, wide: Bool, size: CGSize) -> (lead: CGFloat, width: CGFloat) {        let knobs = RolodexFaceKnobs.self        guard wide, underPrint(place, size: size) else { return room(size) }        let lead = knobs.printLeft * size.width        return (lead, (1 - knobs.trail) * size.width - lead)    }    /// `words` typed at a fact's size on a card `height` points: how wide.    static func factWidth(_ words: String, height: CGFloat) -> CGFloat {        let set = NSAttributedString(            string: words, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): typeFont(RolodexFaceKnobs.lineSize * height)])        return CGFloat(CTLineGetTypographicBounds(CTLineCreateWithAttributedString(set), nil, nil, nil))    }    /// The name's lines at `width`, on a card `height` points: one line at    /// the name's size when it fits, else two; a name that wants a third is    /// taken down step by step to the least, and stops there at the second    /// line's last whole word, with no ellipsis. An oversized word shrinks    /// to fit before it may split at the floor, with an explicit hyphen.    public static func nameLines(_ name: String, width: CGFloat, height: CGFloat) -> (lines: [String], size: CGFloat) {        let knobs = RolodexFaceKnobs.self        guard !name.isEmpty else { return ([], knobs.nameSize) }        // Taken down in steps of 4% of its size, to the least and no further.        let steps = Int(((1 - knobs.nameLeast) / 0.04).rounded())        let sizes = (0...steps).map { knobs.nameSize * (1 - 0.04 * CGFloat($0)) }        let words = name.split(whereSeparator: \.isWhitespace).map(String.init)        let fit = NameFit.lines(words, sizes: sizes, limit: knobs.nameLines) { share in            let font = typeFont(share * height)            return { text in                let set = NSAttributedString(string: text, attributes: [                    NSAttributedString.Key(kCTFontAttributeName as String): font])                return CGFloat(CTLineGetTypographicBounds(CTLineCreateWithAttributedString(set), nil, nil, nil)) <= width            }        }        return (Array(fit.lines.prefix(knobs.nameLines)), fit.size)    }    /// The typewriter's face at `points`, for CoreText to measure by.    static func typeFont(_ points: CGFloat) -> CTFont {        // Asked of CottonFonts first, so the bundled faces are registered        // before CoreText is asked for them by name.        _ = CottonFonts.type(1)        return CTFontCreateWithName(CottonFonts.typeFace as CFString, points.isFinite ? max(points, 1) : 1, nil)    }}public struct RolodexFace: View {    @Environment(\.faceRelatedOpening) private var openRelated    let card: DeckCard    /// The record's photograph, filling the print's window; nil keeps the    /// print blank, with the initials.    let photo: FacePicture?    public init(card: DeckCard, photo: FacePicture?) {        self.card = card        self.photo = photo    }    public var body: some View {        Rolodex(card: card, photo: photo, picture: { $0.text("photo").map { FacePicture(key: $0, edge: 420) } }) { leaf in            FrontCard(card: leaf.card, photo: leaf.photo, size: leaf.size, nameOnly: leaf.nameOnly)        } name: { card, size in            RiffleName(card: card, size: size)        } under: { width in            VStack(alignment: .leading, spacing: 12) {                Text(ShellLines.line("cards", "opened.file_index"))                if card.relatedReadFailed { Text(ShellLines.line("cards", "opened.index_failed")) }                ForEach(card.related) { group in                    Button { openRelated?(group.id) } label: {                        Text(group.said).frame(maxWidth: .infinity, alignment: .leading)                    }.buttonStyle(.plain).accessibilityIdentifier("person-index-\(group.id)")                }            }            .font(CottonFonts.type(15)).foregroundStyle(PeopleMaterial.card.colour)            .padding(.horizontal, width * 0.1)        }    }}/// The front card's own: the print pasted at its top left, and the typing/// on its rules, over the file's painted card (`Rolodex`).private struct FrontCard: View {    let card: DeckCard    let photo: FacePicture?    let size: CGSize    var nameOnly = false    var body: some View {        let knobs = RolodexFaceKnobs.self        let w = size.width        let h = size.height        let typed = RolodexSetting.set(card, size: size)        let room = RolodexSetting.room(size)        let rule = { (index: Int) in RolodexKnobs.rules[index] * h }        let lineSize = knobs.lineSize * h        let side = knobs.printSide * w        ZStack(alignment: .topLeading) {            if !nameOnly {                Print(photo: photo, initials: typed.initials, side: side)                    .rotationEffect(.degrees(knobs.printTurn))                    .facePart(.picture)                    .offset(x: knobs.printLeft * w, y: knobs.printTop * h)            }            Group {                if !typed.name.isEmpty {                    let size = typed.nameSize * h                    let last = rule(0) - knobs.nameOver * h                    let baselines = typed.name.indices.map { last - CGFloat(typed.name.count - 1 - $0) * knobs.nameStep * size }                    RolodexTyped(lines: typed.name, baselines: baselines, font: CottonFonts.type(size), size: size, ink: PeopleMaterial.ink.colour, width: room.width, strike: knobs.strike * size)                        .accessibilityRepresentation { Text(typed.name.joined(separator: " ")).accessibilityAddTraits(.isHeader) }                        .accessibilityIdentifier("face-name")                        .facePart(.title)                        .offset(x: room.lead, y: RolodexTyped.top(baselines, size: size))                }                if !nameOnly {                    fact(typed, 0, part: .call, id: "rolodex-number", size: lineSize)                    fact(typed, 1, part: .email, id: "rolodex-email", size: lineSize)                    fact(typed, 2, part: .when, id: "face-corner", size: lineSize, red: typed.cornerRed)                    fact(typed, 3, part: .subtitle, id: "rolodex-subtitle", size: lineSize)                    if let foot = typed.foot {                        let size = knobs.footSize * h                        let base = [knobs.footBase * h]                        RolodexTyped(lines: [foot], baselines: base, font: CottonFonts.signature(size), size: size, ink: PeopleMaterial.graphite.colour, width: (1 - knobs.footLead - knobs.trail) * w)                            .accessibilityRepresentation { Text(foot) }                            .accessibilityIdentifier("rolodex-foot")                            .offset(x: knobs.footLead * w, y: RolodexTyped.top(base, size: size))                    }                }            }            // Ink soaks into the card: the typing multiplies over the paint.            .blendMode(.multiply)        }        .frame(width: w, height: h, alignment: .topLeading)    }    /// One fact typed on its rule, its part; nothing where the card has    /// none, so the rule stands bare.    @ViewBuilder    private func fact(_ typed: RolodexCard, _ place: Int, part: FacePart, id: String, size: CGFloat, red: Bool = false) -> some View {        if let words = typed.facts[place] {            let base = [RolodexSetting.factBaseline(place, size: self.size)]            let room = RolodexSetting.factRoom(place, wide: typed.wide, size: self.size)            RolodexTyped(lines: [words], baselines: base, font: CottonFonts.type(size), size: size, ink: (red ? PeopleMaterial.red : PeopleMaterial.ink).colour, width: room.width)                .accessibilityRepresentation { Text(words) }                .accessibilityIdentifier(id)                .facePart(part)                .offset(x: room.lead, y: RolodexTyped.top(base, size: size))        }    }}/// The square print pasted on the card: the painted blank print (or its/// stand-in), the portrait in its window, or the initials pencilled on it.private struct Print: View {    let photo: FacePicture?    let initials: String?    let side: CGFloat    var body: some View {        let window = RolodexFaceKnobs.window        ZStack(alignment: .topLeading) {            if let print = rolodexPainted("rolodex-print") {                print.resizable().interpolation(.high)                    .frame(width: side, height: side)                    .accessibilityHidden(true)            } else {                Rectangle().fill(PeopleMaterial.print.colour)                    .frame(width: side, height: side)                    .accessibilityHidden(true)            }            Group {                if let photo {                    photo                        .frame(width: window.width * side, height: window.height * side)                        .clipped()                } else if let initials {                    Text(initials)                        .font(CottonFonts.signature(RolodexFaceKnobs.initials * window.height * side))                        .foregroundStyle(PeopleMaterial.graphite.colour)                        .lineLimit(1)                        .minimumScaleFactor(0.5)                        .frame(width: window.width * side, height: window.height * side)                        .blendMode(.multiply)                        .accessibilityHidden(true)                }            }            .offset(x: window.minX * side, y: window.minY * side)        }        .frame(width: side, height: side, alignment: .topLeading)        .accessibilityElement(children: .ignore)        .accessibilityIdentifier("rolodex-print")    }}/// The rolodex, by its id beside the person's own face, and the people it is/// reviewed in: invented people, stand-in numbers and example.org mail only./// The specimen world's today is Thursday 29 October 2026; a corner and a/// last-spoke line are the core's words (`corner.birthday`,/// `corner.not_reached`, `field.reached`).public enum RolodexFaceCatalogue {    public static let spinSpecimens: [Specimen] = ["Ada", "Bela", "Cora", "Dara", "Esha", "Fara", "Gita", "Hana", "Ira", "Jaya", "Kira", "Lila"].map { name in        Specimen("spin-\(name.lowercased())", person(phones: ["+91 99000 00000"], emails: ["specimen@example.org"],            ["title": .text("\(name) Sample"), "subtitle": .text("Synthetic specimen"), "reached": .text("Last spoke yesterday")]))    }    public static let stock: FaceStock = .own    public static let ground: FaceGround = .amethystDesk    public static var opened: DeckCard {        var card = friend        card.related = [("thread", "4 threads", 4), ("photo", "12 photos", 12), ("event", "3 events", 3), ("todo", "1 todo", 1)]            .map { CardRelatedCount(id: $0.0, said: $0.1, count: $0.2) }        return card    }    public static let face = Face(id: "person.rolodex", specimens: [        Specimen("opened", opened, picture: "rolodex-friend", opened: true),        Specimen("friend", friend, picture: "rolodex-friend"),        Specimen("ananya", ananya, picture: "rolodex-ananya"),        Specimen("no-portrait", noPortrait),        Specimen("sparse", sparse),        Specimen("long-name", longName, picture: "portrait"),    ], steps: .turns, spins: spinSpecimens) { card, picture, _ in        RolodexFace(card: card, photo: picture)    }    static func person(corner: String? = nil, pressing: Bool = false, phones: [String] = [], emails: [String] = [], _ fields: [String: RecordValue]) -> DeckCard {        var card = DeckCard(face: "person.rolodex", corner: corner, pressing: pressing, pace: nil, plate: nil, fields: fields)        card.reach = CardReach(phones: phones, emails: emails, call: !phones.isEmpty, message: !phones.isEmpty, email: !emails.isEmpty)        return card    }    /// The picture's man: every line of the card typed.    public static let friend = person(        corner: "Birthday Sunday", phones: ["+91 98765 43210"], emails: ["rahul@example.org"],        [            "title": .text("Rahul Mehta"),            "subtitle": .text("College friend · Pune"),            "reached": .text("Last spoke 2 days ago on WhatsApp"),        ])    /// Her birthday is today.    public static let ananya = person(        corner: "Birthday today", phones: ["+91 90000 01234"], emails: ["ananya@example.org"],        [            "title": .text("Ananya Rao"),            "subtitle": .text("Cousin · Chennai"),            "reached": .text("Last spoke yesterday on WhatsApp"),        ])    /// No photograph: the blank print keeps her initials.    public static let noPortrait = person(        corner: "Not reached in 6 weeks", phones: ["+91 99999 00012"], emails: ["meera@example.org"],        [            "title": .text("Meera Iyer"),            "subtitle": .text("Architect · Studio Iyer · Bengaluru"),            "reached": .text("Last spoke 6 weeks ago on Instagram"),        ])    /// A name and a number, the rest of the rules bare.    public static let sparse = person(phones: ["0484 2000 000"], ["title": .text("Dr Nair's clinic")])    /// A name that takes two lines at a smaller type, an email and a    /// subtitle too long for the column typed from the card's left.    public static let longName = person(        corner: "Not reached in 3 months", pressing: true,        phones: ["+91 98888 80000"], emails: ["lakshmi.narasimhan@example.org"],        [            "title": .text("Venkata Lakshmi Narasimhan"),            "subtitle": .text("Professor · Coastal University · Chennai"),            "reached": .text("Last spoke 3 months ago on WhatsApp"),        ])}/// The current card's name follows every wheel frame, including within a letter.struct RiffleName: View {    let card: DeckCard    let size: CGSize    var body: some View {        let k = RolodexFaceKnobs.self        let typed = RolodexSetting.set(card, size: size)        let fontSize = typed.nameSize * size.height        let last = (RolodexKnobs.rules[0] - k.nameOver) * size.height        let baselines = typed.name.indices.map { last - CGFloat(typed.name.count - 1 - $0) * k.nameStep * fontSize }        RolodexTyped(lines: typed.name, baselines: baselines, font: CottonFonts.type(fontSize), size: fontSize,              ink: PeopleMaterial.ink.colour, width: RolodexSetting.room(size).width, strike: k.strike * fontSize)            .offset(x: RolodexSetting.room(size).lead, y: RolodexTyped.top(baselines, size: fontSize))    }}