Sources/OrgstarMobile/EditorScreen.swift

e159ec59dfbacc1644db740591e310c4c1663fed
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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