Sources/OrgstarMobile/CaptureScreen.swift

71105e530ae19022795c2d9038c3edfefc5da64e
orgstar/Sources/OrgstarMobile/CaptureScreen.swift

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