Sources/OrgstarMobile/CaptureScreen.swift
436 lines · 19714 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import SwiftUI
6
7/// Capture with a template: its questions (`%^{…}`, `%^g`, `%^t`…), then its text to edit,
8/// filed where the template says, as `org-capture` does. Refile files it and then moves it
9/// (`org-capture-refile`).
10struct CaptureScreen: View {
11 let workspace: WorkspaceModel
12 let session: DocumentSession
13 let request: CaptureRequest
14 @Environment(\.dismiss) private var dismiss
15 @Environment(ClockModel.self) private var clock
16 @Environment(MobileModel.self) private var model
17 @State private var templates: [CaptureTemplate] = []
18 @State private var groups: [CaptureGroup] = []
19 /// The day `:time-prompt` asked for.
20 @State private var treeDate: Date?
21 /// The filed entry, while its refile target is picked.
22 @State private var refiling: RefileEntry?
23 @State private var key: String?
24 @State private var context = CaptureContext()
25 @State private var questions: [Capture.Question] = []
26 @State private var answers: [String] = []
27 @State private var editing = false
28 @State private var text = ""
29 @State private var selection: TextSelection?
30 @State private var problem: String?
31 /// The entry's date or tags sheet: on the form, not its section, which may not be in the window.
32 @State private var planning: EntryPlanning?
33 @State private var choosingTags = false
34 @FocusState private var focused: Bool
35
36 private var template: CaptureTemplate? { templates.first { $0.key == key } }
37
38 var body: some View {
39 NavigationStack {
40 Form {
41 Picker("Template", selection: $key) {
42 ForEach(templates) { Text(CaptureTemplates.label($0, groups: groups)).tag(Optional($0.key)) }
43 }
44 if editing {
45 Section {
46 TextEditor(text: $text, selection: $selection)
47 .font(.body.monospaced())
48 .frame(minHeight: 120)
49 .focused($focused)
50 } footer: {
51 if let problem { Text(problem).foregroundStyle(.red) }
52 }
53 if let entry = CaptureEntry(text: text, defaults: session.defaults) {
54 EntryFields(entry: entry, change: change, planning: $planning, choosingTags: $choosingTags)
55 }
56 } else {
57 ForEach(questions.indices, id: \.self) { index in
58 QuestionField(question: questions[index], answer: $answers[index], defaultDate: request.day.map(Self.date))
59 }
60 if let problem { Text(problem).foregroundStyle(.red) }
61 }
62 }
63 .sheet(item: $planning) { which in
64 let entry = CaptureEntry(text: text, defaults: session.defaults)
65 DateTimeSheet(title: which.rawValue, initial: EntryFields.initial(which == .scheduled ? entry?.scheduled : entry?.deadline)) { answer in
66 planning = nil
67 if let answer { change(SetPlanning(deadline: which == .deadline), ["date": answer]) }
68 }
69 }
70 .sheet(isPresented: $choosingTags) {
71 TagsSheet(selected: CaptureEntry(text: text, defaults: session.defaults)?.tags ?? [], choices: Array(Set(context.allTags + context.fileTags)).sorted()) { tags in
72 choosingTags = false
73 if let tags { change(SetTags(), ["tags": tags.joined(separator: ":")]) }
74 }
75 }
76 .sheet(item: $refiling, onDismiss: { dismiss() }) { entry in
77 let document = session.openDocuments.first { $0.path == entry.path }?.document
78 ?? FileManager.default.contents(atPath: entry.path).map { DocumentState(bytes: [UInt8]($0)) }
79 RefileSheet(targets: workspace.refileTargets(openPath: entry.path, document: document)) { target in
80 // Filed either way; where refiling fails, the entry opens where it was filed.
81 let message = target.flatMap { session.refile(to: $0, from: (entry.path, entry.offset)) }
82 if target == nil || !(message?.hasPrefix("Refiled") ?? false) { model.openRequest = .offset(entry.path, entry.offset) }
83 refiling = nil
84 }
85 }
86 .navigationTitle("Capture")
87 .navigationBarTitleDisplayMode(.inline)
88 .toolbar {
89 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
90 if editing, template?.kind == .entry {
91 ToolbarItem(placement: .bottomBar) { Button("Refile…") { file(refile: true) } }
92 }
93 ToolbarItem(placement: .confirmationAction) {
94 if editing {
95 Button("File") { file() }.disabled(template == nil)
96 } else {
97 Button("Continue", action: fill)
98 }
99 }
100 }
101 }
102 .onAppear {
103 let loaded = CaptureTemplates.load()
104 templates = loaded.templates
105 groups = loaded.groups
106 problem = loaded.problems.first
107 key = request.template.flatMap { wanted in templates.first { $0.key == wanted }?.key } ?? templates.first?.key
108 if let wanted = request.template, !templates.contains(where: { $0.key == wanted }) { problem = "No capture template \"\(wanted)\"" }
109 }
110 .onChange(of: key, initial: true) { choose() }
111 }
112
113 /// The template's questions, asked before its text; none, and the text shows at once.
114 private func choose() {
115 guard let template else { return }
116 context = CaptureContext(
117 initial: request.properties["initial"] ?? "", annotation: request.properties["annotation"] ?? "",
118 allTags: (try? workspace.index.tags()) ?? []
119 )
120 context.linkProperties = request.properties
121 context.readsTemplateFiles()
122 // `%^g` offers the target file's tags.
123 let path = DocumentSession.resolve(template.target.file, root: workspace.rootPaths.first)
124 if !template.target.file.isEmpty,
125 let source = session.openTexts[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) {
126 var tags: [String] = []
127 for heading in DocumentModel(tree: OrgParser.parse(source)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
128 context.fileTags = tags
129 }
130 questions = (asksTreeDate(template) ? [Self.treeQuestion] : []) + Capture.questions(template.template, context: context)
131 answers = questions.map { _ in "" }
132 treeDate = nil
133 editing = false
134 if questions.isEmpty { fill() }
135 }
136
137 /// The template expanded with the answers; the caret where `%?` was.
138 /// `:time-prompt` asks first, unless the agenda day is the date.
139 private func asksTreeDate(_ template: CaptureTemplate) -> Bool { template.asksTreeDate && request.day == nil }
140
141 static let treeQuestion = Capture.Question(prompt: "Date for tree entry", defaultValue: "", choices: [], kind: .date(withTime: false, inactive: false))
142
143 /// The template's date: the tree's day, the agenda day, or now.
144 private var captureDate: Date { treeDate ?? request.day.map(Self.date) ?? Date() }
145
146 private func fill() {
147 guard let template else { return }
148 var answers = answers
149 if asksTreeDate(template) { treeDate = Capture.treeDate(answers.removeFirst(), now: Date()) }
150 context.now = captureDate
151 switch Capture.fill(template.template, context: context, answers: answers) {
152 case .success(let filled):
153 let (filledText, cursor) = request.day.map { Capture.scheduling(filled.text, cursor: filled.cursor, on: $0) } ?? (filled.text, filled.cursor)
154 text = filledText
155 selection = TextSelection(insertionPoint: String.Index(utf16Offset: cursor, in: filledText))
156 problem = nil
157 editing = true
158 focused = true
159 if template.options.immediateFinish { file() }
160 case .failure(.message(let message)):
161 problem = message
162 }
163 }
164
165 /// The entry's text after `command`, as the editor runs it. Changing a date here isn't a
166 /// reschedule, so it isn't logged as one.
167 private func change(_ command: any OrgCommand, _ answers: [String: String]) {
168 var options = session.options
169 options.logReschedule = nil
170 options.logRedeadline = nil
171 if let changed = CaptureEntry.applying(command, answers: answers, to: text, defaults: session.defaults, options: options, now: context.now) {
172 text = changed
173 }
174 }
175
176 /// Now's time of day on `day` (a `Days` number): the default time of an agenda day's
177 /// capture, as `org-agenda-capture` sets `org-overriding-default-time`.
178 static func date(_ day: Int) -> Date {
179 let calendar = Calendar.current
180 let d = Days.date(day)
181 var parts = calendar.dateComponents([.hour, .minute, .second], from: Date())
182 (parts.year, parts.month, parts.day) = (d.year, d.month, d.day)
183 return calendar.date(from: parts) ?? Date()
184 }
185
186 private func file(refile: Bool = false) {
187 guard let template else { return }
188 let now = Date()
189 let placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in
190 session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: treeDate ?? request.day.map(Self.date) ?? now)
191 }
192 switch placed {
193 case .failure(let error):
194 problem = error.message
195 editing = true
196 case .success(let entry):
197 // Clocked from when capture began.
198 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
199 Task { [clock, session, opened = context.now] in
200 _ = await clock.captured(entry, options: template.options, session: session, paths: paths, ask: model.clockPrompts.ask, opened: opened, now: now)
201 }
202 if refile {
203 refiling = RefileEntry(path: entry.path, offset: entry.offset)
204 return
205 }
206 if template.options.jumpToCaptured { model.openRequest = .offset(entry.path, entry.offset) }
207 dismiss()
208 }
209 }
210}
211
212private struct RefileEntry: Identifiable {
213 let path: String
214 let offset: Int
215 var id: String { "\(path)\u{0}\(offset)" }
216}
217
218/// One of a template's questions: text with its choices, tags, or a date.
219struct QuestionField: View {
220 let question: Capture.Question
221 @Binding var answer: String
222 /// What an empty date answer means: now, or the agenda day capture started from.
223 let defaultDate: Date?
224 @State private var date: Date
225
226 init(question: Capture.Question, answer: Binding<String>, defaultDate: Date? = nil) {
227 self.question = question
228 _answer = answer
229 self.defaultDate = defaultDate
230 _date = State(initialValue: defaultDate ?? Date())
231 }
232
233 var body: some View {
234 Section {
235 TextField(placeholder, text: $answer)
236 .autocorrectionDisabled()
237 .textInputAutocapitalization(.never)
238 if case .date(let withTime, _) = question.kind {
239 DatePicker("Date", selection: $date, displayedComponents: withTime ? [.date, .hourAndMinute] : [.date])
240 .onChange(of: date) { answer = Self.stamp(date, withTime: withTime) }
241 }
242 if !question.choices.isEmpty {
243 ScrollView(.horizontal, showsIndicators: false) {
244 HStack {
245 ForEach(question.choices.prefix(30), id: \.self) { choice in
246 Button(choice) { pick(choice) }.buttonStyle(.bordered)
247 }
248 }
249 }
250 }
251 } header: {
252 Text(question.prompt)
253 }
254 }
255
256 /// What an empty answer means.
257 private var placeholder: String {
258 switch question.kind {
259 case .text, .property, .clipboard: question.defaultValue
260 case .tags: "tag:tag"
261 case .date(let withTime, _):
262 defaultDate.map { Self.stamp($0, withTime: withTime) + "; or +2d, fri" }
263 ?? (withTime ? "now; or +2d, fri 14:00" : "today; or +2d, fri")
264 }
265 }
266
267 /// Tags add to what's typed; other choices replace it.
268 private func pick(_ choice: String) {
269 guard question.kind == .tags else { return answer = choice }
270 let tags = answer.split(separator: ":").map(String.init)
271 if !tags.contains(choice) { answer = (tags + [choice]).joined(separator: ":") }
272 }
273
274 static func stamp(_ date: Date, withTime: Bool) -> String {
275 let formatter = DateFormatter()
276 formatter.locale = Locale(identifier: "en_US_POSIX")
277 formatter.dateFormat = withTime ? "yyyy-MM-dd HH:mm" : "yyyy-MM-dd"
278 return formatter.string(from: date)
279 }
280}
281/// Which date of the captured entry is being picked.
282private enum EntryPlanning: String, Identifiable {
283 case scheduled = "Scheduled", deadline = "Deadline"
284 var id: Self { self }
285}
286
287/// The captured entry's keyword, priority, dates and tags, set without editing its text.
288private struct EntryFields: View {
289 let entry: CaptureEntry
290 let change: (any OrgCommand, [String: String]) -> Void
291 @Binding var planning: EntryPlanning?
292 @Binding var choosingTags: Bool
293
294 var body: some View {
295 Section {
296 Picker("State", selection: Binding { entry.todo ?? "" } set: { change(SetTodo(keyword: $0.isEmpty ? nil : $0), [:]) }) {
297 Text("None").tag("")
298 ForEach(entry.keywords, id: \.self) { Text($0).tag($0) }
299 }
300 if !entry.priorities.isEmpty {
301 Picker("Priority", selection: Binding { entry.priority ?? "" } set: { change(SetPriority(), ["priority": $0.isEmpty ? " " : $0]) }) {
302 Text("None").tag("")
303 ForEach(entry.priorities, id: \.self) { Text($0).tag($0) }
304 }
305 }
306 date(.scheduled, entry.scheduled)
307 date(.deadline, entry.deadline)
308 Button {
309 choosingTags = true
310 } label: {
311 LabeledContent("Tags", value: entry.tags.isEmpty ? "None" : entry.tags.joined(separator: " "))
312 }
313 .tint(.primary)
314 }
315 }
316
317 private func date(_ which: EntryPlanning, _ stamp: Timestamp?) -> some View {
318 Menu {
319 Button("Today") { set(which, 0) }
320 Button("Tomorrow") { set(which, 1) }
321 Button("In a Week") { set(which, 7) }
322 Button("Pick Date…") { planning = which }
323 if stamp != nil {
324 Button("Remove", role: .destructive) { change(RemovePlanning(deadline: which == .deadline), [:]) }
325 }
326 } label: {
327 LabeledContent(which.rawValue, value: stamp.map(Self.text) ?? "None")
328 }
329 .tint(.primary)
330 }
331
332 private func set(_ which: EntryPlanning, _ days: Int) {
333 let day = Calendar.current.date(byAdding: .day, value: days, to: Date()) ?? Date()
334 change(SetPlanning(deadline: which == .deadline), ["date": QuestionField.stamp(day, withTime: false)])
335 }
336
337 static func initial(_ stamp: Timestamp?) -> Date {
338 guard let stamp else { return Date() }
339 let point = stamp.start
340 return Calendar.current.date(from: DateComponents(year: point.year, month: point.month, day: point.day, hour: point.hour, minute: point.minute)) ?? Date()
341 }
342
343 /// `Sat 12 Oct`, with the time when it has one.
344 private static func text(_ stamp: Timestamp) -> String {
345 let point = stamp.start
346 let date = Calendar.current.date(from: DateComponents(year: point.year, month: point.month, day: point.day)) ?? Date()
347 let day = date.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))
348 guard let hour = point.hour else { return day }
349 return day + String(format: " %02d:%02d", hour, point.minute ?? 0)
350 }
351}
352
353/// A date and, when switched on, a time; the answer as a date prompt takes it.
354private struct DateTimeSheet: View {
355 let title: String
356 let initial: Date
357 let done: (String?) -> Void
358 @State private var date = Date()
359 @State private var withTime = false
360
361 var body: some View {
362 NavigationStack {
363 Form {
364 DatePicker(title, selection: $date, displayedComponents: .date).datePickerStyle(.graphical)
365 Toggle("Time", isOn: $withTime)
366 if withTime { DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute) }
367 }
368 .navigationTitle(title)
369 .navigationBarTitleDisplayMode(.inline)
370 .toolbar {
371 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { done(nil) } }
372 ToolbarItem(placement: .confirmationAction) { Button("Set") { done(QuestionField.stamp(date, withTime: withTime)) } }
373 }
374 }
375 .presentationDetents([.large])
376 .onAppear { date = initial }
377 }
378}
379
380/// Tags to toggle, from the file and the workspace, and new ones typed in.
381private struct TagsSheet: View {
382 let choices: [String]
383 let done: ([String]?) -> Void
384 @State private var selected: [String]
385 @State private var typed = ""
386
387 init(selected: [String], choices: [String], done: @escaping ([String]?) -> Void) {
388 _selected = State(initialValue: selected)
389 self.choices = choices
390 self.done = done
391 }
392
393 var body: some View {
394 NavigationStack {
395 List {
396 Section {
397 TextField("New tag", text: $typed)
398 .autocorrectionDisabled()
399 .textInputAutocapitalization(.never)
400 .onSubmit(add)
401 }
402 Section {
403 ForEach(Array(Set(choices + selected)).sorted(), id: \.self) { tag in
404 Button {
405 if selected.contains(tag) { selected.removeAll { $0 == tag } } else { selected.append(tag) }
406 } label: {
407 HStack {
408 Text(tag).foregroundStyle(.primary)
409 Spacer()
410 if selected.contains(tag) { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
411 }
412 }
413 }
414 }
415 }
416 .navigationTitle("Tags")
417 .navigationBarTitleDisplayMode(.inline)
418 .toolbar {
419 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { done(nil) } }
420 ToolbarItem(placement: .confirmationAction) {
421 Button("Set") {
422 add()
423 done(selected)
424 }
425 }
426 }
427 }
428 }
429
430 /// The typed tags, `:` or spaces between several, added and checked.
431 private func add() {
432 for tag in typed.split(whereSeparator: { $0 == ":" || $0 == " " }).map(String.init) where !selected.contains(tag) { selected.append(tag) }
433 typed = ""
434 }
435}
436#endif