Sources/OrgstarWatch/WatchApp.swift
192 lines · 7320 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 if link.agenda?.locked == true {
101 ScrollView {
102 Text("The Watch app needs orgstar+. Get it in orgstar on your iPhone, in Settings.")
103 .foregroundStyle(.secondary)
104 }
105 .navigationTitle("Today")
106 } else {
107 list
108 }
109 }
110
111 private var list: some View {
112 List {
113 if let clock = link.agenda?.clock {
114 Section("Clocked In") {
115 VStack(alignment: .leading, spacing: 2) {
116 Text(clock.heading).font(.headline).lineLimit(2)
117 Text(clock.startedAt, style: .timer).font(.title3.monospacedDigit()).foregroundStyle(.green)
118 }
119 Button("Clock Out", systemImage: "stop.circle") { link.send(.clockOut) }.tint(.red)
120 }
121 } else if let last = link.agenda?.lastClocked {
122 Section("Clock") {
123 Button { link.send(.clockInLast) } label: {
124 Label { Text("Clock In to \(last)").lineLimit(2) } icon: { Image(systemName: "play.circle") }
125 }
126 }
127 }
128 Section {
129 TextField("Capture", text: $dictated)
130 .onSubmit {
131 let text = dictated.trimmingCharacters(in: .whitespacesAndNewlines)
132 dictated = ""
133 if !text.isEmpty { link.send(.capture(text: text)) }
134 }
135 if link.sentCaptures > 0 {
136 Text(link.sentCaptures == 1 ? "Sent to orgstar on iPhone." : "\(link.sentCaptures) sent to orgstar on iPhone.")
137 .font(.footnote).foregroundStyle(.secondary)
138 }
139 } footer: {
140 Text("orgstar files it with a template when you next open it on iPhone.")
141 }
142 if let agenda = link.agenda {
143 if !agenda.overdue.isEmpty {
144 Section("Overdue") { ForEach(agenda.overdue) { EntryRow(entry: $0, link: link) } }
145 }
146 Section(agenda.day.formatted(.dateTime.weekday(.wide).day().month())) {
147 if agenda.rows.isEmpty { Text("Nothing scheduled").foregroundStyle(.secondary) }
148 ForEach(agenda.rows) { EntryRow(entry: $0, link: link) }
149 }
150 } else {
151 Text("Open orgstar on your iPhone to show your agenda here.").foregroundStyle(.secondary)
152 }
153 }
154 .navigationTitle("Today")
155 }
156}
157
158struct EntryRow: View {
159 let entry: WatchAgenda.Entry
160 let link: PhoneLink
161
162 var body: some View {
163 if let done = entry.done {
164 Button { link.send(done) } label: { content(symbol: "circle") }
165 .accessibilityHint("Marks it \(entry.doneKeyword ?? "done")")
166 } else {
167 content(symbol: entry.isDone ? "checkmark.circle.fill" : entry.isEvent ? "calendar" : nil)
168 }
169 }
170
171 private func content(symbol: String?) -> some View {
172 HStack(alignment: .top, spacing: 6) {
173 if let symbol {
174 Image(systemName: symbol).foregroundStyle(entry.isDone ? .green : .secondary)
175 }
176 VStack(alignment: .leading, spacing: 1) {
177 if !entry.gutter.isEmpty {
178 Text(entry.gutter).font(.caption2).foregroundStyle(entry.status == "overdue" ? .red : .secondary)
179 }
180 Text(entry.title).strikethrough(entry.isDone).lineLimit(3)
181 if let todo = entry.todo { Text(todo).font(.caption2.weight(.semibold)).foregroundStyle(entry.isDone ? .green : .orange) }
182 }
183 }
184 }
185}
186#else
187/// The watch app builds for watchOS only; elsewhere the product does nothing.
188@main
189enum OrgstarWatchApp {
190 static func main() {}
191}
192#endif