Sources/OrgstarWatch/WatchApp.swift

220 lines · 8591 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 if link.agenda == nil {
107            ScrollView {
108                Text("Open orgstar on your iPhone to show your agenda here.")
109                    .foregroundStyle(.secondary)
110            }
111            .navigationTitle("Today")
112        } else {
113            list
114        }
115    }
116
117    private var list: some View {
118        List {
119            if let clock = link.agenda?.clock {
120                Section("Clocked In") {
121                    VStack(alignment: .leading, spacing: 2) {
122                        Text(clock.heading).font(.headline).lineLimit(2)
123                        Text(clock.startedAt, style: .timer).font(.title3.monospacedDigit()).foregroundStyle(.green)
124                    }
125                    Button("Clock Out", systemImage: "stop.circle") { link.send(.clockOut) }.tint(.red)
126                }
127            } else if let last = link.agenda?.lastClocked {
128                Section("Clock") {
129                    Button { link.send(.clockInLast) } label: {
130                        Label { Text("Clock In to \(last)").lineLimit(2) } icon: { Image(systemName: "play.circle") }
131                    }
132                }
133            }
134            Section {
135                TextField("Capture", text: $dictated)
136                    .onSubmit {
137                        let text = dictated.trimmingCharacters(in: .whitespacesAndNewlines)
138                        dictated = ""
139                        if !text.isEmpty { link.send(.capture(text: text)) }
140                    }
141                if link.sentCaptures > 0 {
142                    Text(link.sentCaptures == 1 ? "Sent to orgstar on iPhone." : "\(link.sentCaptures) sent to orgstar on iPhone.")
143                        .font(.footnote).foregroundStyle(.secondary)
144                }
145            } footer: {
146                Text("orgstar files it with a template when you next open it on iPhone.")
147            }
148            if let agenda = link.agenda {
149                if !agenda.overdue.isEmpty {
150                    Section("Overdue") { ForEach(agenda.overdue) { EntryRow(entry: $0, link: link) } }
151                }
152                Section(agenda.day.formatted(.dateTime.weekday(.wide).day().month())) {
153                    if agenda.rows.isEmpty { Text("Nothing scheduled").foregroundStyle(.secondary) }
154                    ForEach(agenda.rows) { EntryRow(entry: $0, link: link) }
155                }
156            }
157        }
158        .navigationTitle("Today")
159    }
160}
161
162struct EntryRow: View {
163    let entry: WatchAgenda.Entry
164    let link: PhoneLink
165
166    var body: some View {
167        if let done = entry.done {
168            Button { link.send(done) } label: { content(symbol: "circle") }
169                .accessibilityHint("Marks it \(entry.doneKeyword ?? "done")")
170        } else {
171            content(symbol: entry.isDone ? "checkmark.circle.fill" : entry.isEvent ? "calendar" : nil)
172        }
173    }
174
175    private func content(symbol: String?) -> some View {
176        HStack(alignment: .top, spacing: 6) {
177            if let symbol {
178                Image(systemName: symbol).foregroundStyle(entry.isDone ? .green : .secondary)
179            }
180            VStack(alignment: .leading, spacing: 1) {
181                if !entry.gutter.isEmpty {
182                    Text(entry.gutter).font(.caption2).foregroundStyle(statusColor)
183                }
184                Text(entry.title).strikethrough(entry.isDone).lineLimit(3)
185                if let todo = entry.todo { Text(todo).font(.caption2.weight(.semibold)).foregroundStyle(Self.color(keyword: todo, isDone: entry.isDone)) }
186            }
187        }
188    }
189
190    /// The agenda's status colors: `agenda-overdue`, `agenda-due-soon`, `done`.
191    private var statusColor: Color {
192        switch entry.status {
193        case "overdue": .red
194        case "due-soon": .orange
195        case "done": .green
196        default: .secondary
197        }
198    }
199
200    /// The keyword's class color, as the default theme draws it: `todo`, `todo-next`,
201    /// `todo-waiting`, `done`, `todo-cancelled`. The words are `ThemeSpec.TodoClass`'s.
202    static func color(keyword: String, isDone: Bool) -> Color {
203        let word = keyword.uppercased()
204        if isDone { return cancelledWords.contains(word) ? .gray : .green }
205        if nextWords.contains(word) { return .blue }
206        if waitingWords.contains(word) { return .yellow }
207        return .red
208    }
209
210    static let nextWords: Set<String> = ["NEXT", "STRT", "STARTED", "START", "DOING", "ACTIVE", "INPROGRESS", "IN-PROGRESS"]
211    static let waitingWords: Set<String> = ["WAIT", "WAITING", "HOLD", "ONHOLD", "BLOCKED", "DEFERRED", "SOMEDAY", "MAYBE"]
212    static let cancelledWords: Set<String> = ["KILL", "KILLED", "CANCELLED", "CANCELED", "CANCEL", "SKIPPED", "SKIP", "ABORTED", "NO", "WONTFIX"]
213}
214#else
215/// The watch app builds for watchOS only; elsewhere the product does nothing.
216@main
217enum OrgstarWatchApp {
218    static func main() {}
219}
220#endif