Sources/OrgstarMobile/CaptureScreen.swift

73fcba4bfb8709ee26c1b1ecee1b70ce400e5b7e
orgstar/Sources/OrgstarMobile/CaptureScreen.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form