Sources/OrgstarMobile/CaptureScreen.swift

a866e469a3568bf7a2829a8dd2a56317ced4736e
orgstar/Sources/OrgstarMobile/CaptureScreen.swift history · blame · raw

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