// 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.importCottonPaperimportCoreTextimportCottonValuesimportSwiftUIenumEventFaceKnobs {staticlet inset = EdgeInsets(top: 30, leading: 30, bottom: 26, trailing: 24)staticlet weekdayHand: CGFloat = 46staticlet dayHand: CGFloat = 52staticlet handLeading: CGFloat = -18/// The alarm clock's width as a share of the card's.staticlet 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.staticlet 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.staticlet hourReach: CGFloat = 0.19staticlet minuteReach: CGFloat = 0.245staticlet hourWidth: CGFloat = 0.036staticlet minuteWidth: CGFloat = 0.03/// How far a hand's tail reaches back past the hub, as a share of the/// picture's width.staticlet 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.staticlet handSwell: CGFloat = 0.74staticlet handNeck: CGFloat = 0.4/// The boss the hands turn on and its red ring, as shares of the/// picture's width.staticlet boss: CGFloat = 0.052staticlet 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.staticlet headRoom: CGFloat = 56staticlet titleSize: CGFloat = 34staticlet lineSize: CGFloat = 19staticlet lineGap: CGFloat = 8staticlet bodySize: CGFloat = 13staticlet personMount: CGFloat = 42staticlet personGap: CGFloat = 10/// The room between "With" and the names: a typed space.staticlet withGap: CGFloat = 10/// The lines the names after "With" take; names that need more are told/// shorter (`EventNames`).staticlet withLines = 2staticlet 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`).publicstructEventWhen: Equatable {publicvar weekday: Stringpublicvar day: Stringpublicvar clock: String?/// The core's join between a date's day and its clock.staticlet join = " \u{00B7} "publicinit(_ 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 }}extensionEventWhen {/// A date place's words parted where the core joined them: the day,/// and the clock after the join when it has one.staticfunc 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) }}publicstructEventFace: View {let card: DeckCardpublicinit(card: DeckCard) {self.card = card }publicvar body: someView {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) {iflet 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) }iflet 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) {iflet subtitle = card.text("subtitle") { typed(subtitle).facePart(.subtitle) }iflet clock = when?.clock { typed(EventEnds.clock(clock, ends: card.text("ends"))) }if allDay { typed(ShellLines.line("dates", "all_day")) }iflet day = EventEnds.day(card.text("ends")) { typed(day) }iflet repeats = card.text("repeats") { typed(repeats) }iflet 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)iflet notes {FacePages(text: notes, size: EventFaceKnobs.bodySize, ink: .pencil) .padding(.top, 14) .facePart(.body) } else {Spacer(minLength: 0) }iflet 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)) }privatefunc typed(_ words: String) -> someView {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 privatefunc with(width: CGFloat) -> someView {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 privatevar people: someView {let entries = card.entries("people")if !entries.isEmpty { HStack(spacing: EventFaceKnobs.personGap) {ForEach(Array(entries.enumerated()), id: \.offset) { _, entry inFaceMount(name: entry["name"]?.text ?? "", picture: entry["picture"]?.text, size: EventFaceKnobs.personMount) }iflet 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").publicenumEventEnds {publicstaticfunc clock(_ start: String, ends: String?) -> String {guardlet ends, EventHands.time(ends) != nilelse { return start }returnShellLines.line("dates", "span", ["start": start, "end": ends]) }publicstaticfunc day(_ ends: String?) -> String? {guardlet ends, EventHands.time(ends) == nilelse { returnnil }returnShellLines.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.publicenumEventNames {publicstaticfunc 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 } }publicstaticfunc 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.staticfunc width(of words: String, size: CGFloat) -> CGFloat {guardlet line = InkFit.laid(words, face: .courier, size: size, width: .greatestFiniteMagnitude)?.first else { return0 }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.publicenumEventHands {publicstaticfunc time(_ clock: String?) -> ClockTime? {guardlet clock else { returnnil }let halves = [(ShellLines.line("dates", "clock.am"), 0), (ShellLines.line("dates", "clock.pm"), 12)]for (line, after) in halves {guardlet 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.returnClockTime(hour: hour % 12 + after, minute: minute) }returnnil }/// The hour and minute hands' angles, clockwise from twelve: the hour/// hand walks with the minutes, so half past two sits halfway to three.publicstaticfunc 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.privatestaticfunc 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})")returntry? NSRegularExpression(pattern: "^\(pattern)$", options: .caseInsensitive) }privatestaticfunc 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.privatestructEventClock: View {let clock: String? @Environment(\.theme) privatevar themevar body: someView {FaceArt(name: "face-art-clock") .overlay {iflet hands = EventHands.angles(clock) {GeometryReader { art inlet width = art.size.widthlet 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.privatestructClockHand: Shape {let hub: CGPointlet degrees: Doublelet reach: CGFloatlet width: CGFloatlet tail: CGFloatfunc path(in rect: CGRect) -> Path {let half = width / 2let neck = half * EventFaceKnobs.handNecklet 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.privatestructHandDay: View {let when: EventWhen @Environment(\.theme) privatevar themevar body: someView { 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`).publicenumEventFaceCatalogue {publicstaticlet stock: FaceStock = .framedpublicstaticlet ground: FaceGround = .paperpublicstaticlet face = Face(id: "event", specimens: [Specimen("dentist", dentist), Specimen("dinner", dinner)]) { card, _, _ inEventFace(card: card) }publicstaticlet 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")])]), ] )publicstaticlet 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."), ] )}