Sources/OrgstarMobile/CaptureScreen.swift

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

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