Sources/OrgstarMobile/CaptureScreen.swift

9a7439fd01e4ce5041bc5fab90542f083143ae10
orgstar/Sources/OrgstarMobile/CaptureScreen.swift history · blame · raw

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