Sources/OrgstarWatch/WatchApp.swift
180 lines · 6967 bytes
1#if os(watchOS)
2import OrgWatchData
3import SwiftUI
4import WatchConnectivity
5import WidgetKit
6
7/// orgstar on the watch: today's agenda from the phone, marking entries done, the running
8/// clock, and dictated capture into the phone's capture inbox.
9@main
10struct OrgstarWatchApp: App {
11 @State private var link = PhoneLink.shared
12
13 var body: some Scene {
14 WindowGroup {
15 NavigationStack { AgendaList(link: link) }
16 .onAppear { link.activate() }
17 }
18 }
19}
20
21/// The phone, over WatchConnectivity: the agenda it last sent, and the actions sent to it.
22/// Actions go as a message when the phone is reachable, which wakes the app there, else with
23/// `transferUserInfo`, which waits for it.
24@MainActor
25@Observable
26final class PhoneLink: NSObject, WCSessionDelegate {
27 static let shared = PhoneLink()
28
29 private(set) var agenda: WatchAgenda? = WatchAgenda.read()
30 /// Captures sent and not yet acknowledged by the next agenda.
31 private(set) var sentCaptures = 0
32
33 func activate() {
34 guard WCSession.isSupported(), WCSession.default.delegate == nil else { return }
35 WCSession.default.delegate = self
36 WCSession.default.activate()
37 }
38
39 func send(_ action: WatchAction) {
40 switch action {
41 case .done:
42 if case .done(_, let offset, _, _) = action, let agenda,
43 let entry = (agenda.rows + agenda.overdue).first(where: { $0.offset == offset && $0.done == action }) {
44 store(agenda.markingDone(entry.id))
45 }
46 case .clockOut:
47 if var agenda {
48 agenda.lastClocked = agenda.clock?.heading ?? agenda.lastClocked
49 agenda.clock = nil
50 store(agenda)
51 }
52 case .capture:
53 sentCaptures += 1
54 case .clockInLast:
55 break
56 }
57 let session = WCSession.default
58 guard session.activationState == .activated else { return }
59 let info = action.userInfo
60 if session.isReachable {
61 session.sendMessage(info, replyHandler: nil) { _ in session.transferUserInfo(info) }
62 } else {
63 session.transferUserInfo(info)
64 }
65 }
66
67 private func store(_ new: WatchAgenda) {
68 agenda = new
69 if (try? new.write()) == true { WidgetCenter.shared.reloadAllTimelines() }
70 }
71
72 private func received(_ new: WatchAgenda?) {
73 guard let new else { return }
74 store(new)
75 sentCaptures = 0
76 }
77
78 nonisolated private static func agenda(in context: [String: Any]) -> WatchAgenda? {
79 (context[WatchAgenda.contextKey] as? Data).flatMap(WatchAgenda.decode)
80 }
81
82 nonisolated func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
83 let new = Self.agenda(in: session.receivedApplicationContext)
84 Task { @MainActor in self.received(new) }
85 }
86
87 nonisolated func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
88 let new = Self.agenda(in: applicationContext)
89 Task { @MainActor in self.received(new) }
90 }
91}
92
93/// Today: the running clock, capture, and the entries, each of which a tap marks done.
94struct AgendaList: View {
95 let link: PhoneLink
96 @State private var capturing = false
97 @State private var dictated = ""
98
99 var body: some View {
100 List {
101 if let clock = link.agenda?.clock {
102 Section("Clocked In") {
103 VStack(alignment: .leading, spacing: 2) {
104 Text(clock.heading).font(.headline).lineLimit(2)
105 Text(clock.startedAt, style: .timer).font(.title3.monospacedDigit()).foregroundStyle(.green)
106 }
107 Button("Clock Out", systemImage: "stop.circle") { link.send(.clockOut) }.tint(.red)
108 }
109 } else if let last = link.agenda?.lastClocked {
110 Section("Clock") {
111 Button { link.send(.clockInLast) } label: {
112 Label { Text("Clock In to \(last)").lineLimit(2) } icon: { Image(systemName: "play.circle") }
113 }
114 }
115 }
116 Section {
117 TextField("Capture", text: $dictated)
118 .onSubmit {
119 let text = dictated.trimmingCharacters(in: .whitespacesAndNewlines)
120 dictated = ""
121 if !text.isEmpty { link.send(.capture(text: text)) }
122 }
123 if link.sentCaptures > 0 {
124 Text(link.sentCaptures == 1 ? "Sent to orgstar on iPhone." : "\(link.sentCaptures) sent to orgstar on iPhone.")
125 .font(.footnote).foregroundStyle(.secondary)
126 }
127 } footer: {
128 Text("orgstar files it with a template when you next open it on iPhone.")
129 }
130 if let agenda = link.agenda {
131 if !agenda.overdue.isEmpty {
132 Section("Overdue") { ForEach(agenda.overdue) { EntryRow(entry: $0, link: link) } }
133 }
134 Section(agenda.day.formatted(.dateTime.weekday(.wide).day().month())) {
135 if agenda.rows.isEmpty { Text("Nothing scheduled").foregroundStyle(.secondary) }
136 ForEach(agenda.rows) { EntryRow(entry: $0, link: link) }
137 }
138 } else {
139 Text("Open orgstar on your iPhone to show your agenda here.").foregroundStyle(.secondary)
140 }
141 }
142 .navigationTitle("Today")
143 }
144}
145
146struct EntryRow: View {
147 let entry: WatchAgenda.Entry
148 let link: PhoneLink
149
150 var body: some View {
151 if let done = entry.done {
152 Button { link.send(done) } label: { content(symbol: "circle") }
153 .accessibilityHint("Marks it \(entry.doneKeyword ?? "done")")
154 } else {
155 content(symbol: entry.isDone ? "checkmark.circle.fill" : entry.isEvent ? "calendar" : nil)
156 }
157 }
158
159 private func content(symbol: String?) -> some View {
160 HStack(alignment: .top, spacing: 6) {
161 if let symbol {
162 Image(systemName: symbol).foregroundStyle(entry.isDone ? .green : .secondary)
163 }
164 VStack(alignment: .leading, spacing: 1) {
165 if !entry.gutter.isEmpty {
166 Text(entry.gutter).font(.caption2).foregroundStyle(entry.status == "overdue" ? .red : .secondary)
167 }
168 Text(entry.title).strikethrough(entry.isDone).lineLimit(3)
169 if let todo = entry.todo { Text(todo).font(.caption2.weight(.semibold)).foregroundStyle(entry.isDone ? .green : .orange) }
170 }
171 }
172 }
173}
174#else
175/// The watch app builds for watchOS only; elsewhere the product does nothing.
176@main
177enum OrgstarWatchApp {
178 static func main() {}
179}
180#endif