Sources/OrgstarWatch/WatchApp.swift
278 lines · 11068 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 case .rate(_, _, _, let rating):
57 if let agenda, let card = agenda.cards?.first(where: { $0.rate(rating) == action }) {
58 store(agenda.rating(card, again: rating == "again"))
59 }
60 }
61 let session = WCSession.default
62 guard session.activationState == .activated else { return }
63 let info = action.userInfo
64 if session.isReachable {
65 session.sendMessage(info, replyHandler: nil) { _ in session.transferUserInfo(info) }
66 } else {
67 session.transferUserInfo(info)
68 }
69 }
70
71 private func store(_ new: WatchAgenda) {
72 agenda = new
73 if (try? new.write()) == true { WidgetCenter.shared.reloadAllTimelines() }
74 }
75
76 private func received(_ new: WatchAgenda?) {
77 guard let new else { return }
78 store(new)
79 sentCaptures = 0
80 }
81
82 nonisolated private static func agenda(in context: [String: Any]) -> WatchAgenda? {
83 (context[WatchAgenda.contextKey] as? Data).flatMap(WatchAgenda.decode)
84 }
85
86 nonisolated func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
87 let new = Self.agenda(in: session.receivedApplicationContext)
88 Task { @MainActor in self.received(new) }
89 }
90
91 nonisolated func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
92 let new = Self.agenda(in: applicationContext)
93 Task { @MainActor in self.received(new) }
94 }
95}
96
97/// Today: the running clock, capture, and the entries, each of which a tap marks done.
98struct AgendaList: View {
99 let link: PhoneLink
100 @State private var capturing = false
101 @State private var dictated = ""
102
103 var body: some View {
104 if link.agenda?.locked == true {
105 ScrollView {
106 Text("The Watch app needs orgstar+. Get it in orgstar on your iPhone, in Settings.")
107 .foregroundStyle(.secondary)
108 }
109 .navigationTitle("Today")
110 } else if link.agenda == nil {
111 ScrollView {
112 Text("Open orgstar on your iPhone to show your agenda here.")
113 .foregroundStyle(.secondary)
114 }
115 .navigationTitle("Today")
116 } else {
117 list
118 }
119 }
120
121 private var list: some View {
122 List {
123 if let clock = link.agenda?.clock {
124 Section("Clocked In") {
125 VStack(alignment: .leading, spacing: 2) {
126 Text(clock.heading).font(.headline).lineLimit(2)
127 Text(clock.startedAt, style: .timer).font(.title3.monospacedDigit()).foregroundStyle(.green)
128 }
129 Button("Clock Out", systemImage: "stop.circle") { link.send(.clockOut) }.tint(.red)
130 }
131 } else if let last = link.agenda?.lastClocked {
132 Section("Clock") {
133 Button { link.send(.clockInLast) } label: {
134 Label { Text("Clock In to \(last)").lineLimit(2) } icon: { Image(systemName: "play.circle") }
135 }
136 }
137 }
138 Section {
139 TextField("Capture", text: $dictated)
140 .onSubmit {
141 let text = dictated.trimmingCharacters(in: .whitespacesAndNewlines)
142 dictated = ""
143 if !text.isEmpty { link.send(.capture(text: text)) }
144 }
145 if link.sentCaptures > 0 {
146 Text("\(link.sentCaptures) sent to orgstar on iPhone.")
147 .font(.footnote).foregroundStyle(.secondary)
148 }
149 } footer: {
150 Text("orgstar files it with a template when you next open it on iPhone.")
151 }
152 if let cards = link.agenda?.cards, !cards.isEmpty {
153 Section("Flashcards") {
154 NavigationLink { CardReview(link: link) } label: {
155 Label("Review \(cards.count) cards", systemImage: "rectangle.on.rectangle.angled")
156 }
157 }
158 }
159 if let agenda = link.agenda {
160 if !agenda.overdue.isEmpty {
161 Section("Overdue") { ForEach(agenda.overdue) { EntryRow(entry: $0, link: link) } }
162 }
163 Section(agenda.day.formatted(.dateTime.weekday(.wide).day().month())) {
164 if agenda.rows.isEmpty { Text("Nothing scheduled").foregroundStyle(.secondary) }
165 ForEach(agenda.rows) { EntryRow(entry: $0, link: link) }
166 }
167 }
168 }
169 .navigationTitle("Today")
170 }
171}
172
173/// Normal and double flashcards due, from the phone: the front, Show Answer, the back and
174/// org-fc's four ratings. The phone writes each rating to the card's file.
175struct CardReview: View {
176 let link: PhoneLink
177 @State private var flipped = false
178
179 var body: some View {
180 if let card = link.agenda?.cards?.first {
181 ScrollView {
182 VStack(alignment: .leading, spacing: 6) {
183 Text(flipped ? card.backTitle : card.title ?? "[…]").font(.headline)
184 .foregroundStyle(flipped || card.title != nil ? .primary : .secondary)
185 let text = flipped ? card.back : card.front
186 if !text.isEmpty { Text(text).font(.body) }
187 if flipped {
188 Grid(horizontalSpacing: 6, verticalSpacing: 6) {
189 GridRow {
190 rate(card, "again", "Again", .red)
191 rate(card, "hard", "Hard", .orange)
192 }
193 GridRow {
194 rate(card, "good", "Good", .green)
195 rate(card, "easy", "Easy", .blue)
196 }
197 }
198 .padding(.top, 4)
199 } else {
200 Button("Show Answer") { flipped = true }.padding(.top, 4)
201 }
202 }
203 }
204 .navigationTitle("\(link.agenda?.cards?.count ?? 0) left")
205 } else {
206 Text("Nothing else is due.").foregroundStyle(.secondary).navigationTitle("Flashcards")
207 }
208 }
209
210 private func rate(_ card: WatchAgenda.Card, _ rating: String, _ title: LocalizedStringKey, _ tint: Color) -> some View {
211 Button(title) {
212 flipped = false
213 link.send(card.rate(rating))
214 }
215 .tint(tint)
216 .buttonStyle(.borderedProminent)
217 }
218}
219
220struct EntryRow: View {
221 let entry: WatchAgenda.Entry
222 let link: PhoneLink
223
224 var body: some View {
225 if let done = entry.done {
226 Button { link.send(done) } label: { content(symbol: "circle") }
227 .accessibilityHint("Marks it \(entry.doneKeyword ?? "done")")
228 } else {
229 content(symbol: entry.isDone ? "checkmark.circle.fill" : entry.isEvent ? "calendar" : nil)
230 }
231 }
232
233 private func content(symbol: String?) -> some View {
234 HStack(alignment: .top, spacing: 6) {
235 if let symbol {
236 Image(systemName: symbol).foregroundStyle(entry.isDone ? .green : .secondary)
237 }
238 VStack(alignment: .leading, spacing: 1) {
239 if !entry.gutter.isEmpty {
240 Text(entry.gutter).font(.caption2).foregroundStyle(statusColor)
241 }
242 Text(entry.title).strikethrough(entry.isDone).lineLimit(3)
243 if let todo = entry.todo { Text(todo).font(.caption2.weight(.semibold)).foregroundStyle(Self.color(keyword: todo, isDone: entry.isDone)) }
244 }
245 }
246 }
247
248 /// The agenda's status colors: `agenda-overdue`, `agenda-due-soon`, `done`.
249 private var statusColor: Color {
250 switch entry.status {
251 case "overdue": .red
252 case "due-soon": .orange
253 case "done": .green
254 default: .secondary
255 }
256 }
257
258 /// The keyword's class color, as the default theme draws it: `todo`, `todo-next`,
259 /// `todo-waiting`, `done`, `todo-cancelled`. The words are `ThemeSpec.TodoClass`'s.
260 static func color(keyword: String, isDone: Bool) -> Color {
261 let word = keyword.uppercased()
262 if isDone { return cancelledWords.contains(word) ? .gray : .green }
263 if nextWords.contains(word) { return .blue }
264 if waitingWords.contains(word) { return .yellow }
265 return .red
266 }
267
268 static let nextWords: Set<String> = ["NEXT", "STRT", "STARTED", "START", "DOING", "ACTIVE", "INPROGRESS", "IN-PROGRESS"]
269 static let waitingWords: Set<String> = ["WAIT", "WAITING", "HOLD", "ONHOLD", "BLOCKED", "DEFERRED", "SOMEDAY", "MAYBE"]
270 static let cancelledWords: Set<String> = ["KILL", "KILLED", "CANCELLED", "CANCELED", "CANCEL", "SKIPPED", "SKIP", "ABORTED", "NO", "WONTFIX"]
271}
272#else
273/// The watch app builds for watchOS only; elsewhere the product does nothing.
274@main
275enum OrgstarWatchApp {
276 static func main() {}
277}
278#endif