Sources/OrgstarMobile/EditorScreen.swift

1569d791fbc3c0618d100bc101222d3bfc5f56d9
orgstar/Sources/OrgstarMobile/EditorScreen.swift history · blame · raw

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