Sources/OrgstarMobile/EditorScreen.swift

7f4768ef8f7de8b64da04e67a271c08d6645fef3
orgstar/Sources/OrgstarMobile/EditorScreen.swift history · blame · raw

433 lines · 18709 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(session.bufferName(path) + (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.onRefreshSetup = { session.refreshSetup() }
166            editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
167            editor.onAppCommand = { id in
168                switch id {
169                case "app.clock.in": message = clock.clockIn(session)
170                case "app.clock.out": message = clock.clockOut(session)
171                case "app.clock.cancel": message = clock.clockOut(session, cancel: true)
172                case "app.clock.goto":
173                    if let location = clock.location(session) { model.openRequest = .offset(location.path, location.offset) } else { message = "No active clock" }
174                default: message = "Not available on iOS yet"
175                }
176            }
177            self.editor = editor
178        }
179        if let editor { session.attach(editor) }
180        if let offset { editor?.reveal(offset) }
181        if session.conflict != nil {
182            sheet = .conflict
183        } else if case let copies = session.syncConflictCopies().count, copies > 0 {
184            message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
185        }
186    }
187}
188
189/// The editor's text view, with the Org key bar over the keyboard.
190struct EditorTextView: UIViewRepresentable {
191    let editor: MobileEditor
192    let palette: () -> Void
193
194    func makeUIView(context: Context) -> UITextView {
195        let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
196        bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
197        bar.view.backgroundColor = .clear
198        bar.sizingOptions = []
199        editor.textView.inputAccessoryView = bar.view
200        context.coordinator.bar = bar
201        return editor.textView
202    }
203
204    func updateUIView(_ view: UITextView, context: Context) {}
205
206    func makeCoordinator() -> Coordinator { Coordinator() }
207
208    final class Coordinator {
209        var bar: UIViewController?
210    }
211}
212
213/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
214/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
215struct KeyBar: View {
216    let editor: MobileEditor
217    let palette: () -> Void
218
219    private static let keys: [(label: String, symbol: String?, keys: String)] = [
220        ("Fold", "arrow.right.to.line", "TAB"),
221        ("Overview", "arrow.left.to.line", "S-TAB"),
222        ("Promote", "arrow.left", "M-<left>"),
223        ("Demote", "arrow.right", "M-<right>"),
224        ("Move up", "arrow.up", "M-<up>"),
225        ("Move down", "arrow.down", "M-<down>"),
226        ("New heading or item", "plus", "M-RET"),
227        ("TODO", nil, "C-c C-t"),
228        ("Act at point", "checkmark.square", "C-c C-c"),
229        ("Schedule", "calendar", "C-c C-s"),
230        ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
231        ("Tags", "tag", "C-c C-q"),
232        ("Open link", "link", "C-c C-o"),
233    ]
234
235    var body: some View {
236        ScrollView(.horizontal, showsIndicators: false) {
237            HStack(spacing: 4) {
238                Button("Commands", systemImage: "command", action: palette)
239                ForEach(Self.keys, id: \.keys) { key in
240                    Button {
241                        editor.run(keys: key.keys)
242                    } label: {
243                        if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
244                    }
245                    .accessibilityLabel(key.label)
246                }
247                Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
248            }
249            .labelStyle(.iconOnly)
250            .buttonStyle(.bordered)
251            .padding(.horizontal, 8)
252            .padding(.vertical, 6)
253        }
254        .background(.bar)
255    }
256}
257
258/// A command's question: text with choices, a date, or fast selection by keys.
259struct PromptSheet: View {
260    let prompt: Prompt
261    let answer: (String?) -> Void
262    @State private var text = ""
263    @State private var date = Date()
264    @State private var keys: [FastSelection.Input] = []
265
266    var body: some View {
267        NavigationStack {
268            Form {
269                if let fast = prompt.fast {
270                    fastSection(fast)
271                } else {
272                    Section {
273                        TextField(prompt.message, text: $text)
274                            .autocorrectionDisabled()
275                            .textInputAutocapitalization(.never)
276                            .onSubmit { answer(text) }
277                    } footer: {
278                        if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
279                    }
280                    if prompt.date != nil {
281                        DatePicker("Date", selection: $date, displayedComponents: [.date])
282                            .datePickerStyle(.graphical)
283                            .onChange(of: date) { text = Self.stamp(date) }
284                    }
285                    if !prompt.choices.isEmpty {
286                        let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
287                        Section("Choices") {
288                            ForEach(matching.prefix(50), id: \.self) { choice in
289                                Button(choice) { choose(choice) }
290                            }
291                        }
292                    }
293                }
294            }
295            .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
296            .navigationBarTitleDisplayMode(.inline)
297            .toolbar {
298                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
299                if prompt.fast == nil || prompt.fast?.multiple == true {
300                    ToolbarItem(placement: .confirmationAction) {
301                        Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
302                            .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
303                    }
304                }
305            }
306        }
307        .onAppear {
308            text = prompt.initial
309            if let day = prompt.date?.defaultDate { date = day }
310        }
311    }
312
313    /// With a separator (tags), what's typed after the last one.
314    private var lastPart: String {
315        guard let separator = prompt.completionSeparator else { return text }
316        return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
317    }
318
319    private func choose(_ choice: String) {
320        guard let separator = prompt.completionSeparator else {
321            text = choice
322            if prompt.date == nil { answer(choice) }
323            return
324        }
325        var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
326        if parts.isEmpty { parts = [""] }
327        parts[parts.count - 1] = choice
328        text = parts.joined(separator: String(separator)) + String(separator)
329    }
330
331    @ViewBuilder
332    private func fastSection(_ fast: FastSelection) -> some View {
333        let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
334        Section {
335            ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
336                Button {
337                    if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
338                } label: {
339                    HStack {
340                        Text(option.name).foregroundStyle(.primary)
341                        Spacer()
342                        if current.contains(option.name) { Image(systemName: "checkmark") }
343                        Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
344                    }
345                }
346            }
347            if !fast.multiple {
348                Button("No keyword") { answer(" ") }
349            }
350        } footer: {
351            if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
352        }
353    }
354
355    static func stamp(_ date: Date) -> String {
356        let formatter = DateFormatter()
357        formatter.locale = Locale(identifier: "en_US_POSIX")
358        formatter.dateFormat = "yyyy-MM-dd"
359        return formatter.string(from: date)
360    }
361}
362
363/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
364struct BlockEditSheet: View {
365    let edit: BlockEdit
366    let finish: (String?) -> Void
367    @State private var text = ""
368    @FocusState private var focused: Bool
369
370    var body: some View {
371        NavigationStack {
372            TextEditor(text: $text)
373                .font(.body.monospaced())
374                .autocorrectionDisabled()
375                .textInputAutocapitalization(.never)
376                .focused($focused)
377                .padding(.horizontal, 8)
378                .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
379                .navigationBarTitleDisplayMode(.inline)
380                .toolbar {
381                    ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
382                    ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text) } }
383                }
384        }
385        .onAppear {
386            text = edit.content
387            focused = true
388        }
389    }
390}
391
392/// Every command that applies at the caret, by name.
393struct CommandPalette: View {
394    let editor: MobileEditor
395    /// Called with the chosen command before the palette closes.
396    let choose: (String) -> Void
397    @State private var query = ""
398    @Environment(\.dismiss) private var dismiss
399
400    private static let viewCommands: [(id: String, title: String)] = [
401        ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
402        ("edit.undo", "Undo"), ("edit.redo", "Redo"),
403        ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
404        ("app.clock.goto", "Go to Clocked Entry"),
405    ]
406
407    var body: some View {
408        let context = editor.editContext()
409        let all = Self.viewCommands + Commands.everything.map { ($0.id, $0.title) }
410        let shown = all.filter { editor.applies($0.id, in: context) && (query.isEmpty || $0.title.localizedCaseInsensitiveContains(query)) }
411        NavigationStack {
412            List(shown, id: \.id) { command in
413                Button {
414                    choose(command.id)
415                    dismiss()
416                } label: {
417                    HStack {
418                        Text(command.title).foregroundStyle(.primary)
419                        Spacer()
420                        if let keys = editor.keymap.keyLabels(for: command.id).first {
421                            Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
422                        }
423                    }
424                }
425            }
426            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
427            .navigationTitle("Commands")
428            .navigationBarTitleDisplayMode(.inline)
429            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
430        }
431    }
432}
433#endif