Sources/OrgstarMobile/ClockScreens.swift
308 lines · 12868 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import SwiftUI
5
6/// Clock commands that ask questions, and their answers in `ClockPromptSheet`.
7@MainActor
8@Observable
9final class ClockPrompter {
10 struct Pending: Identifiable {
11 let id = UUID()
12 let prompt: Prompt
13 let reply: (String?) -> Void
14 }
15
16 var pending: Pending?
17
18 var ask: ClockModel.Ask {
19 { [self] prompt in
20 await withCheckedContinuation { continuation in
21 pending = Pending(prompt: prompt) { continuation.resume(returning: $0) }
22 }
23 }
24 }
25
26 func answer(_ text: String?) {
27 guard let request = pending else { return }
28 pending = nil
29 request.reply(text)
30 }
31}
32
33/// The clock commands both the editor and the clock accessory run.
34@MainActor
35enum MobileClock {
36 /// The clock commands that need no caret, for the Commands list of a screen without one.
37 static let screenCommands: [(id: String, title: String)] = CommandPalette.viewCommands.filter {
38 $0.id.hasPrefix("app.clock.") && !["app.clock.in", "app.clock.default"].contains($0.id)
39 }
40
41 /// Runs a clock command; false for other ids. Messages go to `show`; entries to show open.
42 static func run(_ id: String, model: MobileModel, workspace: WorkspaceModel, show: @escaping (String) -> Void) -> Bool {
43 let clock = model.clock
44 let session = model.session
45 let ask = model.clockPrompts.ask
46 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
47 func open(_ location: (path: String, offset: Int)?) {
48 if let location { model.openRequest = .offset(location.path, location.offset) }
49 }
50 func report(_ outcome: ClockModel.Outcome) {
51 open(outcome.jump)
52 if let message = outcome.messages.last(where: { !$0.isEmpty }) { show(message) }
53 }
54 func clockIn(_ target: ClockModel.Target) {
55 Task { report(await clock.clockIn(session, target: target, paths: paths, ask: ask)) }
56 }
57 switch id {
58 case "app.clock.in": clockIn(.caret)
59 case "app.clock.in-recent": clockIn(.select)
60 case "app.clock.in-last": clockIn(.last)
61 case let id where id.hasPrefix("app.clock.history."):
62 guard let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count else { return true }
63 clockIn(.task(clock.history[index]))
64 case "app.clock.out": show(clock.clockOut(session))
65 case "app.clock.cancel": show(clock.clockOut(session, cancel: true))
66 case "app.clock.goto":
67 let found = clock.goto(session)
68 open(found.location)
69 if let message = found.message { show(message) }
70 case "app.clock.goto-recent":
71 Task {
72 let found = await clock.gotoRecent(session, ask: ask)
73 open(found.location)
74 if let message = found.message { show(message) }
75 }
76 case "app.clock.default": show(clock.markDefault(session))
77 case "app.clock.resolve":
78 Task { report(await clock.resolveOpenClocks(session, paths: paths, ask: ask)) }
79 default:
80 return false
81 }
82 return true
83 }
84
85 /// `org-resolve-clocks-if-idle` for the running clock, idle since `since`.
86 static func resolveIdle(since: Date, model: MobileModel, show: @escaping (String) -> Void) {
87 Task {
88 let outcome = await model.clock.resolveIdle(model.session, idleSince: since, ask: model.clockPrompts.ask)
89 if let jump = outcome.jump { model.openRequest = .offset(jump.path, jump.offset) }
90 if let message = outcome.messages.last(where: { !$0.isEmpty }) { show(message) }
91 }
92 }
93}
94
95/// Recent entries to clock in to, and the commands that choose among them.
96struct RecentClockMenu: View {
97 let clock: ClockModel
98 let perform: (String) -> Void
99
100 var body: some View {
101 Menu("Recent Entries", systemImage: "clock.arrow.circlepath") {
102 ForEach(Array(clock.history.enumerated()), id: \.offset) { index, task in
103 Button(task.title) { perform("app.clock.history.\(index)") }
104 }
105 Divider()
106 Button("Clock In to Recent Entry…") { perform("app.clock.in-recent") }
107 Button("Go to Recent Clocked Entry…") { perform("app.clock.goto-recent") }
108 }
109 .disabled(clock.history.isEmpty)
110 }
111}
112
113/// A clock question: keys to choose from under their sections, or a number or date to type.
114struct ClockPromptSheet: View {
115 let prompt: Prompt
116 let answer: (String?) -> Void
117 @State private var text = ""
118
119 var body: some View {
120 NavigationStack {
121 Form {
122 if let fast = prompt.fast {
123 ForEach(Array(sections(fast).enumerated()), id: \.offset) { _, section in
124 Section(section.title) {
125 ForEach(Array(section.options.enumerated()), id: \.offset) { _, option in
126 Button {
127 answer(String(option.key))
128 } label: {
129 HStack(alignment: .firstTextBaseline) {
130 Text(String(option.key)).font(.body.monospaced()).foregroundStyle(.tint)
131 Text(option.name).foregroundStyle(.primary)
132 }
133 }
134 }
135 }
136 }
137 } else {
138 Section {
139 TextField(prompt.message, text: $text)
140 .autocorrectionDisabled()
141 .textInputAutocapitalization(.never)
142 .keyboardType(prompt.date == nil ? .numbersAndPunctuation : .default)
143 .onSubmit { answer(text) }
144 } footer: {
145 Text(prompt.date == nil ? "Empty takes the default." : "Org's date syntax: 14:00, -1h, today 9:30")
146 }
147 }
148 }
149 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ":?[] ")))
150 .navigationBarTitleDisplayMode(.inline)
151 .toolbar {
152 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
153 if prompt.fast == nil {
154 ToolbarItem(placement: .confirmationAction) { Button("Done") { answer(text) } }
155 }
156 }
157 }
158 .onAppear { text = prompt.initial }
159 .interactiveDismissDisabled()
160 }
161
162 private struct Group {
163 var title: String
164 var options: [(key: Character, name: String)]
165 }
166
167 /// Options under the labels before them.
168 private func sections(_ fast: FastSelection) -> [Group] {
169 var groups: [Group] = []
170 for item in fast.items {
171 switch item {
172 case .label(let title): groups.append(Group(title: title, options: []))
173 case .option(let key, let name):
174 if groups.isEmpty { groups.append(Group(title: "", options: [])) }
175 groups[groups.count - 1].options.append((key, name))
176 default: break
177 }
178 }
179 return groups
180 }
181}
182
183/// The running clock over the tab bar: the entry and time so far, and clocking out.
184struct ClockAccessory: View {
185 let running: ClockModel.Running
186 let clock: ClockModel
187 let perform: (String) -> Void
188
189 var body: some View {
190 Menu {
191 Button("Clock Out", systemImage: "stop.circle") { perform("app.clock.out") }
192 Button("Cancel Clock", systemImage: "xmark.circle") { perform("app.clock.cancel") }
193 Button("Go to Clocked Entry", systemImage: "arrow.right.circle") { perform("app.clock.goto") }
194 RecentClockMenu(clock: clock, perform: perform)
195 Button("Clock Report", systemImage: "list.bullet.rectangle") { perform("app.clock.report") }
196 } label: {
197 HStack {
198 Image(systemName: "stopwatch")
199 Text(running.heading).lineLimit(1)
200 Spacer()
201 TimelineView(.periodic(from: .now, by: 30)) { context in
202 Text(Self.elapsed(running, now: context.date)).monospacedDigit()
203 }
204 }
205 .padding(.horizontal)
206 }
207 .accessibilityLabel("Clocked in on \(running.heading)")
208 }
209
210 /// Elapsed time of the running clock, `H:MM`.
211 static func elapsed(_ running: ClockModel.Running, now: Date) -> String {
212 let minutes = max(0, Int(now.timeIntervalSince(running.startedAt) / 60))
213 return String(format: "%d:%02d", minutes / 60, minutes % 60)
214 }
215}
216
217extension View {
218 /// The running clock over the tab bar, while there is one.
219 @ViewBuilder
220 func clockAccessory(_ clock: ClockModel, perform: @escaping (String) -> Void) -> some View {
221 if #available(iOS 26.1, *) {
222 tabViewBottomAccessory(isEnabled: clock.running != nil) {
223 if let running = clock.running { ClockAccessory(running: running, clock: clock, perform: perform) }
224 }
225 } else {
226 safeAreaInset(edge: .bottom) {
227 if let running = clock.running { ClockAccessory(running: running, clock: clock, perform: perform).padding(.vertical, 8).background(.bar) }
228 }
229 }
230 }
231}
232
233/// Time per day and heading, as `tr/generate-report` writes it, for chosen files and dates.
234struct ClockReportScreen: View {
235 let workspace: WorkspaceModel
236 @State private var start = Calendar.current.date(byAdding: .day, value: -6, to: Date()) ?? Date()
237 @State private var end = Date()
238 @State private var limit = false
239 @State private var selected: Set<String> = []
240 @State private var report = ""
241 @Environment(\.dismiss) private var dismiss
242
243 private var candidates: [FileEntry] { workspace.files.filter { $0.kind == .org } }
244
245 var body: some View {
246 NavigationStack {
247 Form {
248 Section("Files") {
249 ForEach(candidates) { file in
250 Toggle(file.relativePath, isOn: Binding {
251 selected.contains(file.path)
252 } set: { on in
253 if on { selected.insert(file.path) } else { selected.remove(file.path) }
254 })
255 }
256 }
257 Section {
258 Toggle("Limit dates", isOn: $limit)
259 if limit {
260 DatePicker("From", selection: $start, displayedComponents: .date)
261 DatePicker("To", selection: $end, displayedComponents: .date)
262 }
263 }
264 Section("Report") {
265 ScrollView(.horizontal) {
266 Text(report.isEmpty ? "Choose files with clocked time." : report)
267 .font(.footnote.monospaced())
268 .textSelection(.enabled)
269 .fixedSize()
270 }
271 }
272 }
273 .navigationTitle("Clock Report")
274 .navigationBarTitleDisplayMode(.inline)
275 .toolbar {
276 ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } }
277 ToolbarItem(placement: .primaryAction) {
278 ShareLink(item: report, preview: SharePreview("Clock Report")).disabled(report.isEmpty)
279 }
280 }
281 }
282 .onAppear {
283 if selected.isEmpty {
284 selected = Set(candidates.filter { (try? String(contentsOfFile: $0.path, encoding: .utf8))?.contains("CLOCK: [") ?? false }.map(\.path))
285 }
286 compute()
287 }
288 .onChange(of: selected) { compute() }
289 .onChange(of: start) { compute() }
290 .onChange(of: end) { compute() }
291 .onChange(of: limit) { compute() }
292 }
293
294 private func day(_ date: Date) -> String {
295 let c = Calendar.current.dateComponents([.year, .month, .day], from: date)
296 return String(format: "%04d-%02d-%02d", c.year!, c.month!, c.day!)
297 }
298
299 private func compute() {
300 var entries: [ClockReport.Entry] = []
301 for path in selected.sorted() {
302 guard let text = try? String(contentsOfFile: path, encoding: .utf8) else { continue }
303 entries += ClockReport.entries(text, settings: workspace.settings.org)
304 }
305 report = selected.isEmpty ? "" : ClockReport.timeReport(entries, start: limit ? day(start) : nil, end: limit ? day(end) : nil)
306 }
307}
308#endif