Sources/OrgstarMobile/CaptureScreen.swift

451 lines · 20561 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    /// `date` at the next whole hour from now when it has no time of day yet, for a time
275    /// switched on; otherwise as it is.
276    static func timed(_ date: Date, now: Date = Date()) -> Date {
277        let calendar = Calendar.current
278        let parts = calendar.dateComponents([.hour, .minute], from: date)
279        guard parts.hour == 0, parts.minute == 0 else { return date }
280        let hour = min(calendar.component(.hour, from: now) + 1, 23)
281        return calendar.date(bySettingHour: hour, minute: 0, second: 0, of: date) ?? date
282    }
283
284    static func stamp(_ date: Date, withTime: Bool) -> String {
285        let formatter = DateFormatter()
286        formatter.locale = Locale(identifier: "en_US_POSIX")
287        formatter.dateFormat = withTime ? "yyyy-MM-dd HH:mm" : "yyyy-MM-dd"
288        return formatter.string(from: date)
289    }
290}
291/// Which date of the captured entry is being picked.
292private enum EntryPlanning: String, Identifiable {
293    case scheduled = "Scheduled", deadline = "Deadline"
294    var id: Self { self }
295}
296
297/// The captured entry's keyword, priority, dates and tags, set without editing its text.
298private struct EntryFields: View {
299    let entry: CaptureEntry
300    let change: (any OrgCommand, [String: String]) -> Void
301    @Binding var planning: EntryPlanning?
302    @Binding var choosingTags: Bool
303
304    var body: some View {
305        Section {
306            Picker("State", selection: Binding { entry.todo ?? "" } set: { change(SetTodo(keyword: $0.isEmpty ? nil : $0), [:]) }) {
307                Text("None").tag("")
308                ForEach(entry.keywords, id: \.self) { Text($0).tag($0) }
309            }
310            if !entry.priorities.isEmpty {
311                Picker("Priority", selection: Binding { entry.priority ?? "" } set: { change(SetPriority(), ["priority": $0.isEmpty ? " " : $0]) }) {
312                    Text("None").tag("")
313                    ForEach(entry.priorities, id: \.self) { Text($0).tag($0) }
314                }
315            }
316            date(.scheduled, entry.scheduled)
317            date(.deadline, entry.deadline)
318            Button {
319                choosingTags = true
320            } label: {
321                LabeledContent("Tags", value: entry.tags.isEmpty ? "None" : entry.tags.joined(separator: " "))
322            }
323            .tint(.primary)
324        }
325    }
326
327    private func date(_ which: EntryPlanning, _ stamp: Timestamp?) -> some View {
328        Menu {
329            Button("Today") { set(which, 0) }
330            Button("Tomorrow") { set(which, 1) }
331            Button("In a Week") { set(which, 7) }
332            Button("Pick Date…") { planning = which }
333            if stamp != nil {
334                Button("Remove", role: .destructive) { change(RemovePlanning(deadline: which == .deadline), [:]) }
335            }
336        } label: {
337            LabeledContent(which.rawValue, value: stamp.map(Self.text) ?? "None")
338        }
339        .tint(.primary)
340    }
341
342    private func set(_ which: EntryPlanning, _ days: Int) {
343        let day = Calendar.current.date(byAdding: .day, value: days, to: Date()) ?? Date()
344        change(SetPlanning(deadline: which == .deadline), ["date": QuestionField.stamp(day, withTime: false)])
345    }
346
347    static func initial(_ stamp: Timestamp?) -> Date {
348        guard let stamp else { return Calendar.current.startOfDay(for: Date()) }
349        let point = stamp.start
350        return Calendar.current.date(from: DateComponents(year: point.year, month: point.month, day: point.day, hour: point.hour, minute: point.minute)) ?? Date()
351    }
352
353    /// `Sat 12 Oct`, with the time when it has one.
354    private static func text(_ stamp: Timestamp) -> String {
355        let point = stamp.start
356        let date = Calendar.current.date(from: DateComponents(year: point.year, month: point.month, day: point.day)) ?? Date()
357        let day = date.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))
358        guard let hour = point.hour else { return day }
359        return day + String(format: " %02d:%02d", hour, point.minute ?? 0)
360    }
361}
362
363/// A date and, when switched on, a time; the answer as a date prompt takes it.
364private struct DateTimeSheet: View {
365    let title: String
366    let initial: Date
367    let done: (String?) -> Void
368    @State private var date = Date()
369    @State private var withTime = false
370
371    var body: some View {
372        NavigationStack {
373            Form {
374                DatePicker(title, selection: $date, displayedComponents: .date).datePickerStyle(.graphical)
375                Toggle("Time", isOn: $withTime)
376                    .onChange(of: withTime) { if withTime { date = QuestionField.timed(date) } }
377                if withTime { DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute) }
378            }
379            .navigationTitle(title)
380            .navigationBarTitleDisplayMode(.inline)
381            .toolbar {
382                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { done(nil) } }
383                ToolbarItem(placement: .confirmationAction) { Button("Set") { done(QuestionField.stamp(date, withTime: withTime)) } }
384            }
385        }
386        .presentationDetents([.large])
387        .onAppear {
388            date = initial
389            let parts = Calendar.current.dateComponents([.hour, .minute], from: initial)
390            withTime = parts.hour != 0 || parts.minute != 0
391        }
392    }
393}
394
395/// Tags to toggle, from the file and the workspace, and new ones typed in.
396private struct TagsSheet: View {
397    let choices: [String]
398    let done: ([String]?) -> Void
399    @State private var selected: [String]
400    @State private var typed = ""
401
402    init(selected: [String], choices: [String], done: @escaping ([String]?) -> Void) {
403        _selected = State(initialValue: selected)
404        self.choices = choices
405        self.done = done
406    }
407
408    var body: some View {
409        NavigationStack {
410            List {
411                Section {
412                    TextField("New tag", text: $typed)
413                        .autocorrectionDisabled()
414                        .textInputAutocapitalization(.never)
415                        .onSubmit(add)
416                }
417                Section {
418                    ForEach(Array(Set(choices + selected)).sorted(), id: \.self) { tag in
419                        Button {
420                            if selected.contains(tag) { selected.removeAll { $0 == tag } } else { selected.append(tag) }
421                        } label: {
422                            HStack {
423                                Text(tag).foregroundStyle(.primary)
424                                Spacer()
425                                if selected.contains(tag) { Image(systemName: "checkmark").foregroundStyle(Color.accentColor) }
426                            }
427                        }
428                    }
429                }
430            }
431            .navigationTitle("Tags")
432            .navigationBarTitleDisplayMode(.inline)
433            .toolbar {
434                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { done(nil) } }
435                ToolbarItem(placement: .confirmationAction) {
436                    Button("Set") {
437                        add()
438                        done(selected)
439                    }
440                }
441            }
442        }
443    }
444
445    /// The typed tags, `:` or spaces between several, added and checked.
446    private func add() {
447        for tag in typed.split(whereSeparator: { $0 == ":" || $0 == " " }).map(String.init) where !selected.contains(tag) { selected.append(tag) }
448        typed = ""
449    }
450}
451#endif