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