Sources/OrgstarMobile/CaptureScreen.swift

1d52ac3e828cb73639dc1c0cd5b6c9f0795b14a7
orgstar/Sources/OrgstarMobile/CaptureScreen.swift history · blame · raw

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