Sources/OrgstarMobile/CaptureScreen.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgstarMobile/CaptureScreen.swift history · blame · raw

473 lines · 22079 bytes

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