Sources/OrgstarMobile/EditorScreen.swift

eda8fce281cb165bf8e1bdf1dcdb24ae82947fe0
orgstar/Sources/OrgstarMobile/EditorScreen.swift

575 lines · 25906 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        /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
 37        case refile(String)
 38        case block(BlockEdit)
 39
 40        var id: String {
 41            switch self {
 42            case .palette: "palette"
 43            case .refile(let command): command
 44            case .conflict: "conflict"
 45            case .syncCopies: "syncCopies"
 46            case .recovery: "recovery"
 47            case .block(let edit): "block \(edit.range)"
 48            }
 49        }
 50    }
 51
 52    var body: some View {
 53        Group {
 54            if let editor {
 55                EditorTextView(editor: editor, palette: { sheet = .palette })
 56                    .ignoresSafeArea(.container, edges: .bottom)
 57            } else {
 58                ProgressView()
 59            }
 60        }
 61        .navigationTitle(session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""))
 62        .navigationBarTitleDisplayMode(.inline)
 63        .toolbar(.hidden, for: .tabBar)
 64        .toolbar {
 65            ToolbarItemGroup(placement: .primaryAction) {
 66                if session.conflict != nil {
 67                    Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
 68                }
 69                Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
 70                Menu("More", systemImage: "ellipsis.circle") {
 71                    Button("Commands", systemImage: "command") { sheet = .palette }
 72                    Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
 73                    Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) {
 74                        Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
 75                    }
 76                    RecentClockMenu(clock: clock) { editor?.run($0) }
 77                    if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) { message = $0 } }
 78                    Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
 79                    Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
 80                }
 81            }
 82        }
 83        .safeAreaInset(edge: .top) {
 84            if let message {
 85                Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
 86                    .onTapGesture { self.message = nil }
 87                    .task(id: message) {
 88                        try? await Task.sleep(for: .seconds(4))
 89                        if self.message == message { self.message = nil }
 90                    }
 91            }
 92        }
 93        .sheet(item: $prompt) { request in
 94            PromptSheet(prompt: request.prompt) { answer in
 95                prompt = nil
 96                request.reply(answer)
 97            }
 98        }
 99        .sheet(item: $sheet, onDismiss: {
100            // After the sheet has gone, so a command's own prompt can show.
101            if let id = chosen {
102                chosen = nil
103                editor?.run(id)
104            }
105        }) { sheet in
106            switch sheet {
107            case .palette: if let editor { CommandPalette(editor: editor) { chosen = $0 } }
108            case .conflict: ConflictSheet(session: session)
109            case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
110            case .recovery: RecoverySheet(session: session) { message = $0 }
111            case .refile(let command):
112                RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
113                            create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
114                    self.sheet = nil
115                    switch session.createRefileChild(under: parent, title: child) {
116                    case .success(let target):
117                        guard let path = session.path, let editor else { return }
118                        message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
119                    case .failure(.message(let text)): message = text
120                    }
121                }) { target in
122                    self.sheet = nil
123                    guard let target else { return }
124                    if command == "app.refile.goto" {
125                        model.openRequest = .offset(target.path, target.start ?? Int.max)
126                    } else {
127                        refile(to: target, keep: command == "app.refile.copy")
128                    }
129                }
130            case .block(let edit):
131                BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
132                    self.sheet = nil
133                    if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
134                }
135            }
136        }
137        .onChange(of: session.conflict) { _, conflict in
138            if conflict != nil, session.path == path { sheet = .conflict }
139        }
140        .onChange(of: session.lastError) { _, error in
141            if let error { message = error; session.lastError = nil }
142        }
143        .onAppear(perform: start)
144        .onChange(of: session.revealRequest?.id) {
145            if let offset = session.revealRequest?.offset, session.path == path { editor?.reveal(offset) }
146        }
147        .onChange(of: model.settingsVersion) {
148            editor?.options = session.options
149            editor?.themeSpec = model.theme
150            editor?.keymap = model.keymap
151            editor?.modal = model.modalKeys
152        }
153        .onChange(of: model.showMarkup) { editor?.showMarkup = model.showMarkup }
154        .onDisappear {
155            // Typing the reader shows next, and a save, don't wait for the autosave delay.
156            if session.dirtyPaths.contains(path) { _ = session.save(path) }
157        }
158    }
159
160    /// Store Link, Store ID Link and Insert Link, with the links stored while the app runs.
161    private func link(_ id: String) {
162        guard let editor else { return }
163        switch id {
164        case "org.link.store":
165            message = StoredLink.add(Links.store(in: editor.editContext(), path: Links.abbreviate(path, home: NSHomeDirectory())), to: &model.storedLinks)
166        case "org.id.store-link":
167            if case .commit = editor.perform(CreateID()),
168               let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
169                message = StoredLink.add(link, to: &model.storedLinks)
170            }
171        default:
172            _ = editor.perform(InsertLink(stored: model.storedLinks, file: path))
173        }
174    }
175
176    /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
177    private func run(_ job: BabelJob) {
178        let go = {
179            message = "Running \(job.language) block…"
180            session.startBabel(job) { message = $0 }
181        }
182        if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
183        let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
184        prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
185            switch answer {
186            case "always":
187                trust.trust(path: path, content: job.blockText)
188                go()
189            case "yes": go()
190            default: message = "Not run"
191            }
192        }
193    }
194
195    private func start() {
196        if session.path != path { session.open(path) }
197        if editor == nil, let document = session.document {
198            let editor = MobileEditor(
199                document: document, editable: document.isEditable, options: session.options, theme: model.theme,
200                showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
201            )
202            editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
203            editor.onChange = { [weak session] in session?.bufferChanged(path) }
204            editor.onMessage = { message = $0 }
205            editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
206            editor.onLink = { link in
207                switch session.follow(link, workspace: workspace, isText: { _ in false }) {
208                case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")"
209                case .openExternally(let url): openURL(url)
210                case .message(let text): message = text
211                }
212            }
213            editor.onEditBlock = { edit in sheet = .block(edit) }
214            editor.onTangle = { scope in message = session.tangle(scope) }
215            editor.onBabel = { job in run(job) }
216            editor.onRefreshSetup = { session.refreshSetup() }
217            editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
218            editor.keymap = model.keymap
219            editor.modal = model.modalKeys
220            editor.onAppCommand = { id in
221                if id == "app.save" {
222                    _ = session.save(path)
223                } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
224                    sheet = .refile(id)
225                } else if id == "app.toggle-markup" {
226                    model.showMarkup.toggle()
227                } else if MobileEditor.linkCommands.contains(id) {
228                    link(id)
229                } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
230                    message = "Not available on iOS yet"
231                }
232            }
233            self.editor = editor
234        }
235        if let editor { session.attach(editor) }
236        if let offset { editor?.reveal(offset) }
237        if session.conflict != nil {
238            sheet = .conflict
239        } else if case let copies = session.syncConflictCopies().count, copies > 0 {
240            message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
241        }
242    }
243}
244
245extension EditorScreen {
246    /// `org-refile` of the entry at the caret, to a target worked out again from the files
247    /// now, as the agenda's Refile… does.
248    func refile(to target: RefileTarget, keep: Bool = false) {
249        guard let editor, let path = session.path else { return }
250        let caret = editor.editContext().caret
251        guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
252            message = "Can't find \(target.label) any more."
253            return
254        }
255        message = session.refile(to: current, from: (path, caret), keep: keep)
256    }
257}
258
259/// The editor's text view, with the Org key bar over the keyboard.
260struct EditorTextView: UIViewRepresentable {
261    let editor: MobileEditor
262    let palette: () -> Void
263
264    func makeUIView(context: Context) -> UITextView {
265        let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
266        bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
267        bar.view.backgroundColor = .clear
268        bar.sizingOptions = []
269        editor.textView.inputAccessoryView = bar.view
270        context.coordinator.bar = bar
271        return editor.textView
272    }
273
274    func updateUIView(_ view: UITextView, context: Context) {}
275
276    func makeCoordinator() -> Coordinator { Coordinator() }
277
278    final class Coordinator {
279        var bar: UIViewController?
280    }
281}
282
283/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
284/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
285struct KeyBar: View {
286    let editor: MobileEditor
287    let palette: () -> Void
288
289    private static let keys: [(label: String, symbol: String?, keys: String)] = [
290        ("Fold", "arrow.right.to.line", "TAB"),
291        ("Overview", "arrow.left.to.line", "S-TAB"),
292        ("Promote", "arrow.left", "M-<left>"),
293        ("Demote", "arrow.right", "M-<right>"),
294        ("Move up", "arrow.up", "M-<up>"),
295        ("Move down", "arrow.down", "M-<down>"),
296        ("New heading or item", "plus", "M-RET"),
297        ("TODO", nil, "C-c C-t"),
298        ("Act at point", "checkmark.square", "C-c C-c"),
299        ("Schedule", "calendar", "C-c C-s"),
300        ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
301        ("Tags", "tag", "C-c C-q"),
302        ("Open link", "link", "C-c C-o"),
303    ]
304
305    var body: some View {
306        ScrollView(.horizontal, showsIndicators: false) {
307            HStack(spacing: 4) {
308                Button("Commands", systemImage: "command", action: palette)
309                ForEach(Self.keys, id: \.keys) { key in
310                    Button {
311                        editor.run(keys: key.keys)
312                    } label: {
313                        if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
314                    }
315                    .accessibilityLabel(key.label)
316                }
317                Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
318            }
319            .labelStyle(.iconOnly)
320            .buttonStyle(.bordered)
321            .padding(.horizontal, 8)
322            .padding(.vertical, 6)
323        }
324        .background(.bar)
325    }
326}
327
328/// A command's question: text with choices, a date, or fast selection by keys.
329struct PromptSheet: View {
330    let prompt: Prompt
331    let answer: (String?) -> Void
332    @State private var text = ""
333    @State private var date = Date()
334    @State private var keys: [FastSelection.Input] = []
335
336    var body: some View {
337        NavigationStack {
338            Form {
339                if let fast = prompt.fast {
340                    fastSection(fast)
341                } else {
342                    Section {
343                        TextField(prompt.message, text: $text)
344                            .autocorrectionDisabled()
345                            .textInputAutocapitalization(.never)
346                            .onSubmit { answer(text) }
347                    } footer: {
348                        if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
349                    }
350                    if prompt.date != nil {
351                        DatePicker("Date", selection: $date, displayedComponents: [.date])
352                            .datePickerStyle(.graphical)
353                            .onChange(of: date) { text = Self.stamp(date) }
354                    }
355                    if !prompt.choices.isEmpty {
356                        let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
357                        Section("Choices") {
358                            ForEach(matching.prefix(50), id: \.self) { choice in
359                                Button(choice) { choose(choice) }
360                            }
361                        }
362                    }
363                }
364            }
365            .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
366            .navigationBarTitleDisplayMode(.inline)
367            .toolbar {
368                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
369                if prompt.fast == nil || prompt.fast?.multiple == true {
370                    ToolbarItem(placement: .confirmationAction) {
371                        Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
372                            .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
373                    }
374                }
375            }
376        }
377        .onAppear {
378            text = prompt.initial
379            if let day = prompt.date?.defaultDate { date = day }
380        }
381    }
382
383    /// With a separator (tags), what's typed after the last one.
384    private var lastPart: String {
385        guard let separator = prompt.completionSeparator else { return text }
386        return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
387    }
388
389    private func choose(_ choice: String) {
390        guard let separator = prompt.completionSeparator else {
391            text = choice
392            if prompt.date == nil { answer(choice) }
393            return
394        }
395        var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
396        if parts.isEmpty { parts = [""] }
397        parts[parts.count - 1] = choice
398        text = parts.joined(separator: String(separator)) + String(separator)
399    }
400
401    @ViewBuilder
402    private func fastSection(_ fast: FastSelection) -> some View {
403        let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
404        Section {
405            ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
406                Button {
407                    if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
408                } label: {
409                    HStack {
410                        Text(option.name).foregroundStyle(.primary)
411                        Spacer()
412                        if current.contains(option.name) { Image(systemName: "checkmark") }
413                        Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
414                    }
415                }
416            }
417            if !fast.multiple {
418                Button("No keyword") { answer(" ") }
419            }
420        } footer: {
421            if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
422        }
423    }
424
425    static func stamp(_ date: Date) -> String {
426        let formatter = DateFormatter()
427        formatter.locale = Locale(identifier: "en_US_POSIX")
428        formatter.dateFormat = "yyyy-MM-dd"
429        return formatter.string(from: date)
430    }
431}
432
433/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
434/// A src block's code is highlighted as its language.
435struct BlockEditSheet: View {
436    let edit: BlockEdit
437    let theme: MobileTheme
438    let finish: (String?) -> Void
439    @State private var text: String?
440
441    var body: some View {
442        NavigationStack {
443            Group {
444                if let text {
445                    CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
446                }
447            }
448            .padding(.horizontal, 8)
449            .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
450            .navigationBarTitleDisplayMode(.inline)
451            .toolbar {
452                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
453                ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
454            }
455        }
456        .onAppear { text = edit.content }
457    }
458}
459
460/// A text view for code, restyled with the editor's highlighter after each change.
461struct CodeTextView: UIViewRepresentable {
462    let text: String
463    let language: String?
464    let theme: MobileTheme
465    let changed: (String) -> Void
466
467    func makeUIView(context: Context) -> UITextView {
468        let view = UITextView()
469        view.autocorrectionType = .no
470        view.autocapitalizationType = .none
471        view.smartQuotesType = .no
472        view.smartDashesType = .no
473        view.spellCheckingType = .no
474        view.keyboardDismissMode = .interactive
475        view.backgroundColor = .clear
476        view.text = text
477        view.delegate = context.coordinator
478        context.coordinator.style(view)
479        DispatchQueue.main.async { view.becomeFirstResponder() }
480        return view
481    }
482
483    func updateUIView(_ view: UITextView, context: Context) {
484        context.coordinator.parent = self
485    }
486
487    func makeCoordinator() -> Coordinator { Coordinator(self) }
488
489    @MainActor
490    final class Coordinator: NSObject, UITextViewDelegate {
491        var parent: CodeTextView
492        init(_ parent: CodeTextView) { self.parent = parent }
493
494        func textViewDidChange(_ view: UITextView) {
495            parent.changed(view.text)
496            style(view)
497        }
498
499        /// The theme's font and color, then the language's token colors.
500        func style(_ view: UITextView) {
501            let storage = view.textStorage
502            let whole = NSRange(location: 0, length: storage.length)
503            let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
504            storage.beginEditing()
505            storage.setAttributes(base, range: whole)
506            if let language = parent.language {
507                for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
508                    guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
509                    storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
510                }
511            }
512            storage.endEditing()
513            view.typingAttributes = base
514        }
515    }
516}
517
518/// Every command that applies at the caret, by name.
519struct CommandPalette: View {
520    let editor: MobileEditor
521    /// Called with the chosen command before the palette closes.
522    let choose: (String) -> Void
523    @State private var query = ""
524    @Environment(\.dismiss) private var dismiss
525
526    private static let viewCommands: [(id: String, title: String)] = [
527        ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
528        ("edit.undo", "Undo"), ("edit.redo", "Redo"),
529        ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
530        ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
531        ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
532        ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
533        ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
534        ("app.toggle-markup", "Show or Hide Markup"),
535        ("org.toggle-inline-images", "Show or Hide Inline Images"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"),
536        ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
537        ("org.table.expand", "Expand Table Columns"),
538    ]
539
540    /// The commands that apply at the caret and their keys, worked out once when the palette
541    /// opens rather than on every keystroke in the search field.
542    @State private var applicable: [(id: String, title: String, keys: String?)]?
543
544    var body: some View {
545        let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
546        NavigationStack {
547            List(shown, id: \.id) { command in
548                Button {
549                    choose(command.id)
550                    dismiss()
551                } label: {
552                    HStack {
553                        Text(command.title).foregroundStyle(.primary)
554                        Spacer()
555                        if let keys = command.keys {
556                            Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
557                        }
558                    }
559                }
560            }
561            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
562            .navigationTitle("Commands")
563            .navigationBarTitleDisplayMode(.inline)
564            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
565        }
566        .onAppear {
567            guard applicable == nil else { return }
568            let context = editor.editContext()
569            applicable = (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) })
570                .filter { editor.applies($0.id, in: context) }
571                .map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) }
572        }
573    }
574}
575#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form