Sources/OrgWatchData/WatchAgenda.swift
238 lines · 9504 bytes
18 symbols in this file
1import Foundation
2
3/// What the watch shows, sent by the phone over WatchConnectivity: today's agenda, the running
4/// clock and the entry Clock In Last would take. The watch keeps the last one it got.
5public struct WatchAgenda: Codable, Equatable, Sendable {
6 public struct Entry: Codable, Equatable, Sendable, Identifiable {
7 public var id: String
8 public var title: String
9 /// The agenda's gutter: the time or a short status.
10 public var gutter: String
11 public var category: String
12 public var todo: String?
13 /// `AgendaRow.Status`'s raw value: `overdue`, `due-soon`, `normal`, `done`.
14 public var status: String
15 public var isDone: Bool
16 public var isEvent: Bool
17 public var start: Date?
18 public var end: Date?
19 /// Where the entry is, and its heading line, for the phone to find it again.
20 public var path: String?
21 public var offset: Int?
22 public var headingLine: String?
23 /// The keyword marking it done takes: the first done keyword of its sequence.
24 public var doneKeyword: String?
25
26 public init(
27 id: String, title: String, gutter: String, category: String, todo: String?, status: String, isDone: Bool, isEvent: Bool,
28 start: Date?, end: Date?, path: String?, offset: Int?, headingLine: String?, doneKeyword: String?
29 ) {
30 self.id = id
31 self.title = title
32 self.gutter = gutter
33 self.category = category
34 self.todo = todo
35 self.status = status
36 self.isDone = isDone
37 self.isEvent = isEvent
38 self.start = start
39 self.end = end
40 self.path = path
41 self.offset = offset
42 self.headingLine = headingLine
43 self.doneKeyword = doneKeyword
44 }
45
46 /// An open TODO entry the phone can find.
47 public var canBeDone: Bool {
48 !isDone && !isEvent && todo != nil && doneKeyword != nil && path != nil && offset != nil && headingLine != nil
49 }
50
51 /// The action marking it done.
52 public var done: WatchAction? {
53 guard canBeDone, let path, let offset, let headingLine, let doneKeyword else { return nil }
54 return .done(path: path, offset: offset, headingLine: headingLine, keyword: doneKeyword)
55 }
56 }
57
58 public struct Clock: Codable, Equatable, Sendable {
59 public var heading: String
60 public var startedAt: Date
61
62 public init(heading: String, startedAt: Date) {
63 self.heading = heading
64 self.startedAt = startedAt
65 }
66 }
67
68 /// A flashcard position due for review: a normal or double card's two sides as text.
69 public struct Card: Codable, Equatable, Sendable, Identifiable {
70 public var path: String
71 /// The card's ID.
72 public var card: String
73 public var position: String
74 /// The front's title; nil while it is hidden.
75 public var title: String?
76 public var front: String
77 public var backTitle: String
78 public var back: String
79
80 public var id: String { path + "\n" + card + "\n" + position }
81
82 public init(path: String, card: String, position: String, title: String?, front: String, backTitle: String, back: String) {
83 self.path = path
84 self.card = card
85 self.position = position
86 self.title = title
87 self.front = front
88 self.backTitle = backTitle
89 self.back = back
90 }
91
92 /// The action rating it `rating` (`again`, `hard`, `good` or `easy`).
93 public func rate(_ rating: String) -> WatchAction { .rate(path: path, card: card, position: position, rating: rating) }
94 }
95
96 /// Flashcard positions due, in review order; nil from a phone without them.
97 public var cards: [Card]?
98
99 public var generated: Date
100 /// Midnight starting today.
101 public var day: Date
102 /// Deadlines and scheduled entries from before today.
103 public var overdue: [Entry]
104 public var rows: [Entry]
105 public var clock: Clock?
106 /// The most recently clocked entry, `org-clock-in-last`'s.
107 public var lastClocked: String?
108 /// True when the phone hasn't got orgstar+, which the Watch app needs.
109 public var locked: Bool?
110
111 /// What the phone sends without Pro: no entries.
112 public static func locked(generated: Date) -> WatchAgenda {
113 var agenda = WatchAgenda(generated: generated, day: generated, overdue: [], rows: [], clock: nil, lastClocked: nil)
114 agenda.locked = true
115 return agenda
116 }
117
118 public init(generated: Date, day: Date, overdue: [Entry], rows: [Entry], clock: Clock?, lastClocked: String?) {
119 self.generated = generated
120 self.day = day
121 self.overdue = overdue
122 self.rows = rows
123 self.clock = clock
124 self.lastClocked = lastClocked
125 }
126
127 /// What's left of today at `now`, as the Up Next widget counts it: entries that aren't
128 /// done, without timed ones that have ended (or started, with no end), then the overdue.
129 public func upcoming(at now: Date, calendar: Calendar = .current) -> [Entry] {
130 guard calendar.isDate(day, inSameDayAs: now) else { return [] }
131 let left = rows.filter { row in
132 guard !row.isDone else { return false }
133 if let end = row.end ?? row.start { return end > now }
134 return true
135 }
136 return left + overdue.filter { !$0.isDone }
137 }
138
139 /// The first of `upcoming`.
140 public func next(at now: Date, calendar: Calendar = .current) -> Entry? { upcoming(at: now, calendar: calendar).first }
141
142 /// Open TODO entries today and overdue, as the complication counts them.
143 public func openCount(at now: Date, calendar: Calendar = .current) -> Int {
144 guard calendar.isDate(day, inSameDayAs: now) else { return 0 }
145 return (rows + overdue).filter { !$0.isDone && !$0.isEvent && $0.todo != nil }.count
146 }
147
148 /// `card` rated here before the phone sends the agenda again: gone, or with Again, last.
149 public func rating(_ card: Card, again: Bool) -> WatchAgenda {
150 var copy = self
151 copy.cards?.removeAll { $0.id == card.id }
152 if again { copy.cards?.append(card) }
153 return copy
154 }
155
156 /// `entry` marked done here before the phone sends the agenda again.
157 public func markingDone(_ id: String) -> WatchAgenda {
158 var copy = self
159 func mark(_ rows: inout [Entry]) {
160 for i in rows.indices where rows[i].id == id {
161 rows[i].isDone = true
162 rows[i].todo = rows[i].doneKeyword
163 rows[i].status = "done"
164 }
165 }
166 mark(©.rows)
167 mark(©.overdue)
168 return copy
169 }
170
171 // MARK: - Transfer
172
173 static var encoder: JSONEncoder {
174 let encoder = JSONEncoder()
175 encoder.dateEncodingStrategy = .iso8601
176 encoder.outputFormatting = [.sortedKeys]
177 return encoder
178 }
179
180 static var decoder: JSONDecoder {
181 let decoder = JSONDecoder()
182 decoder.dateDecodingStrategy = .iso8601
183 return decoder
184 }
185
186 /// The application context key the agenda travels under.
187 public static let contextKey = "agenda"
188
189 public func data() throws -> Data { try Self.encoder.encode(self) }
190
191 public static func decode(_ data: Data) -> WatchAgenda? { try? decoder.decode(WatchAgenda.self, from: data) }
192
193 /// `Widgets/watch.json` in the app group's container, which the complications read; nil
194 /// without the group.
195 public static func file(group: String = "group.sh.krz.orgstar") -> URL? {
196 FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group)?
197 .appendingPathComponent("Widgets").appendingPathComponent("watch.json")
198 }
199
200 public static func read(from file: URL? = file()) -> WatchAgenda? {
201 file.flatMap { try? Data(contentsOf: $0) }.flatMap(decode)
202 }
203
204 /// Writes unless the file holds the same; true when it wrote.
205 @discardableResult
206 public func write(to file: URL? = WatchAgenda.file()) throws -> Bool {
207 guard let file, Self.read(from: file) != self else { return false }
208 try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
209 try data().write(to: file, options: .atomic)
210 return true
211 }
212}
213
214/// What the watch asks the phone to do.
215public enum WatchAction: Codable, Equatable, Sendable {
216 /// Sets the entry's keyword to `keyword`, if its heading line is still `headingLine`.
217 case done(path: String, offset: Int, headingLine: String, keyword: String)
218 case clockOut
219 /// `org-clock-in-last`.
220 case clockInLast
221 /// Dictated text for the capture inbox.
222 case capture(text: String)
223 /// Rates a flashcard position, found by its card's ID.
224 case rate(path: String, card: String, position: String, rating: String)
225
226 /// The user info key an action travels under.
227 public static let key = "action"
228
229 public var userInfo: [String: Any] {
230 guard let data = try? WatchAgenda.encoder.encode(self) else { return [:] }
231 return [Self.key: data]
232 }
233
234 public init?(userInfo: [String: Any]) {
235 guard let data = userInfo[Self.key] as? Data, let action = try? WatchAgenda.decoder.decode(WatchAction.self, from: data) else { return nil }
236 self = action
237 }
238}