Cotton code
435 lines · 20.2 KB · SwiftRaw
// The EVENT face (Calendar, reference `calendar.png`): a cream card inside// its printed notched frame. At the top left the day written large by hand// over two lines — the weekday, then the date — with a red pen stroke under// it; at the top right the alarm-clock picture, its hands at the event's// start (none for a day with no clock). Under them the title typed// heavy, then typed lines: the subtitle (who, how often), the clock and// when it ends (`ends`) — or "All day" for a day with no clock, and the day// it runs until — how it repeats (`repeats`), the place, "With" and the people's// names, the people as round mounts, the notes; and the corner's// "why now" ("in 6 days", "Today") typed and ringed in red at the bottom// right. With no notes the title stands lower, under open room, as the// references set it, so a short event fills its card. Every word is the core's (`DeckCard`):// the face only lays out the date place's own words — its day before the// core's join, its clock after.import CottonPaperimport CoreTextimport CottonValuesimport SwiftUIenum EventFaceKnobs {    static let inset = EdgeInsets(top: 30, leading: 30, bottom: 26, trailing: 24)    static let weekdayHand: CGFloat = 46    static let dayHand: CGFloat = 52    static let handLeading: CGFloat = -18    /// The alarm clock's width as a share of the card's.    static let artShare: CGFloat = 0.38    /// Where the hands turn on the clock picture, as shares of its width and    /// height — measured off `face-art-clock`'s handless dial, so a redrawn    /// clock owes new knobs.    static let clockHub = CGPoint(x: 0.518, y: 0.517)    /// Each hand's reach from the hub and its widest, as shares of the    /// picture's width: the minute hand stops short of the numerals.    static let hourReach: CGFloat = 0.19    static let minuteReach: CGFloat = 0.245    static let hourWidth: CGFloat = 0.036    static let minuteWidth: CGFloat = 0.03    /// How far a hand's tail reaches back past the hub, as a share of the    /// picture's width.    static let handTail: CGFloat = 0.035    /// Where along its reach a hand is widest, and its width at the hub, as    /// shares of its reach and of its widest: a narrow shaft to a spade.    static let handSwell: CGFloat = 0.74    static let handNeck: CGFloat = 0.4    /// The boss the hands turn on and its red ring, as shares of the    /// picture's width.    static let boss: CGFloat = 0.052    static let bossRing: CGFloat = 0.009    /// The most room let open under the day and the clock on a card with no    /// notes: it shares the card's spare room with the foot, so a full card    /// gives it up first.    static let headRoom: CGFloat = 56    static let titleSize: CGFloat = 34    static let lineSize: CGFloat = 19    static let lineGap: CGFloat = 8    static let bodySize: CGFloat = 13    static let personMount: CGFloat = 42    static let personGap: CGFloat = 10    /// The room between "With" and the names: a typed space.    static let withGap: CGFloat = 10    /// The lines the names after "With" take; names that need more are told    /// shorter (`EventNames`).    static let withLines = 2    static let swash = CGSize(width: 150, height: 13)}/// A date place's words parted where the core joined them: the day/// ("Thu 29 Oct") and the clock ("4:30 pm") after the join (`FACT_JOIN`).public struct EventWhen: Equatable {    public var weekday: String    public var day: String    public var clock: String?    /// The core's join between a date's day and its clock.    static let join = " \u{00B7} "    public init(_ words: String) {        let parts = words.components(separatedBy: Self.join)        let day = parts[0].split(separator: " ", maxSplits: 1).map(String.init)        // "Thu 29 Oct" writes as "Thu" over "29 Oct"; a day said as one word        // ("Today") stands alone.        weekday = day.count > 1 ? day[0] : ""        self.day = day.count > 1 ? day[1] : parts[0]        clock = parts.count > 1 ? parts[1...].joined(separator: Self.join) : nil    }}extension EventWhen {    /// A date place's words parted where the core joined them: the day,    /// and the clock after the join when it has one.    static func parted(_ words: String) -> (day: String, clock: String?) {        let parts = words.components(separatedBy: join)        return (parts[0], parts.count > 1 ? parts[1...].joined(separator: join) : nil)    }}public struct EventFace: View {    let card: DeckCard    public init(card: DeckCard) {        self.card = card    }    public var body: some View {        let when = card.text("date").map(EventWhen.init)        // A dated day with no clock is the whole day; an undated event's        // "Add date" is no day at all.        let allDay = when != nil && when?.clock == nil && card.text("date") != ShellLines.line("cards", "date.add")        let notes = card.text("body")        GeometryReader { sheet in            VStack(alignment: .leading, spacing: 0) {                HStack(alignment: .top, spacing: 8) {                    if let when {                        HandDay(when: when)                            .facePart(.corner)                    }                    Spacer(minLength: 0)                    EventClock(clock: when?.clock)                        .frame(width: sheet.size.width * EventFaceKnobs.artShare)                        // The clock keeps its height on a full card: the open                        // room under it gives way first.                        .fixedSize(horizontal: false, vertical: true)                        .padding(.top, -6)                }                if notes == nil {                    Spacer(minLength: 0)                        .frame(maxHeight: EventFaceKnobs.headRoom)                }                if let title = card.text("title") {                    HeavyType(words: title, size: EventFaceKnobs.titleSize)                        .lineLimit(2)                        .padding(.top, 8)                        .accessibilityIdentifier("deck-title")                        .facePart(.title)                }                VStack(alignment: .leading, spacing: EventFaceKnobs.lineGap) {                    if let subtitle = card.text("subtitle") { typed(subtitle).facePart(.subtitle) }                    if let clock = when?.clock { typed(EventEnds.clock(clock, ends: card.text("ends"))) }                    if allDay { typed(ShellLines.line("dates", "all_day")) }                    if let day = EventEnds.day(card.text("ends")) { typed(day) }                    if let repeats = card.text("repeats") { typed(repeats) }                    if let place = card.text("place") { typed(place).facePart(.place) }                    with(width: sheet.size.width - EventFaceKnobs.inset.leading - EventFaceKnobs.inset.trailing)                        .facePart(.people)                }                .padding(.top, 10)                people                    .padding(.top, 12)                    .facePart(.people)                if let notes {                    FacePages(text: notes, size: EventFaceKnobs.bodySize, ink: .pencil)                        .padding(.top, 14)                        .facePart(.body)                } else {                    Spacer(minLength: 0)                }                if let corner = card.corner {                    RingedCorner(words: corner, pressing: card.pressing)                        .facePart(.when)                        .frame(maxWidth: .infinity, alignment: .trailing)                        .padding(.top, 8)                }            }            .padding(EventFaceKnobs.inset)        }        .onCardPaper(EventFaceCatalogue.stock.laid(card.pace))    }    private func typed(_ words: String) -> some View {        Text(words)            .font(CottonFonts.type(EventFaceKnobs.lineSize))            .lineLimit(2)            .fixedSize(horizontal: false, vertical: true)            .faceInk(.ink)    }    /// "With" in pencil and the people's names after it, joined as the core    /// joins a place's words. Names that don't fit their lines are never cut:    /// the face says fewer — first names, then "Priya, Arjun and 1 more".    @ViewBuilder private func with(width: CGFloat) -> some View {        let names = card.entries("people").compactMap { $0["name"]?.text }.filter { !$0.isEmpty }        if !names.isEmpty {            let label = ShellLines.line("cards", "event.with")            let room = width - EventFaceKnobs.withGap - EventNames.width(of: label, size: EventFaceKnobs.lineSize)            HStack(alignment: .firstTextBaseline, spacing: EventFaceKnobs.withGap) {                Text(label)                    .font(CottonFonts.type(EventFaceKnobs.lineSize))                    .faceInk(.pencil)                    .fixedSize()                typed(EventNames.telling(names, size: EventFaceKnobs.lineSize, width: room, lines: EventFaceKnobs.withLines))            }            .accessibilityElement(children: .combine)        }    }    @ViewBuilder private var people: some View {        let entries = card.entries("people")        if !entries.isEmpty {            HStack(spacing: EventFaceKnobs.personGap) {                ForEach(Array(entries.enumerated()), id: \.offset) { _, entry in                    FaceMount(name: entry["name"]?.text ?? "", picture: entry["picture"]?.text, size: EventFaceKnobs.personMount)                }                if let more = card.text("people_more") {                    Text(more)                        .font(CottonFonts.type(EventFaceKnobs.lineSize))                        .faceInk(.pencil)                }            }        }    }}/// When an event ends, as the core says it (`ends`): a clock on its own day/// ("8:00 pm") closes the start's clock ("4:30 pm – 8:00 pm", the `dates`/// span); a later day stands on its own line ("until Sun 8 Nov").public enum EventEnds {    public static func clock(_ start: String, ends: String?) -> String {        guard let ends, EventHands.time(ends) != nil else { return start }        return ShellLines.line("dates", "span", ["start": start, "end": ends])    }    public static func day(_ ends: String?) -> String? {        guard let ends, EventHands.time(ends) == nil else { return nil }        return ShellLines.line("dates", "until", ["day": ends])    }}/// The ways to say an event's people, longest first: every whole name, then/// first names, then fewer first names and how many more — the core's own/// list words (`home` `done.separator`, `done.and_more`). The face sets the/// first that its typing (Courier Prime, as `InkFit` measures it) fits in/// its lines without breaking a word.public enum EventNames {    public static func tellings(_ names: [String]) -> [String] {        let separator = ShellLines.line("home", "done.separator")        let first = names.map(CardPerson.firstName)        var tellings = [names.joined(separator: ShellLines.line("cards", "join")), first.joined(separator: separator)]        for kept in stride(from: names.count - 1, through: 1, by: -1) {            tellings.append(ShellLines.line("home", "done.and_more", [                "list": first.prefix(kept).joined(separator: separator),                "n": String(names.count - kept),            ]))        }        var seen = Set<String>()        return tellings.filter { seen.insert($0).inserted }    }    public static func telling(_ names: [String], size: CGFloat, width: CGFloat, lines: Int) -> String {        let tellings = tellings(names)        return tellings.first { InkFit.fits($0, face: .courier, size: size, width: width, lines: lines) } ?? tellings.last ?? ""    }    /// The typed width of `words` on one line.    static func width(of words: String, size: CGFloat) -> CGFloat {        guard let line = InkFit.laid(words, face: .courier, size: size, width: .greatestFiniteMagnitude)?.first else { return 0 }        return CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))    }}/// Where the clock's hands point for the event's start: the clock words the/// core said after its join ("4:30 pm", already in the event's zone, as the/// day before it) read back through the `dates` set's own `clock.am` and/// `clock.pm` lines, so the face reads no calendar and a reworded clock reads/// the same. No clock words — an all-day event, a bare day — no hands.public enum EventHands {    public static func time(_ clock: String?) -> ClockTime? {        guard let clock else { return nil }        let halves = [(ShellLines.line("dates", "clock.am"), 0), (ShellLines.line("dates", "clock.pm"), 12)]        for (line, after) in halves {            guard let reading = reading(line),                let match = reading.firstMatch(in: clock, range: NSRange(clock.startIndex..., in: clock)),                let hour = number(match, "hour", in: clock), let minute = number(match, "minute", in: clock),                (1...12).contains(hour), (0..<60).contains(minute)            else { continue }            // The house clock counts twelve, never nought: 12 am is midnight.            return ClockTime(hour: hour % 12 + after, minute: minute)        }        return nil    }    /// The hour and minute hands' angles, clockwise from twelve: the hour    /// hand walks with the minutes, so half past two sits halfway to three.    public static func angles(_ clock: String?) -> (hour: Double, minute: Double)? {        time(clock).map(CardEnamelPrint.hands)    }    /// One half of the day's clock line as a pattern: its words matched as    /// they stand, its `{hour}` and `{minute}` as the digits they hold.    private static func reading(_ line: String) -> NSRegularExpression? {        let pattern = NSRegularExpression.escapedPattern(for: line)            .replacingOccurrences(of: NSRegularExpression.escapedPattern(for: "{hour}"), with: "(?<hour>[0-9]{1,2})")            .replacingOccurrences(of: NSRegularExpression.escapedPattern(for: "{minute}"), with: "(?<minute>[0-9]{2})")        return try? NSRegularExpression(pattern: "^\(pattern)$", options: .caseInsensitive)    }    private static func number(_ match: NSTextCheckingResult, _ name: String, in words: String) -> Int? {        Range(match.range(withName: name), in: words).flatMap { Int(words[$0]) }    }}/// The alarm clock, its hands at the event's start over the picture's/// handless dial, turning on a dark boss ringed red as the painted clock's/// was; no start, the dial alone.private struct EventClock: View {    let clock: String?    @Environment(\.theme) private var theme    var body: some View {        FaceArt(name: "face-art-clock")            .overlay {                if let hands = EventHands.angles(clock) {                    GeometryReader { art in                        let width = art.size.width                        let hub = CGPoint(                            x: width * EventFaceKnobs.clockHub.x, y: art.size.height * EventFaceKnobs.clockHub.y)                        let boss = width * EventFaceKnobs.boss                        ZStack(alignment: .topLeading) {                            ClockHand(hub: hub, degrees: hands.hour,                                      reach: width * EventFaceKnobs.hourReach, width: width * EventFaceKnobs.hourWidth,                                      tail: width * EventFaceKnobs.handTail)                                .fill(theme.print(.ink))                            ClockHand(hub: hub, degrees: hands.minute,                                      reach: width * EventFaceKnobs.minuteReach, width: width * EventFaceKnobs.minuteWidth,                                      tail: width * EventFaceKnobs.handTail)                                .fill(theme.print(.ink))                            Circle()                                .fill(theme.print(.ink))                                .overlay(Circle().strokeBorder(theme.print(.red), lineWidth: width * EventFaceKnobs.bossRing))                                .frame(width: boss, height: boss)                                .position(hub)                        }                        .blendMode(theme.printBlend)                    }                    .accessibilityHidden(true)                }            }    }}/// One clock hand turned `degrees` clockwise from twelve about `hub`: a short/// tail behind the hub, a narrow shaft swelling to a spade, then the point.private struct ClockHand: Shape {    let hub: CGPoint    let degrees: Double    let reach: CGFloat    let width: CGFloat    let tail: CGFloat    func path(in rect: CGRect) -> Path {        let half = width / 2        let neck = half * EventFaceKnobs.handNeck        let swell = reach * EventFaceKnobs.handSwell        // Drawn pointing at twelve from a hub at the origin, then turned and set.        var hand = Path()        hand.move(to: CGPoint(x: 0, y: tail))        hand.addLine(to: CGPoint(x: -neck, y: 0))        hand.addLine(to: CGPoint(x: -half, y: -swell))        hand.addLine(to: CGPoint(x: 0, y: -reach))        hand.addLine(to: CGPoint(x: half, y: -swell))        hand.addLine(to: CGPoint(x: neck, y: 0))        hand.closeSubpath()        let turn = CGAffineTransform(rotationAngle: CGFloat(Angle.degrees(degrees).radians))            .concatenating(CGAffineTransform(translationX: hub.x, y: hub.y))        return hand.applying(turn)    }}/// The day written large by hand over two lines, a red pen stroke under it.private struct HandDay: View {    let when: EventWhen    @Environment(\.theme) private var theme    var body: some View {        VStack(alignment: .leading, spacing: EventFaceKnobs.handLeading) {            if !when.weekday.isEmpty {                Text(HandRun.tail(when.weekday))                    .font(CottonFonts.hand(EventFaceKnobs.weekdayHand))                    .faceInk(.ink)            }            Text(HandRun.tail(when.day))                .font(CottonFonts.hand(EventFaceKnobs.dayHand))                .lineLimit(1)                .minimumScaleFactor(0.6)                .faceInk(.ink)                .padding(.leading, 6)            PenSwash()                .stroke(theme.print(.red), style: StrokeStyle(lineWidth: 2.2, lineCap: .round))                .frame(width: EventFaceKnobs.swash.width, height: EventFaceKnobs.swash.height)                .blendMode(theme.printBlend)                .padding(.top, 14)        }        .fixedSize()        .rotationEffect(.degrees(-4), anchor: .leading)        .accessibilityElement(children: .combine)    }}/// The event face, by the kind's name, and the cards it is reviewed in. An/// event card with a picture is a studio's class (`ClassFace`), which the/// deck draws in its place (CottonUI's `DeckFace.faceID`).public enum EventFaceCatalogue {    public static let stock: FaceStock = .framed    public static let ground: FaceGround = .paper    public static let face = Face(id: "event", specimens: [Specimen("dentist", dentist), Specimen("dinner", dinner)]) { card, _, _ in        EventFace(card: card)    }    public static let dentist = DeckCard(        face: .event,        corner: "in 6 days",        fields: [            "title": .text("Dentist"),            "subtitle": .text("Dr Shah"),            "date": .text("Thu 29 Oct \u{00B7} 4:30 pm"),            "place": .text("Indiranagar"),            "people": .list([.object(["name": .text("Meera Iyer"), "picture": .text("guest-2")])]),        ]    )    public static let dinner = DeckCard(        face: .event,        corner: "Today",        fields: [            "title": .text("Dinner at Priya's new flat"),            "date": .text("Fri 23 Oct \u{00B7} 7:30 pm"),            "place": .text("12 Example Lane, Indiranagar"),            "people": .list([                .object(["name": .text("Priya Example"), "picture": .text("guest-0")]),                .object(["name": .text("Arjun Rao"), "picture": .text("guest-1")]),                .object(["name": .text("Meera Iyer")]),            ]),            "people_more": .text("+2"),            "body": .text("Bring the dessert. The lift is out until Monday, so it is the stairs to the fourth floor; park on the side road, not in front of the gate. She asked us to come by seven if we can, before the others, to help set the table on the terrace. Bring the folding chairs from the car and the speaker if the battery is charged."),        ]    )}