Sources/OrgstarMobile/EditorScreen.swift

53e00edef707f97e790c6ab760329429b565e714
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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