Sources/OrgstarMobile/CaptureScreen.swift

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

182 lines · 7573 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import SwiftUI
  5
  6/// Capture with a template: its questions (`%^{…}`, `%^g`, `%^t`…), then its text to edit,
  7/// filed where the template says, as `org-capture` does.
  8struct CaptureScreen: View {
  9    let workspace: WorkspaceModel
 10    let session: DocumentSession
 11    let request: CaptureRequest
 12    @Environment(\.dismiss) private var dismiss
 13    @Environment(ClockModel.self) private var clock
 14    @Environment(MobileModel.self) private var model
 15    @State private var templates: [CaptureTemplate] = []
 16    @State private var key: String?
 17    @State private var context = CaptureContext()
 18    @State private var questions: [Capture.Question] = []
 19    @State private var answers: [String] = []
 20    @State private var editing = false
 21    @State private var text = ""
 22    @State private var selection: TextSelection?
 23    @State private var problem: String?
 24    @FocusState private var focused: Bool
 25
 26    private var template: CaptureTemplate? { templates.first { $0.key == key } }
 27
 28    var body: some View {
 29        NavigationStack {
 30            Form {
 31                Picker("Template", selection: $key) {
 32                    ForEach(templates) { Text($0.name).tag(Optional($0.key)) }
 33                }
 34                if editing {
 35                    Section {
 36                        TextEditor(text: $text, selection: $selection)
 37                            .font(.body.monospaced())
 38                            .frame(minHeight: 200)
 39                            .focused($focused)
 40                    } footer: {
 41                        if let problem { Text(problem).foregroundStyle(.red) }
 42                    }
 43                } else {
 44                    ForEach(questions.indices, id: \.self) { index in
 45                        QuestionField(question: questions[index], answer: $answers[index])
 46                    }
 47                    if let problem { Text(problem).foregroundStyle(.red) }
 48                }
 49            }
 50            .navigationTitle("Capture")
 51            .navigationBarTitleDisplayMode(.inline)
 52            .toolbar {
 53                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
 54                ToolbarItem(placement: .confirmationAction) {
 55                    if editing {
 56                        Button("File", action: file).disabled(template == nil)
 57                    } else {
 58                        Button("Continue", action: fill)
 59                    }
 60                }
 61            }
 62        }
 63        .onAppear {
 64            let loaded = CaptureTemplates.load()
 65            templates = loaded.templates
 66            problem = loaded.problems.first
 67            key = request.template.flatMap { wanted in templates.first { $0.key == wanted }?.key } ?? templates.first?.key
 68        }
 69        .onChange(of: key, initial: true) { choose() }
 70    }
 71
 72    /// The template's questions, asked before its text; none, and the text shows at once.
 73    private func choose() {
 74        guard let template else { return }
 75        context = CaptureContext(
 76            initial: request.properties["initial"] ?? "", annotation: request.properties["annotation"] ?? "",
 77            allTags: (try? workspace.index.tags()) ?? []
 78        )
 79        context.linkProperties = request.properties
 80        // `%^g` offers the target file's tags.
 81        let path = DocumentSession.resolve(template.target.file, root: workspace.rootPaths.first)
 82        if !template.target.file.isEmpty,
 83           let source = session.openTexts[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) {
 84            var tags: [String] = []
 85            for heading in DocumentModel(tree: OrgParser.parse(source)).headings { for tag in heading.localTags where !tags.contains(tag) { tags.append(tag) } }
 86            context.fileTags = tags
 87        }
 88        questions = Capture.questions(template.template, context: context)
 89        answers = questions.map { _ in "" }
 90        editing = false
 91        if questions.isEmpty { fill() }
 92    }
 93
 94    /// The template expanded with the answers; the caret where `%?` was.
 95    private func fill() {
 96        guard let template else { return }
 97        context.now = Date()
 98        switch Capture.fill(template.template, context: context, answers: answers) {
 99        case .success(let filled):
100            text = filled.text
101            selection = TextSelection(insertionPoint: String.Index(utf16Offset: filled.cursor, in: filled.text))
102            problem = nil
103            editing = true
104            focused = true
105            if template.options.immediateFinish { file() }
106        case .failure(.message(let message)):
107            problem = message
108        }
109    }
110
111    private func file() {
112        guard let template else { return }
113        let now = Date()
114        let placed = template.resolved(workspace: workspace, session: session, clock: clock).flatMap { resolved in
115            session.capture(text, template: resolved.template, root: workspace.rootPaths.first, file: resolved.file, now: now)
116        }
117        switch placed {
118        case .failure(let error):
119            problem = error.message
120            editing = true
121        case .success(let entry):
122            // Clocked from when capture began.
123            _ = clock.captured(entry, options: template.options, session: session, opened: context.now, now: now)
124            if template.options.jumpToCaptured { model.openRequest = .offset(entry.path, entry.offset) }
125            dismiss()
126        }
127    }
128}
129
130/// One of a template's questions: text with its choices, tags, or a date.
131struct QuestionField: View {
132    let question: Capture.Question
133    @Binding var answer: String
134    @State private var date = Date()
135
136    var body: some View {
137        Section {
138            TextField(placeholder, text: $answer)
139                .autocorrectionDisabled()
140                .textInputAutocapitalization(.never)
141            if case .date(let withTime, _) = question.kind {
142                DatePicker("Date", selection: $date, displayedComponents: withTime ? [.date, .hourAndMinute] : [.date])
143                    .onChange(of: date) { answer = Self.stamp(date, withTime: withTime) }
144            }
145            if !question.choices.isEmpty {
146                ScrollView(.horizontal, showsIndicators: false) {
147                    HStack {
148                        ForEach(question.choices.prefix(30), id: \.self) { choice in
149                            Button(choice) { pick(choice) }.buttonStyle(.bordered)
150                        }
151                    }
152                }
153            }
154        } header: {
155            Text(question.prompt)
156        }
157    }
158
159    /// What an empty answer means.
160    private var placeholder: String {
161        switch question.kind {
162        case .text, .property, .clipboard: question.defaultValue
163        case .tags: "tag:tag"
164        case .date(let withTime, _): withTime ? "now; or +2d, fri 14:00" : "today; or +2d, fri"
165        }
166    }
167
168    /// Tags add to what's typed; other choices replace it.
169    private func pick(_ choice: String) {
170        guard question.kind == .tags else { return answer = choice }
171        let tags = answer.split(separator: ":").map(String.init)
172        if !tags.contains(choice) { answer = (tags + [choice]).joined(separator: ":") }
173    }
174
175    static func stamp(_ date: Date, withTime: Bool) -> String {
176        let formatter = DateFormatter()
177        formatter.locale = Locale(identifier: "en_US_POSIX")
178        formatter.dateFormat = withTime ? "yyyy-MM-dd HH:mm" : "yyyy-MM-dd"
179        return formatter.string(from: date)
180    }
181}
182#endif