Sources/OrgstarMobile/EditorScreen.swift

46d6a046f519e5ab5a9338ff643341bd53e7788f
orgstar/Sources/OrgstarMobile/EditorScreen.swift history · blame · raw

432 lines · 18658 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import OrgDocument
  5import SwiftUI
  6import UIKit
  7
  8/// Editing a file: the text with Org's folding and styling, a bar of Org keys over the keyboard,
  9/// and every command in a palette. The editor is the open file's live state, so autosave and
 10/// merging go through the session as on the Mac.
 11struct EditorScreen: View {
 12    let path: String
 13    let offset: Int?
 14    let workspace: WorkspaceModel
 15    let session: DocumentSession
 16    @State private var editor: MobileEditor?
 17    @State private var prompt: PromptRequest?
 18    @State private var message: String?
 19    @State private var sheet: Sheet?
 20    @State private var trust = TrustStore()
 21    /// The command chosen in the palette, run once the palette is gone.
 22    @State private var chosen: String?
 23    @Environment(ClockModel.self) private var clock
 24    @Environment(MobileModel.self) private var model
 25    @Environment(\.openURL) private var openURL
 26
 27    struct PromptRequest: Identifiable {
 28        let id = UUID()
 29        let prompt: Prompt
 30        let reply: (String?) -> Void
 31    }
 32
 33    /// One sheet at a time: two presenters on this screen interfere.
 34    enum Sheet: Identifiable {
 35        case palette, conflict, syncCopies, recovery
 36        case block(BlockEdit)
 37
 38        var id: String {
 39            switch self {
 40            case .palette: "palette"
 41            case .conflict: "conflict"
 42            case .syncCopies: "syncCopies"
 43            case .recovery: "recovery"
 44            case .block(let edit): "block \(edit.range)"
 45            }
 46        }
 47    }
 48
 49    var body: some View {
 50        Group {
 51            if let editor {
 52                EditorTextView(editor: editor, palette: { sheet = .palette })
 53                    .ignoresSafeArea(.container, edges: .bottom)
 54            } else {
 55                ProgressView()
 56            }
 57        }
 58        .navigationTitle((path as NSString).lastPathComponent + (session.dirtyPaths.contains(path) ? " •" : ""))
 59        .navigationBarTitleDisplayMode(.inline)
 60        .toolbar(.hidden, for: .tabBar)
 61        .toolbar {
 62            ToolbarItemGroup(placement: .primaryAction) {
 63                if session.conflict != nil {
 64                    Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
 65                }
 66                Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
 67                Menu("More", systemImage: "ellipsis.circle") {
 68                    Button("Commands", systemImage: "command") { sheet = .palette }
 69                    Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
 70                    if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) }
 71                    Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
 72                    Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
 73                }
 74            }
 75        }
 76        .safeAreaInset(edge: .top) {
 77            if let message {
 78                Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
 79                    .onTapGesture { self.message = nil }
 80                    .task(id: message) {
 81                        try? await Task.sleep(for: .seconds(4))
 82                        if self.message == message { self.message = nil }
 83                    }
 84            }
 85        }
 86        .sheet(item: $prompt) { request in
 87            PromptSheet(prompt: request.prompt) { answer in
 88                prompt = nil
 89                request.reply(answer)
 90            }
 91        }
 92        .sheet(item: $sheet, onDismiss: {
 93            // After the sheet has gone, so a command's own prompt can show.
 94            if let id = chosen {
 95                chosen = nil
 96                editor?.run(id)
 97            }
 98        }) { sheet in
 99            switch sheet {
100            case .palette: if let editor { CommandPalette(editor: editor) { chosen = $0 } }
101            case .conflict: ConflictSheet(session: session)
102            case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
103            case .recovery: RecoverySheet(session: session) { message = $0 }
104            case .block(let edit):
105                BlockEditSheet(edit: edit) { content in
106                    self.sheet = nil
107                    if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
108                }
109            }
110        }
111        .onChange(of: session.conflict) { _, conflict in
112            if conflict != nil, session.path == path { sheet = .conflict }
113        }
114        .onChange(of: session.lastError) { _, error in
115            if let error { message = error; session.lastError = nil }
116        }
117        .onAppear(perform: start)
118        .onChange(of: session.revealRequest?.id) {
119            if let offset = session.revealRequest?.offset, session.path == path { editor?.reveal(offset) }
120        }
121        .onDisappear {
122            // Typing the reader shows next, and a save, don't wait for the autosave delay.
123            if session.dirtyPaths.contains(path) { _ = session.save(path) }
124        }
125    }
126
127    /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
128    private func run(_ job: BabelJob) {
129        let go = {
130            message = "Running \(job.language) block…"
131            session.startBabel(job) { message = $0 }
132        }
133        if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
134        let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
135        prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
136            switch answer {
137            case "always":
138                trust.trust(path: path, content: job.blockText)
139                go()
140            case "yes": go()
141            default: message = "Not run"
142            }
143        }
144    }
145
146    private func start() {
147        if session.path != path { session.open(path) }
148        if editor == nil, let document = session.document {
149            let editor = MobileEditor(document: document, editable: document.isEditable)
150            editor.options = session.options
151            editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
152            editor.onChange = { [weak session] in session?.bufferChanged(path) }
153            editor.onMessage = { message = $0 }
154            editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
155            editor.onLink = { link in
156                switch session.follow(link, workspace: workspace, isText: { _ in false }) {
157                case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")"
158                case .openExternally(let url): openURL(url)
159                case .message(let text): message = text
160                }
161            }
162            editor.onEditBlock = { edit in sheet = .block(edit) }
163            editor.onTangle = { scope in message = session.tangle(scope) }
164            editor.onBabel = { job in run(job) }
165            editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
166            editor.onAppCommand = { id in
167                switch id {
168                case "app.clock.in": message = clock.clockIn(session)
169                case "app.clock.out": message = clock.clockOut(session)
170                case "app.clock.cancel": message = clock.clockOut(session, cancel: true)
171                case "app.clock.goto":
172                    if let location = clock.location(session) { model.openRequest = .offset(location.path, location.offset) } else { message = "No active clock" }
173                default: message = "Not available on iOS yet"
174                }
175            }
176            self.editor = editor
177        }
178        if let editor { session.attach(editor) }
179        if let offset { editor?.reveal(offset) }
180        if session.conflict != nil {
181            sheet = .conflict
182        } else if case let copies = session.syncConflictCopies().count, copies > 0 {
183            message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
184        }
185    }
186}
187
188/// The editor's text view, with the Org key bar over the keyboard.
189struct EditorTextView: UIViewRepresentable {
190    let editor: MobileEditor
191    let palette: () -> Void
192
193    func makeUIView(context: Context) -> UITextView {
194        let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
195        bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
196        bar.view.backgroundColor = .clear
197        bar.sizingOptions = []
198        editor.textView.inputAccessoryView = bar.view
199        context.coordinator.bar = bar
200        return editor.textView
201    }
202
203    func updateUIView(_ view: UITextView, context: Context) {}
204
205    func makeCoordinator() -> Coordinator { Coordinator() }
206
207    final class Coordinator {
208        var bar: UIViewController?
209    }
210}
211
212/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
213/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
214struct KeyBar: View {
215    let editor: MobileEditor
216    let palette: () -> Void
217
218    private static let keys: [(label: String, symbol: String?, keys: String)] = [
219        ("Fold", "arrow.right.to.line", "TAB"),
220        ("Overview", "arrow.left.to.line", "S-TAB"),
221        ("Promote", "arrow.left", "M-<left>"),
222        ("Demote", "arrow.right", "M-<right>"),
223        ("Move up", "arrow.up", "M-<up>"),
224        ("Move down", "arrow.down", "M-<down>"),
225        ("New heading or item", "plus", "M-RET"),
226        ("TODO", nil, "C-c C-t"),
227        ("Act at point", "checkmark.square", "C-c C-c"),
228        ("Schedule", "calendar", "C-c C-s"),
229        ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
230        ("Tags", "tag", "C-c C-q"),
231        ("Open link", "link", "C-c C-o"),
232    ]
233
234    var body: some View {
235        ScrollView(.horizontal, showsIndicators: false) {
236            HStack(spacing: 4) {
237                Button("Commands", systemImage: "command", action: palette)
238                ForEach(Self.keys, id: \.keys) { key in
239                    Button {
240                        editor.run(keys: key.keys)
241                    } label: {
242                        if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
243                    }
244                    .accessibilityLabel(key.label)
245                }
246                Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
247            }
248            .labelStyle(.iconOnly)
249            .buttonStyle(.bordered)
250            .padding(.horizontal, 8)
251            .padding(.vertical, 6)
252        }
253        .background(.bar)
254    }
255}
256
257/// A command's question: text with choices, a date, or fast selection by keys.
258struct PromptSheet: View {
259    let prompt: Prompt
260    let answer: (String?) -> Void
261    @State private var text = ""
262    @State private var date = Date()
263    @State private var keys: [FastSelection.Input] = []
264
265    var body: some View {
266        NavigationStack {
267            Form {
268                if let fast = prompt.fast {
269                    fastSection(fast)
270                } else {
271                    Section {
272                        TextField(prompt.message, text: $text)
273                            .autocorrectionDisabled()
274                            .textInputAutocapitalization(.never)
275                            .onSubmit { answer(text) }
276                    } footer: {
277                        if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
278                    }
279                    if prompt.date != nil {
280                        DatePicker("Date", selection: $date, displayedComponents: [.date])
281                            .datePickerStyle(.graphical)
282                            .onChange(of: date) { text = Self.stamp(date) }
283                    }
284                    if !prompt.choices.isEmpty {
285                        let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
286                        Section("Choices") {
287                            ForEach(matching.prefix(50), id: \.self) { choice in
288                                Button(choice) { choose(choice) }
289                            }
290                        }
291                    }
292                }
293            }
294            .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
295            .navigationBarTitleDisplayMode(.inline)
296            .toolbar {
297                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
298                if prompt.fast == nil || prompt.fast?.multiple == true {
299                    ToolbarItem(placement: .confirmationAction) {
300                        Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
301                            .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
302                    }
303                }
304            }
305        }
306        .onAppear {
307            text = prompt.initial
308            if let day = prompt.date?.defaultDate { date = day }
309        }
310    }
311
312    /// With a separator (tags), what's typed after the last one.
313    private var lastPart: String {
314        guard let separator = prompt.completionSeparator else { return text }
315        return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
316    }
317
318    private func choose(_ choice: String) {
319        guard let separator = prompt.completionSeparator else {
320            text = choice
321            if prompt.date == nil { answer(choice) }
322            return
323        }
324        var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
325        if parts.isEmpty { parts = [""] }
326        parts[parts.count - 1] = choice
327        text = parts.joined(separator: String(separator)) + String(separator)
328    }
329
330    @ViewBuilder
331    private func fastSection(_ fast: FastSelection) -> some View {
332        let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
333        Section {
334            ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
335                Button {
336                    if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
337                } label: {
338                    HStack {
339                        Text(option.name).foregroundStyle(.primary)
340                        Spacer()
341                        if current.contains(option.name) { Image(systemName: "checkmark") }
342                        Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
343                    }
344                }
345            }
346            if !fast.multiple {
347                Button("No keyword") { answer(" ") }
348            }
349        } footer: {
350            if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
351        }
352    }
353
354    static func stamp(_ date: Date) -> String {
355        let formatter = DateFormatter()
356        formatter.locale = Locale(identifier: "en_US_POSIX")
357        formatter.dateFormat = "yyyy-MM-dd"
358        return formatter.string(from: date)
359    }
360}
361
362/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
363struct BlockEditSheet: View {
364    let edit: BlockEdit
365    let finish: (String?) -> Void
366    @State private var text = ""
367    @FocusState private var focused: Bool
368
369    var body: some View {
370        NavigationStack {
371            TextEditor(text: $text)
372                .font(.body.monospaced())
373                .autocorrectionDisabled()
374                .textInputAutocapitalization(.never)
375                .focused($focused)
376                .padding(.horizontal, 8)
377                .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
378                .navigationBarTitleDisplayMode(.inline)
379                .toolbar {
380                    ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
381                    ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text) } }
382                }
383        }
384        .onAppear {
385            text = edit.content
386            focused = true
387        }
388    }
389}
390
391/// Every command that applies at the caret, by name.
392struct CommandPalette: View {
393    let editor: MobileEditor
394    /// Called with the chosen command before the palette closes.
395    let choose: (String) -> Void
396    @State private var query = ""
397    @Environment(\.dismiss) private var dismiss
398
399    private static let viewCommands: [(id: String, title: String)] = [
400        ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
401        ("edit.undo", "Undo"), ("edit.redo", "Redo"),
402        ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
403        ("app.clock.goto", "Go to Clocked Entry"),
404    ]
405
406    var body: some View {
407        let context = editor.editContext()
408        let all = Self.viewCommands + Commands.everything.map { ($0.id, $0.title) }
409        let shown = all.filter { editor.applies($0.id, in: context) && (query.isEmpty || $0.title.localizedCaseInsensitiveContains(query)) }
410        NavigationStack {
411            List(shown, id: \.id) { command in
412                Button {
413                    choose(command.id)
414                    dismiss()
415                } label: {
416                    HStack {
417                        Text(command.title).foregroundStyle(.primary)
418                        Spacer()
419                        if let keys = editor.keymap.keyLabels(for: command.id).first {
420                            Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
421                        }
422                    }
423                }
424            }
425            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
426            .navigationTitle("Commands")
427            .navigationBarTitleDisplayMode(.inline)
428            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
429        }
430    }
431}
432#endif