Cotton code
374 lines · 17.7 KB · SwiftRaw
// The EVENT as a ROLODEX CARD (owner, 3 Nov 2026: "for calendar can you add// another face that looks and works very similar to Rolodex"): the shared// rotary card file (`Rolodex`), turned on its rail as People's is, standing// on the calendar's bottle-green baize. The card is the design session's// (3 Nov 2026), and everything typed on it is here, in `EventRolodexFront`// and its knobs, and nowhere else:////   the tab, at the card's top left: the day, "Thu 5"; an event over several//   days its first to its last, "5 to 7"; a small dot in the accent beside//   it while an invitation waits for an answer.//   the big line, struck heavy where the person's name sits: the time,//   "6:30 am", its end after it when it has one, "6:30 am to 8:00 pm"; an//   all-day event "All day".//   on the two rules under it, typed: the title, one line, a second when it//   must, never cut.//   on the rule under that: the details joined by middle dots, the place//   and who it is with (first names, "+N" past three).//   a past event, or one declined, sits on the rail dimmed (`Rolodex`'s dim).//// Every word is the core's (`DeckCard`: `date` and `ends` as the core says// them, the face only parting them where the core joined a day and a clock;// `title`, `place`, `people`; `state` while the reply is wanted; the pace// band) or a shipped line (`cards` `rolodex.*`, `dates` `all_day`,// `people.more`). A line the card does not carry is a bare rule. Each line// is its part (`facePart`), as the invitation tags them: the tab and the// time the when, the title the title, the place the place, who it is with// the people.import CottonPaperimport CottonValuesimport CoreTextimport SwiftUIenum EventRolodexKnobs {    /// The writing's lead and trail, as shares of the card's width.    static let lead: CGFloat = 0.06    static let trail: CGFloat = 0.04    /// The tab's type and baseline, and the dot's side and the gap before    /// it, as shares of the card's height.    static let tabSize: CGFloat = 0.07    static let tabBase: CGFloat = 0.115    static let dotSide: CGFloat = 0.045    static let dotGap: CGFloat = 0.03    /// The big line's type, struck heavy, and its baseline above the first    /// rule (the person's name's).    static let timeSize: CGFloat = 0.098    static let timeOver: CGFloat = 0.085    static let strike: CGFloat = 0.025    /// The title's type and how many rules it may take.    static let titleSize: CGFloat = 0.075    static let titleLines = 2    /// The details' type and the rule they stand on; a line's baseline    /// above its rule.    static let lineSize: CGFloat = 0.064    static let detailRule = 3    static let lineOver: CGFloat = 0.022    /// First names said before the rest are counted ("+2").    static let names = 3}/// An event's card as the rolodex types it: each nil or empty where the/// card has none (a bare rule).public struct EventRolodexCard: Equatable, Sendable {    public var tab: String?    /// An invitation waits for the person's answer: the accent's dot.    public var asks: Bool    public var time: String?    public var title: [String]    /// The details in their order, each with its part: the place, who.    public var details: [EventRolodexDetail]    /// Past or declined: the card sits dimmed.    public var dimmed: Bool}public struct EventRolodexDetail: Equatable, Sendable {    public var words: String    public var part: FacePart}/// How an event's card is typed on the rolodex.public enum EventRolodexSetting {    /// `card` typed on a front card `size` points.    public static func set(_ card: DeckCard, size: CGSize) -> EventRolodexCard {        let knobs = EventRolodexKnobs.self        let date = card.text("date").flatMap { $0 == ShellLines.line("cards", "date.add") ? nil : $0 }        let title = card.text("title").map { $0.split(whereSeparator: \.isNewline).joined(separator: " ") } ?? ""        var details: [EventRolodexDetail] = []        if let place = card.text("place") { details.append(EventRolodexDetail(words: place, part: .place)) }        if let with = with(card) { details.append(EventRolodexDetail(words: with, part: .people)) }        return EventRolodexCard(            tab: date.flatMap { tab($0, ends: card.text("ends")) },            asks: card.text("state") != nil,            time: date.map { time($0, ends: card.text("ends")) },            title: wrapped(title, width: width(size), points: knobs.titleSize * size.height, lines: knobs.titleLines),            details: details,            dimmed: card.pace == .late || card.pace == .done)    }    /// The tab's words: "Thu 5", or "5 to 7" for an event that ends on a    /// later day.    public static func tab(_ date: String, ends: String?) -> String {        let start = EventWhen(date)        let first = dayNumber(start)        if let ends, endsLater(ends) {            let last = dayNumber(EventWhen(ends))            if last != first { return ShellLines.line("cards", "rolodex.days", ["from": first, "to": last]) }        }        return ShellLines.line("cards", "rolodex.day", ["weekday": start.weekday, "day": first])    }    /// The big line: the clock, with the end's clock after it when it has    /// one; a day with no clock, all day.    public static func time(_ date: String, ends: String?) -> String {        guard let clock = EventWhen(date).clock else { return ShellLines.line("dates", "all_day") }        guard let ends else { return clock }        let end = endsLater(ends) ? EventWhen(ends).clock : ends        guard let end, EventHands.time(end) != nil else { return clock }        return ShellLines.line("cards", "rolodex.times", ["start": clock, "end": end])    }    /// Who it is with: "with Ananya, Rahul, Meera +2".    static func with(_ card: DeckCard) -> String? {        let names = card.entries("people").compactMap { $0["name"]?.text }.filter { !$0.isEmpty }.map(CardPerson.firstName)        guard !names.isEmpty else { return nil }        let shown = EventRolodexKnobs.names        var said = names.prefix(shown).joined(separator: ShellLines.line("home", "done.separator"))        if names.count > shown { said += " " + ShellLines.line("cards", "people.more", ["n": String(names.count - shown)]) }        return ShellLines.line("cards", "rolodex.with", ["names": said])    }    /// The core says an end on the start's day as its clock alone, and an    /// end on a later day as that day, with its clock when it keeps one.    private static func endsLater(_ ends: String) -> Bool {        ends.contains(EventWhen.join) || EventHands.time(ends) == nil    }    /// The day of the month in a weekday date's words ("29 Oct": "29").    private static func dayNumber(_ when: EventWhen) -> String {        when.day.split(separator: " ").first.map(String.init) ?? when.day    }    /// The writing's room across a card `size` points: where it starts and    /// how wide it may run.    static func room(_ size: CGSize) -> (lead: CGFloat, width: CGFloat) {        (EventRolodexKnobs.lead * size.width, width(size))    }    private static func width(_ size: CGSize) -> CGFloat {        (1 - EventRolodexKnobs.lead - EventRolodexKnobs.trail) * size.width    }    /// The baseline of the line typed on rule `index`, on a card `size`.    public static func baseline(onRule index: Int, size: CGSize) -> CGFloat {        (RolodexKnobs.rules[index] - EventRolodexKnobs.lineOver) * size.height    }    /// `words` typed at `points`: how wide.    static func measure(_ words: String, points: CGFloat) -> CGFloat {        let set = NSAttributedString(string: words, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): RolodexSetting.typeFont(points)])        return CGFloat(CTLineGetTypographicBounds(CTLineCreateWithAttributedString(set), nil, nil, nil))    }    /// `words` broken at whole words into at most `lines` lines `width`    /// wide at `points`; what will not fit runs on in the last, which the    /// typing squeezes to its rule: never cut.    static func wrapped(_ words: String, width: CGFloat, points: CGFloat, lines: Int) -> [String] {        var out: [String] = []        for word in words.split(whereSeparator: \.isWhitespace).map(String.init) {            if let last = out.last, out.count == lines || measure(last + " " + word, points: points) <= width {                out[out.count - 1] = last + " " + word            } else {                out.append(word)            }        }        return out    }    /// The details laid along their rule, the middle dot between each two    /// (a piece of no part): each piece's words, part, lead and width, all    /// squeezed together when the whole line is wider than the room.    static func laid(_ details: [EventRolodexDetail], size: CGSize) -> [(words: String, part: FacePart?, lead: CGFloat, width: CGFloat)] {        let points = EventRolodexKnobs.lineSize * size.height        let join = ShellLines.line("cards", "join")        var pieces: [(words: String, part: FacePart?)] = []        for detail in details {            if !pieces.isEmpty { pieces.append((join, nil)) }            pieces.append((detail.words, detail.part))        }        let room = room(size)        let widths = pieces.map { measure($0.words, points: points) }        let whole = widths.reduce(0, +)        let squeeze = whole > room.width ? room.width / whole : 1        var lead = room.lead        return zip(pieces, widths).map { piece, width in            defer { lead += width * squeeze }            return (piece.words, piece.part, lead, width * squeeze)        }    }}public struct EventRolodexFace: View {    let card: DeckCard    public init(card: DeckCard) {        self.card = card    }    public var body: some View {        Rolodex(card: card, photo: nil, picture: { _ in nil }, dims: { EventRolodexSetting.set($0, size: .zero).dimmed }) { leaf in            EventRolodexFront(card: leaf.card, size: leaf.size, headOnly: leaf.nameOnly)        } name: { card, size in            EventRolodexHead(typed: EventRolodexSetting.set(card, size: size), size: size)        } under: { _ in            EmptyView()        }    }}/// The front card's own typing, over the file's painted card.private struct EventRolodexFront: View {    let card: DeckCard    let size: CGSize    /// The wheel goes by at reading speed: the tab and the time alone.    let headOnly: Bool    var body: some View {        let knobs = EventRolodexKnobs.self        let typed = EventRolodexSetting.set(card, size: size)        let room = EventRolodexSetting.room(size)        let h = size.height        ZStack(alignment: .topLeading) {            Group {                EventRolodexHead(typed: typed, size: size)                if !headOnly {                    if !typed.title.isEmpty {                        let points = knobs.titleSize * h                        let baselines = typed.title.indices.map { EventRolodexSetting.baseline(onRule: $0 + 1, size: size) }                        RolodexTyped(lines: typed.title, baselines: baselines, font: CottonFonts.type(points), size: points, ink: PeopleMaterial.ink.colour, width: room.width)                            .accessibilityRepresentation { Text(typed.title.joined(separator: " ")).accessibilityAddTraits(.isHeader) }                            .accessibilityIdentifier("deck-title")                            .facePart(.title)                            .offset(x: room.lead, y: RolodexTyped.top(baselines, size: points))                    }                    let points = knobs.lineSize * h                    let base = [EventRolodexSetting.baseline(onRule: knobs.detailRule, size: size)]                    ForEach(Array(EventRolodexSetting.laid(typed.details, size: size).enumerated()), id: \.offset) { _, piece in                        let typing = RolodexTyped(lines: [piece.words], baselines: base, font: CottonFonts.type(points), size: points,                                                  ink: PeopleMaterial.ink.colour, width: piece.width)                        if let part = piece.part {                            typing                                .accessibilityRepresentation { Text(piece.words) }                                .accessibilityIdentifier(part == .place ? "rolodex-place" : "rolodex-with")                                .facePart(part)                                .offset(x: piece.lead, y: RolodexTyped.top(base, size: points))                        } else {                            typing.accessibilityHidden(true)                                .offset(x: piece.lead, y: RolodexTyped.top(base, size: points))                        }                    }                }            }            // Ink soaks into the card: the typing multiplies over the paint.            .blendMode(.multiply)        }        .frame(width: size.width, height: size.height, alignment: .topLeading)    }}/// The tab and the time: the day at the card's top left, with the accent's/// dot while an invitation waits, and the time struck heavy where the/// person's name sits; nothing where the card has no date.private struct EventRolodexHead: View {    let typed: EventRolodexCard    let size: CGSize    var body: some View {        let knobs = EventRolodexKnobs.self        let room = EventRolodexSetting.room(size)        ZStack(alignment: .topLeading) {            if let tab = typed.tab {                let points = knobs.tabSize * size.height                let base = [knobs.tabBase * size.height]                let width = EventRolodexSetting.measure(tab, points: points)                RolodexTyped(lines: [tab], baselines: base, font: CottonFonts.type(points), size: points,                             ink: PeopleMaterial.ink.colour, width: min(room.width, width * 1.05))                    .accessibilityRepresentation { Text(tab) }                    .accessibilityIdentifier("rolodex-tab")                    .facePart(.when)                    .offset(x: room.lead, y: RolodexTyped.top(base, size: points))                if typed.asks {                    let side = knobs.dotSide * size.height                    Circle().fill(PeopleMaterial.red.colour)                        .frame(width: side, height: side)                        .accessibilityHidden(true)                        .offset(x: room.lead + width * 1.05 + knobs.dotGap * size.height,                                y: knobs.tabBase * size.height - points * 0.35 - side / 2)                }            }            if let time = typed.time {                let points = knobs.timeSize * size.height                let base = [(RolodexKnobs.rules[0] - knobs.timeOver) * size.height]                RolodexTyped(lines: [time], baselines: base, font: CottonFonts.type(points), size: points,                             ink: PeopleMaterial.ink.colour, width: room.width, strike: knobs.strike * points)                    .accessibilityRepresentation { Text(time) }                    .accessibilityIdentifier("face-when")                    .facePart(.when)                    .offset(x: room.lead, y: RolodexTyped.top(base, size: points))            }        }        .frame(width: size.width, height: size.height, alignment: .topLeading)    }}/// The event's rolodex, by its id beside the board and the invitation, and/// the cards it is reviewed in: invented events, places and guests only.public enum EventRolodexFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .kitchenTile    public static let face = Face(id: "event.rolodex", specimens: [        Specimen("dinner", dinner),        Specimen("all-day", allDay),        Specimen("days", days),        Specimen("invitation", invitation),        Specimen("past", past),    ], steps: .turns) { card, _, _ in        EventRolodexFace(card: card)    }    static func event(pace: DeckPace? = .soon, _ fields: [String: RecordValue]) -> DeckCard {        DeckCard(face: "event.rolodex", corner: nil, pressing: false, pace: pace, plate: nil, fields: fields)    }    /// A dinner with its end, its place and five guests: three first names    /// and the count of the rest.    public static let dinner = event([        "title": .text("Dinner at Ananya\u{2019}s"),        "date": .text("Thu 5 Nov\(EventWhen.join)6:30 pm"),        "ends": .text("10:00 pm"),        "place": .text("Indiranagar"),        "people": .list(["Ananya Rao", "Rahul Mehta", "Meera Iyer", "Kabir Das", "Nila"].map { .object(["name": .text($0)]) }),    ])    /// An all-day day: all day, and its day on the tab.    public static let allDay = event([        "title": .text("Diwali"),        "date": .text("Sun 8 Nov"),        "place": .text("Home, Pune"),    ])    /// Three days away: the tab says its first day to its last.    public static let days = event(pace: .upcoming, [        "title": .text("Hampi with the college lot"),        "date": .text("Thu 12 Nov\(EventWhen.join)6:00 am"),        "ends": .text("Sat 14 Nov\(EventWhen.join)9:00 pm"),        "place": .text("Hampi"),        "people": .list(["Rahul Mehta", "Ira Sen"].map { .object(["name": .text($0)]) }),    ])    /// An invitation not yet answered: the accent's dot on the tab; a long    /// title on two rules.    public static let invitation = event([        "title": .text("Call with the architects about the studio drawings"),        "date": .text("Fri 6 Nov\(EventWhen.join)4:00 pm"),        "ends": .text("5:00 pm"),        "people": .list(["Meera Iyer", "Arjun Shah"].map { .object(["name": .text($0)]) }),        "state": .text("Needs action"),    ])    /// Gone by: dimmed on the rail; no place and no people, their rule bare.    public static let past = event(pace: .late, [        "title": .text("Pick up the cake"),        "date": .text("Tue 3 Nov\(EventWhen.join)11:00 am"),    ])}