Sources/OrgstarWatchWidgets/WatchWidgets.swift

139 lines · 5777 bytes

  1#if os(watchOS)
  2import OrgWatchData
  3import SwiftUI
  4import WidgetKit
  5
  6/// Complications: the next agenda entry, and the running clock.
  7@main
  8struct OrgstarWatchWidgets: WidgetBundle {
  9    var body: some Widget {
 10        NextEntryComplication()
 11        ClockComplication()
 12    }
 13}
 14
 15struct WatchEntry: TimelineEntry {
 16    let date: Date
 17    let agenda: WatchAgenda?
 18}
 19
 20/// The agenda the watch app last got, with an entry at each change of what's next.
 21struct WatchProvider: TimelineProvider {
 22    func placeholder(in context: Context) -> WatchEntry { WatchEntry(date: .now, agenda: nil) }
 23
 24    func getSnapshot(in context: Context, completion: @escaping (WatchEntry) -> Void) {
 25        completion(WatchEntry(date: .now, agenda: WatchAgenda.read()))
 26    }
 27
 28    func getTimeline(in context: Context, completion: @escaping (Timeline<WatchEntry>) -> Void) {
 29        let agenda = WatchAgenda.read()
 30        let now = Date()
 31        var dates = [now]
 32        for row in agenda?.rows ?? [] {
 33            if let end = row.end ?? row.start, end > now { dates.append(end.addingTimeInterval(60)) }
 34        }
 35        if let midnight = Calendar.current.date(byAdding: .day, value: 1, to: Calendar.current.startOfDay(for: now)) { dates.append(midnight) }
 36        let entries = Set(dates).sorted().map { WatchEntry(date: $0, agenda: agenda) }
 37        completion(Timeline(entries: entries, policy: .never))
 38    }
 39}
 40
 41struct NextEntryComplication: Widget {
 42    var body: some WidgetConfiguration {
 43        StaticConfiguration(kind: "sh.krz.orgstar.watch.next", provider: WatchProvider()) { entry in
 44            NextEntryView(entry: entry).containerBackground(for: .widget) { Color.clear }
 45        }
 46        .configurationDisplayName("Up Next")
 47        .description("The next agenda entry, or how many are open today.")
 48        .supportedFamilies([.accessoryRectangular, .accessoryInline, .accessoryCircular, .accessoryCorner])
 49    }
 50}
 51
 52struct NextEntryView: View {
 53    let entry: WatchEntry
 54    @Environment(\.widgetFamily) private var family
 55
 56    private var next: WatchAgenda.Entry? { entry.agenda?.next(at: entry.date) }
 57    private var open: Int { entry.agenda?.openCount(at: entry.date) ?? 0 }
 58
 59    var body: some View {
 60        switch family {
 61        case .accessoryInline:
 62            Text(next.map { "\($0.gutter) \($0.title)" } ?? (open == 0 ? String(localized: "Agenda clear") : String(localized: "\(open) open today")))
 63        case .accessoryCircular:
 64            ZStack {
 65                AccessoryWidgetBackground()
 66                VStack(spacing: -2) {
 67                    Text("\(open)").font(.title3.weight(.semibold)).widgetAccentable()
 68                    Text("open").font(.caption2)
 69                }
 70            }
 71            .accessibilityElement(children: .ignore)
 72            .accessibilityLabel(Text("\(open) open today"))
 73        case .accessoryCorner:
 74            Text("\(open)").font(.title3.weight(.semibold)).widgetLabel { Text(next?.title ?? String(localized: "Agenda clear")) }
 75                .accessibilityLabel(Text("\(open) open today") + Text(verbatim: next.map { ", \($0.title)" } ?? ""))
 76        default:
 77            VStack(alignment: .leading, spacing: 0) {
 78                Text(next?.gutter ?? String(localized: "Agenda")).font(.headline).widgetAccentable().lineLimit(1)
 79                Text(next?.title ?? (entry.agenda == nil ? String(localized: "Open orgstar") : String(localized: "Nothing left today"))).lineLimit(2)
 80            }
 81            .frame(maxWidth: .infinity, alignment: .leading)
 82            .accessibilityElement(children: .combine)
 83        }
 84    }
 85}
 86
 87struct ClockComplication: Widget {
 88    var body: some WidgetConfiguration {
 89        StaticConfiguration(kind: "sh.krz.orgstar.watch.clock", provider: WatchProvider()) { entry in
 90            ClockView(entry: entry).containerBackground(for: .widget) { Color.clear }
 91        }
 92        .configurationDisplayName("Clock")
 93        .description("The running clock and its time so far.")
 94        .supportedFamilies([.accessoryRectangular, .accessoryInline, .accessoryCircular])
 95    }
 96}
 97
 98struct ClockView: View {
 99    let entry: WatchEntry
100    @Environment(\.widgetFamily) private var family
101
102    var body: some View {
103        let clock = entry.agenda?.clock
104        switch family {
105        case .accessoryInline:
106            if let clock { Text("\(clock.heading) \(clock.startedAt, style: .timer)") } else { Text("Not clocked in") }
107        case .accessoryCircular:
108            ZStack {
109                AccessoryWidgetBackground()
110                if let clock {
111                    Text(clock.startedAt, style: .timer).font(.caption.monospacedDigit()).multilineTextAlignment(.center).widgetAccentable()
112                } else {
113                    Image(systemName: "stopwatch").font(.title3)
114                }
115            }
116            .accessibilityElement(children: .ignore)
117            .accessibilityLabel(clock.map { Text("Clocked in") + Text(verbatim: ", \($0.heading), ") + Text($0.startedAt, style: .timer) } ?? Text("Not clocked in"))
118        default:
119            VStack(alignment: .leading, spacing: 0) {
120                if let clock {
121                    Text(clock.startedAt, style: .timer).font(.headline.monospacedDigit()).widgetAccentable()
122                    Text(clock.heading).lineLimit(2)
123                } else {
124                    Text("Clock").font(.headline).widgetAccentable()
125                    Text("Not clocked in").foregroundStyle(.secondary)
126                }
127            }
128            .frame(maxWidth: .infinity, alignment: .leading)
129            .accessibilityElement(children: .combine)
130        }
131    }
132}
133#else
134/// The complications build for watchOS only; elsewhere the product does nothing.
135@main
136enum OrgstarWatchWidgets {
137    static func main() {}
138}
139#endif