// What the alarm ENGINE stands above its table's list (`EngineListHead`, // looked up by the definition's engine): the NEXT alarm, handwritten under the title, then the note saying // whether this phone will ring (`AlarmDeliveryNotice`). // // The slips cannot say which alarm is next — they are in wall-clock order, so // the first is the earliest of the day and at 9 pm is almost never the next // one. The line reads the alarms the sync pass last read // (`AlarmSyncModel.alarms`) and counts down with `nextAlarm(in:now:)`, the // engine's arithmetic. It is withheld while the phone will not ring: a // countdown to an alarm that is not coming is the wrong thing to read first. import SwiftUI struct AlarmListHead: View { /// Optional on purpose, as the notice's: without the sync model (a /// gallery, a test) the list draws and says nothing about the next alarm. @Environment(AlarmSyncModel.self) private var sync: AlarmSyncModel? var body: some View { VStack(alignment: .leading, spacing: 10) { nextLine AlarmDeliveryNotice() } .padding(.bottom, 4) } /// "next: 6:30 am, in 7 h 12 m". The clock TICKS every thirty seconds — /// the line's finest unit is a minute — and a `TimelineView` re-reads it /// when the app comes back, so a phone picked up in the morning never /// shows last night's countdown. Nothing when no alarm is on. @ViewBuilder private var nextLine: some View { if let sync, sync.gate?.silence == nil, sync.alarms.contains(where: \.enabled) { TimelineView(.periodic(from: Date(), by: 30)) { context in if let next = nextAlarm(in: sync.alarms, now: context.date) { Text(AlarmNextWords.line(hour: next.alarm.hour, minute: next.alarm.minute, at: next.at, now: context.date)) .font(CottonFonts.hand(19)) .foregroundStyle(CottonColors.inkSecondary) .accessibilityIdentifier("alarms-next") } } .padding(.top, -14) } } } /// The next line's words, pure. enum AlarmNextWords { /// "7:30 pm" — no leading zero on the hour, lowercase meridiem. Built from /// the hour and the minute, never by formatting an instant: an alarm is a /// wall clock. static func clock(hour: Int, minute: Int) -> String { let hour12 = hour % 12 == 0 ? 12 : hour % 12 return "\(hour12):\(String(format: "%02d", max(0, minute))) \(hour >= 12 ? "pm" : "am")" } /// "next: 6:30 am, in 7 h 12 m". static func line(hour: Int, minute: Int, at: Date, now: Date) -> String { "next: \(clock(hour: hour, minute: minute)), \(until(at, now: now))" } /// "in 6 h 12 m", rounded DOWN; under a minute there is no number worth /// showing. Days are not a unit: past six hours the hour count is the /// useful thing. static func until(_ at: Date, now: Date) -> String { let seconds = at.timeIntervalSince(now) if seconds < 60 { return ShellLines.line("reminders", "alarms.in_less_than_a") } let hours = Int(seconds / 3600) let minutes = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60) return hours == 0 ? "in \(minutes) m" : "in \(hours) h \(minutes) m" } }