Sources/OrgstarMobile/CaptureScreen.swift

bd275bd1a81b85a03549d5435d6a0bd32c2cbd66
orgstar/Sources/OrgstarMobile/CaptureScreen.swift

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