Sources/OrgstarMobile/EditorScreen.swift

e0794b27d2449358f323e3af8ad1f3e09f1b39df
orgstar/Sources/OrgstarMobile/EditorScreen.swift

915 lines · 45917 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import OrgDocument
  5import PhotosUI
  6import QuickLook
  7import SwiftUI
  8import UIKit
  9import UniformTypeIdentifiers
 10
 11/// Editing a file: the text with Org's folding and styling, a bar of Org keys over the keyboard,
 12/// and every command in a palette. The editor is the open file's live state, so autosave and
 13/// merging go through the session as on the Mac.
 14struct EditorScreen: View {
 15    let path: String
 16    let offset: Int?
 17    let workspace: WorkspaceModel
 18    let session: DocumentSession
 19    @State private var editor: MobileEditor?
 20    @State private var prompt: PromptRequest?
 21    @State private var message: String?
 22    @State private var sheet: Sheet?
 23    @State private var trust = TrustStore()
 24    /// The command chosen in the palette, run once the palette is gone.
 25    @State private var chosen: String?
 26    @Environment(ClockModel.self) private var clock
 27    @Environment(MobileModel.self) private var model
 28    @Environment(\.openURL) private var openURL
 29
 30    /// The session's options with `buffer-file-name` and the agenda files, for clock tables.
 31    private var editorOptions: EditingOptions {
 32        var options = session.options
 33        options.filePath = path
 34        options.agendaFiles = workspace.agendaFilePaths()
 35        options.timer = TimerModel.shared.timer
 36        return options
 37    }
 38
 39    struct PromptRequest: Identifiable {
 40        let id = UUID()
 41        let prompt: Prompt
 42        let reply: (String?) -> Void
 43    }
 44
 45    /// One sheet at a time: two presenters on this screen interfere.
 46    /// `org-table-import`'s file picker is up.
 47    @State private var importingTable = false
 48    /// The table at the caret, for `org-table-export`'s save dialog.
 49    @State private var exportedTable: TableFile?
 50    /// org-attach's file picker is up, for this method.
 51    @State private var attaching: Attachments.Method?
 52    @State private var attachingPhotos = false
 53    @State private var photos: [PhotosPickerItem] = []
 54    /// A file shown in Quick Look.
 55    @State private var previewed: URL?
 56
 57    enum Sheet: Identifiable {
 58        case palette, conflict, syncCopies, recovery
 59        /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
 60        case refile(String)
 61        case block(BlockEdit)
 62        case columns(ColumnView.View)
 63        case plot(TablePlot.Plot)
 64        case crypt(CryptRequest)
 65        case backlinks
 66
 67        var id: String {
 68            switch self {
 69            case .palette: "palette"
 70            case .refile(let command): command
 71            case .conflict: "conflict"
 72            case .syncCopies: "syncCopies"
 73            case .recovery: "recovery"
 74            case .block(let edit): "block \(edit.range)"
 75            case .columns: "columns"
 76            case .plot: "plot"
 77            case .crypt(let request): request.id.uuidString
 78            case .backlinks: "backlinks"
 79            }
 80        }
 81    }
 82
 83    var body: some View {
 84        Group {
 85            if let editor {
 86                EditorTextView(editor: editor, palette: { sheet = .palette })
 87                    .ignoresSafeArea(.container, edges: .bottom)
 88            } else {
 89                ProgressView()
 90            }
 91        }
 92        .navigationTitle(session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""))
 93        .navigationBarTitleDisplayMode(.inline)
 94        .toolbar(.hidden, for: .tabBar)
 95        .toolbar {
 96            ToolbarItemGroup(placement: .primaryAction) {
 97                if session.conflict != nil {
 98                    Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
 99                }
100                Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
101                Menu("More", systemImage: "ellipsis.circle") {
102                    Button("Commands", systemImage: "command") { sheet = .palette }
103                    Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
104                    Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") }
105                    Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") }
106                    Menu("Table", systemImage: "tablecells") {
107                        Button("Import Table from File…", systemImage: "square.and.arrow.down") { importingTable = true }
108                        Button("Export Table as CSV…", systemImage: "square.and.arrow.up") { exportTable(csv: true) }
109                        Button("Export Table as TSV…", systemImage: "square.and.arrow.up") { exportTable(csv: false) }
110                        Button("Plot Table", systemImage: "chart.xyaxis.line") { plotTable() }
111                    }
112                    Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) {
113                        Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
114                    }
115                    RecentClockMenu(clock: clock) { editor?.run($0) }
116                    Button("Backlinks", systemImage: "arrow.uturn.backward.circle") { sheet = .backlinks }
117                    Menu("Daily Notes", systemImage: "calendar") {
118                        Button("Today", systemImage: "calendar") { roamActions.run("app.dailies.today") }
119                        Button("Yesterday", systemImage: "chevron.backward") { roamActions.run("app.dailies.yesterday") }
120                        Button("Tomorrow", systemImage: "chevron.forward") { roamActions.run("app.dailies.tomorrow") }
121                        Button("Date…", systemImage: "calendar.badge.clock") { roamActions.run("app.dailies.date") }
122                        Button("Capture to Today", systemImage: "square.and.pencil") { roamActions.run("app.dailies.capture-today") }
123                        Button("Previous Daily Note", systemImage: "arrow.left") { roamActions.run("app.dailies.previous") }
124                        Button("Next Daily Note", systemImage: "arrow.right") { roamActions.run("app.dailies.next") }
125                    }
126                    Button("Find Node…", systemImage: "point.3.connected.trianglepath.dotted") { roamActions.run("app.node.find") }
127                    Button("Insert Node Link…", systemImage: "link") { roamActions.run("app.node.insert") }
128                    Menu("Attachments", systemImage: "paperclip") {
129                        Button("Attach File…", systemImage: "doc.badge.plus") { attaching = .cp }
130                        Button("Attach Photo or Video…", systemImage: "photo.badge.plus") { attachingPhotos = true }
131                        Button("Attach File from URL…", systemImage: "link.badge.plus") { attachActions.run("app.attach.url") }
132                        Button("New Attachment…", systemImage: "square.and.pencil") { attachActions.run("app.attach.new") }
133                        Button("Open Attachment…", systemImage: "paperclip") { attachActions.run("app.attach.open") }
134                        Button("Show Attachment Folder", systemImage: "folder") { attachActions.run("app.attach.reveal") }
135                        Button("Delete Attachment…", systemImage: "trash") { attachActions.run("app.attach.delete") }
136                        Button("Delete All Attachments…", systemImage: "trash.slash") { attachActions.run("app.attach.delete-all") }
137                        Button("Sync Attachments", systemImage: "arrow.triangle.2.circlepath") { attachActions.run("app.attach.sync") }
138                        Button("Set Attachment Folder…", systemImage: "folder.badge.gearshape") { attachActions.run("app.attach.set-directory") }
139                        Button("Unset Attachment Folder", systemImage: "folder.badge.minus") { attachActions.run("app.attach.unset-directory") }
140                    }
141                    Menu("Encryption", systemImage: "lock") {
142                        Button("Encrypt Entry…", systemImage: "lock") { crypt("app.crypt.encrypt-entry") }
143                        Button("Decrypt Entry…", systemImage: "lock.open") { crypt("app.crypt.open-entry") }
144                        Button("Decrypt Entry in File…", systemImage: "lock.open.trianglebadge.exclamationmark") { crypt("app.crypt.decrypt-entry") }
145                        Button("Encrypt Tagged Entries…", systemImage: "lock.rectangle.stack") { crypt("app.crypt.encrypt-entries") }
146                        Button("Forget Encryption Passphrase", systemImage: "key.slash") { crypt("app.crypt.forget-passphrase") }
147                    }
148                    if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) { message = $0 } }
149                    Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
150                    Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
151                }
152            }
153        }
154        .safeAreaInset(edge: .top) {
155            VStack(spacing: 0) {
156                if let timer = TimerModel.shared.timer {
157                    TimelineView(.periodic(from: .now, by: 1)) { context in
158                        Text(timer.modeLine(now: context.date)).font(.callout.monospacedDigit())
159                    }
160                    .frame(maxWidth: .infinity).padding(4).background(.bar)
161                }
162                if let message {
163                    Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
164                        .onTapGesture { self.message = nil }
165                        .task(id: message) {
166                            try? await Task.sleep(for: .seconds(4))
167                            if self.message == message { self.message = nil }
168                        }
169                }
170            }
171        }
172        .sheet(item: $prompt) { request in
173            PromptSheet(prompt: request.prompt) { answer in
174                prompt = nil
175                request.reply(answer)
176            }
177        }
178        .sheet(item: $sheet, onDismiss: {
179            // After the sheet has gone, so a command's own prompt can show.
180            if let id = chosen {
181                chosen = nil
182                editor?.run(id)
183            }
184        }) { sheet in
185            switch sheet {
186            case .palette: if let editor { CommandPalette(editor: editor) { chosen = $0 } }
187            case .conflict: ConflictSheet(session: session)
188            case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
189            case .recovery: RecoverySheet(session: session) { message = $0 }
190            case .refile(let command):
191                RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
192                            create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
193                    self.sheet = nil
194                    switch session.createRefileChild(under: parent, title: child) {
195                    case .success(let target):
196                        guard let path = session.path, let editor else { return }
197                        message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
198                    case .failure(.message(let text)): message = text
199                    }
200                }) { target in
201                    self.sheet = nil
202                    guard let target else { return }
203                    if command == "app.refile.goto" {
204                        model.openRequest = .offset(target.path, target.start ?? Int.max)
205                    } else {
206                        refile(to: target, keep: command == "app.refile.copy")
207                    }
208                }
209            case .block(let edit):
210                BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
211                    self.sheet = nil
212                    if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
213                }
214            case .columns(let view):
215                ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
216            case .plot(let plot):
217                PlotScreen(plot: plot)
218            case .crypt(let request):
219                CryptScreen(request: request, session: session, editor: editor) { message = $0 }
220            case .backlinks:
221                BacklinksScreen(workspace: workspace, session: session, path: path, caret: editor?.editContext().caret ?? 0) { location in
222                    if location.path == path { editor?.reveal(location.start) } else { model.openRequest = .heading(location) }
223                }
224            }
225        }
226        .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
227            importTable(result)
228        }
229        .background {
230            // A second importer on the same view would replace the first.
231            Color.clear.fileImporter(isPresented: Binding(get: { attaching != nil }, set: { if !$0 { attaching = nil } }),
232                                     allowedContentTypes: [.item, .folder], allowsMultipleSelection: true) { result in
233                let method = attaching ?? .cp
234                switch result {
235                case .success(let urls): attachActions.attach(urls, method: method)
236                case .failure(let error): message = error.localizedDescription
237                }
238            }
239        }
240        .photosPicker(isPresented: $attachingPhotos, selection: $photos, matching: .any(of: [.images, .videos]))
241        .onChange(of: photos) { _, items in
242            guard !items.isEmpty else { return }
243            photos = []
244            attachPhotos(items)
245        }
246        .quickLookPreview($previewed)
247        .fileExporter(isPresented: Binding(get: { exportedTable != nil }, set: { if !$0 { exportedTable = nil } }),
248                      document: exportedTable, contentType: exportedTable?.type ?? .commaSeparatedText,
249                      defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in
250            if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." }
251        }
252        .onChange(of: session.conflict) { _, conflict in
253            if conflict != nil, session.path == path { sheet = .conflict }
254        }
255        .onChange(of: session.lastError) { _, error in
256            if let error { message = error; session.lastError = nil }
257        }
258        .onAppear(perform: start)
259        .onChange(of: session.revealRequest?.id) {
260            if let offset = session.revealRequest?.offset, session.path == path { editor?.reveal(offset) }
261        }
262        .onChange(of: model.settingsVersion) {
263            editor?.options = editorOptions
264            editor?.themeSpec = model.theme
265            editor?.keymap = model.keymap
266            editor?.modal = model.modalKeys
267        }
268        .onChange(of: model.showMarkup) { editor?.showMarkup = model.showMarkup }
269        .onChange(of: TimerModel.shared.timer) { editor?.options = editorOptions }
270        .onDisappear {
271            // Typing the reader shows next, and a save, don't wait for the autosave delay.
272            if session.dirtyPaths.contains(path) { _ = session.save(path) }
273        }
274    }
275
276    /// Store Link, Store ID Link and Insert Link, with the links stored while the app runs.
277    private func link(_ id: String) {
278        guard let editor else { return }
279        switch id {
280        case "org.link.store":
281            message = StoredLink.add(Links.store(in: editor.editContext(), path: Links.abbreviate(path, home: NSHomeDirectory())), to: &model.storedLinks)
282        case "org.id.store-link":
283            if case .commit = editor.perform(CreateID()),
284               let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
285                message = StoredLink.add(link, to: &model.storedLinks)
286            }
287        default:
288            _ = editor.perform(InsertLink(stored: model.storedLinks, file: path))
289        }
290    }
291
292    /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
293    private func run(_ job: BabelJob) {
294        let go = {
295            message = "Running \(job.language) block…"
296            session.startBabel(job) { message = $0 }
297        }
298        if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
299        let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
300        prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
301            switch answer {
302            case "always":
303                trust.trust(path: path, content: job.blockText)
304                go()
305            case "yes": go()
306            default: message = "Not run"
307            }
308        }
309    }
310
311    private func start() {
312        if session.path != path { session.open(path) }
313        if editor == nil, let document = session.document {
314            let editor = MobileEditor(
315                document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
316                showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
317            )
318            editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
319            editor.onChange = { [weak session] in session?.bufferChanged(path) }
320            editor.onMessage = { message = $0 }
321            editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
322            editor.onLink = { link in follow(link) }
323            editor.onEditBlock = { edit in sheet = .block(edit) }
324            editor.onColumnView = { view in sheet = .columns(view) }
325            editor.onTangle = { scope in message = session.tangle(scope) }
326            editor.onBabel = { job in run(job) }
327            editor.onRefreshSetup = { session.refreshSetup() }
328            editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
329            editor.keymap = model.keymap
330            editor.modal = model.modalKeys
331            editor.onAppCommand = { id in
332                if id == "app.save" {
333                    _ = session.save(path)
334                } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
335                    sheet = .refile(id)
336                } else if id == "app.table-import" {
337                    importingTable = true
338                } else if id == "app.table-export" {
339                    exportTable(csv: true)
340                } else if id == "app.plot" {
341                    plotTable()
342                } else if id.hasPrefix("app.crypt.") {
343                    crypt(id)
344                } else if id.hasPrefix("app.attach.") {
345                    attachActions.run(id)
346                } else if id.hasPrefix("app.dailies.") || id.hasPrefix("app.node.") {
347                    roamActions.run(id)
348                } else if id == "app.backlinks" {
349                    sheet = .backlinks
350                } else if id == "app.toggle-markup" {
351                    model.showMarkup.toggle()
352                } else if MobileEditor.linkCommands.contains(id) {
353                    link(id)
354                } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
355                    message = "Not available on iOS yet"
356                }
357            }
358            self.editor = editor
359        }
360        if let editor { session.attach(editor) }
361        if let offset { editor?.reveal(offset) }
362        if session.conflict != nil {
363            sheet = .conflict
364        } else if case let copies = session.syncConflictCopies().count, copies > 0 {
365            message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
366        }
367    }
368}
369
370extension EditorScreen {
371    /// Follows a link; files the editor doesn't open show in Quick Look.
372    private func follow(_ link: OrgLink) {
373        switch session.follow(link, workspace: workspace, isText: { _ in false }) {
374        case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")"
375        case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
376        case .message(let text): message = text
377        }
378    }
379
380    /// org-roam's daily notes and nodes.
381    private var roamActions: RoamActions {
382        RoamActions(
383            session: session, roots: { workspace.rootPaths },
384            nodes: { workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
385            show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
386            open: { file, offset in
387                if file == path { editor?.reveal(offset) } else { model.openRequest = .offset(file, offset) }
388            },
389            insertLink: { link, title in
390                guard let editor else { return }
391                let context = editor.editContext()
392                let range = context.selection.first ?? context.caret..<context.caret
393                let selected = (context.text as NSString).substring(with: NSRange(range))
394                let text = Links.makeString(link, selected.isEmpty ? title : selected)
395                let end = range.lowerBound + (text as NSString).length
396                _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
397            },
398            refresh: { Task { await workspace.refresh() } })
399    }
400
401    /// org-attach's commands for the entry at the caret.
402    private var attachActions: AttachActions {
403        AttachActions(
404            entry: {
405                guard let editor else { return nil }
406                let context = editor.editContext()
407                return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
408            },
409            apply: { new in
410                guard let editor else { return }
411                let context = editor.editContext()
412                let caret = min(context.caret, (new as NSString).length)
413                _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
414            },
415            show: { message = $0 },
416            ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
417            storeLink: { _ = StoredLink.add($0, to: &model.storedLinks) },
418            open: { follow(OrgLink(type: "file", path: $0, raw: "file:" + $0)) },
419            reveal: { dir in
420                if let url = URL(string: "shareddocuments://" + (dir.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? dir)) { openURL(url) }
421            },
422            pick: { attaching = $0 })
423    }
424
425    /// Photos and videos attached under the names Photos gives them.
426    private func attachPhotos(_ items: [PhotosPickerItem]) {
427        Task { @MainActor in
428            var urls: [URL] = []
429            for item in items {
430                if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
431            }
432            if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
433            if !urls.isEmpty { attachActions.attach(urls, method: .mv) }
434        }
435    }
436
437    /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
438    private func importTable(_ result: Result<URL, Error>) {
439        guard case .success(let url) = result, let editor else { return }
440        let scoped = url.startAccessingSecurityScopedResource()
441        defer { if scoped { url.stopAccessingSecurityScopedResource() } }
442        guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
443        _ = editor.perform(ImportTable(contents: contents))
444    }
445
446    /// org-crypt's commands at the caret, through the passphrase sheet.
447    private func crypt(_ id: String) {
448        guard let editor else { return }
449        let context = editor.editContext()
450        switch id {
451        case "app.crypt.forget-passphrase":
452            CryptPassphrases.forget(path)
453            message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
454        case "app.crypt.encrypt-entries":
455            sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
456        default:
457            guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
458            let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
459            if id == "app.crypt.encrypt-entry" {
460                guard !encrypted else { return message = "The entry is encrypted already" }
461                sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
462            } else {
463                guard encrypted else { return message = "Not an encrypted entry" }
464                sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
465            }
466        }
467    }
468
469    /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
470    /// one, else shown.
471    private func plotTable() {
472        guard let editor else { return }
473        let context = editor.editContext()
474        do {
475            let plot = try TablePlot.plot(context.text, at: context.caret)
476            if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
477                try PlotOutput.write(plot, to: url)
478                message = "Plot written to \(url.lastPathComponent)"
479                if editor.showsImages { editor.restyleAll() }
480            } else {
481                sheet = .plot(plot)
482            }
483        } catch {
484            message = "\(error)"
485        }
486    }
487
488    /// `org-table-export` of the table at the caret, as CSV or TSV.
489    private func exportTable(csv: Bool) {
490        guard let editor else { return }
491        let context = editor.editContext()
492        guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
493            return message = "No table at point"
494        }
495        exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
496    }
497
498    /// `org-refile` of the entry at the caret, to a target worked out again from the files
499    /// now, as the agenda's Refile… does.
500    func refile(to target: RefileTarget, keep: Bool = false) {
501        guard let editor, let path = session.path else { return }
502        let caret = editor.editContext().caret
503        guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
504            message = "Can't find \(target.label) any more."
505            return
506        }
507        message = session.refile(to: current, from: (path, caret), keep: keep)
508    }
509}
510
511/// The editor's text view, with the Org key bar over the keyboard.
512struct EditorTextView: UIViewRepresentable {
513    let editor: MobileEditor
514    let palette: () -> Void
515
516    func makeUIView(context: Context) -> UITextView {
517        let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
518        bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
519        bar.view.backgroundColor = .clear
520        bar.sizingOptions = []
521        editor.textView.inputAccessoryView = bar.view
522        context.coordinator.bar = bar
523        return editor.textView
524    }
525
526    func updateUIView(_ view: UITextView, context: Context) {}
527
528    func makeCoordinator() -> Coordinator { Coordinator() }
529
530    final class Coordinator {
531        var bar: UIViewController?
532    }
533}
534
535/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
536/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
537struct KeyBar: View {
538    let editor: MobileEditor
539    let palette: () -> Void
540
541    private static let keys: [(label: String, symbol: String?, keys: String)] = [
542        ("Fold", "arrow.right.to.line", "TAB"),
543        ("Overview", "arrow.left.to.line", "S-TAB"),
544        ("Promote", "arrow.left", "M-<left>"),
545        ("Demote", "arrow.right", "M-<right>"),
546        ("Move up", "arrow.up", "M-<up>"),
547        ("Move down", "arrow.down", "M-<down>"),
548        ("New heading or item", "plus", "M-RET"),
549        ("TODO", nil, "C-c C-t"),
550        ("Act at point", "checkmark.square", "C-c C-c"),
551        ("Schedule", "calendar", "C-c C-s"),
552        ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
553        ("Tags", "tag", "C-c C-q"),
554        ("Open link", "link", "C-c C-o"),
555    ]
556
557    var body: some View {
558        ScrollView(.horizontal, showsIndicators: false) {
559            HStack(spacing: 4) {
560                Button("Commands", systemImage: "command", action: palette)
561                ForEach(Self.keys, id: \.keys) { key in
562                    Button {
563                        editor.run(keys: key.keys)
564                    } label: {
565                        if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
566                    }
567                    .accessibilityLabel(key.label)
568                }
569                Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
570            }
571            .labelStyle(.iconOnly)
572            .buttonStyle(.bordered)
573            .padding(.horizontal, 8)
574            .padding(.vertical, 6)
575        }
576        .background(.bar)
577    }
578}
579
580/// A command's question: text with choices, a date, or fast selection by keys.
581struct PromptSheet: View {
582    let prompt: Prompt
583    let answer: (String?) -> Void
584    @State private var text = ""
585    @State private var date = Date()
586    @State private var keys: [FastSelection.Input] = []
587
588    var body: some View {
589        NavigationStack {
590            Form {
591                if let fast = prompt.fast {
592                    fastSection(fast)
593                } else {
594                    Section {
595                        TextField(prompt.message, text: $text)
596                            .autocorrectionDisabled()
597                            .textInputAutocapitalization(.never)
598                            .onSubmit { answer(text) }
599                    } footer: {
600                        if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
601                    }
602                    if prompt.date != nil {
603                        DatePicker("Date", selection: $date, displayedComponents: [.date])
604                            .datePickerStyle(.graphical)
605                            .onChange(of: date) { text = Self.stamp(date) }
606                    }
607                    if !prompt.choices.isEmpty {
608                        let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
609                        Section("Choices") {
610                            ForEach(matching.prefix(50), id: \.self) { choice in
611                                Button(choice) { choose(choice) }
612                            }
613                        }
614                    }
615                }
616            }
617            .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
618            .navigationBarTitleDisplayMode(.inline)
619            .toolbar {
620                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
621                if prompt.fast == nil || prompt.fast?.multiple == true {
622                    ToolbarItem(placement: .confirmationAction) {
623                        Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
624                            .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
625                    }
626                }
627            }
628        }
629        .onAppear {
630            text = prompt.initial
631            if let day = prompt.date?.defaultDate { date = day }
632        }
633    }
634
635    /// With a separator (tags), what's typed after the last one.
636    private var lastPart: String {
637        guard let separator = prompt.completionSeparator else { return text }
638        return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
639    }
640
641    private func choose(_ choice: String) {
642        guard let separator = prompt.completionSeparator else {
643            text = choice
644            if prompt.date == nil { answer(choice) }
645            return
646        }
647        var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
648        if parts.isEmpty { parts = [""] }
649        parts[parts.count - 1] = choice
650        text = parts.joined(separator: String(separator)) + String(separator)
651    }
652
653    @ViewBuilder
654    private func fastSection(_ fast: FastSelection) -> some View {
655        let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
656        Section {
657            ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
658                Button {
659                    if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
660                } label: {
661                    HStack {
662                        Text(option.name).foregroundStyle(.primary)
663                        Spacer()
664                        if current.contains(option.name) { Image(systemName: "checkmark") }
665                        Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
666                    }
667                }
668            }
669            if !fast.multiple {
670                Button("No keyword") { answer(" ") }
671            }
672        } footer: {
673            if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
674        }
675    }
676
677    static func stamp(_ date: Date) -> String {
678        let formatter = DateFormatter()
679        formatter.locale = Locale(identifier: "en_US_POSIX")
680        formatter.dateFormat = "yyyy-MM-dd"
681        return formatter.string(from: date)
682    }
683}
684
685/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
686/// A src block's code is highlighted as its language.
687struct BlockEditSheet: View {
688    let edit: BlockEdit
689    let theme: MobileTheme
690    let finish: (String?) -> Void
691    @State private var text: String?
692
693    var body: some View {
694        NavigationStack {
695            Group {
696                if let text {
697                    CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
698                }
699            }
700            .padding(.horizontal, 8)
701            .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
702            .navigationBarTitleDisplayMode(.inline)
703            .toolbar {
704                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
705                ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
706            }
707        }
708        .onAppear { text = edit.content }
709    }
710}
711
712/// A text view for code, restyled with the editor's highlighter after each change.
713struct CodeTextView: UIViewRepresentable {
714    let text: String
715    let language: String?
716    let theme: MobileTheme
717    let changed: (String) -> Void
718
719    func makeUIView(context: Context) -> UITextView {
720        let view = UITextView()
721        view.autocorrectionType = .no
722        view.autocapitalizationType = .none
723        view.smartQuotesType = .no
724        view.smartDashesType = .no
725        view.spellCheckingType = .no
726        view.keyboardDismissMode = .interactive
727        view.backgroundColor = .clear
728        view.text = text
729        view.delegate = context.coordinator
730        context.coordinator.style(view)
731        DispatchQueue.main.async { view.becomeFirstResponder() }
732        return view
733    }
734
735    func updateUIView(_ view: UITextView, context: Context) {
736        context.coordinator.parent = self
737    }
738
739    func makeCoordinator() -> Coordinator { Coordinator(self) }
740
741    @MainActor
742    final class Coordinator: NSObject, UITextViewDelegate {
743        var parent: CodeTextView
744        init(_ parent: CodeTextView) { self.parent = parent }
745
746        func textViewDidChange(_ view: UITextView) {
747            parent.changed(view.text)
748            style(view)
749        }
750
751        /// The theme's font and color, then the language's token colors.
752        func style(_ view: UITextView) {
753            let storage = view.textStorage
754            let whole = NSRange(location: 0, length: storage.length)
755            let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
756            storage.beginEditing()
757            storage.setAttributes(base, range: whole)
758            if let language = parent.language {
759                for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
760                    guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
761                    storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
762                }
763            }
764            storage.endEditing()
765            view.typingAttributes = base
766        }
767    }
768}
769
770/// Every command that applies at the caret, by name.
771struct CommandPalette: View {
772    let editor: MobileEditor
773    /// Called with the chosen command before the palette closes.
774    let choose: (String) -> Void
775    @State private var query = ""
776    @Environment(\.dismiss) private var dismiss
777
778    private static let viewCommands: [(id: String, title: String)] = [
779        ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
780        ("edit.undo", "Undo"), ("edit.redo", "Redo"),
781        ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
782        ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
783        ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
784        ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
785        ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
786        ("app.toggle-markup", "Show or Hide Markup"),
787        ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"),
788        ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
789        ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
790        ("org.table.expand", "Expand Table Columns"),
791        ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
792        ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
793        ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
794        ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"),
795        ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
796        ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
797        ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
798        ("app.dailies.capture-tomorrow", "Capture to Tomorrow's Daily Note"), ("app.dailies.capture-date", "Capture to Daily Note for Date…"),
799        ("app.dailies.next", "Next Daily Note"), ("app.dailies.previous", "Previous Daily Note"),
800        ("app.attach.attach", "Attach File…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
801        ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
802        ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
803        ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
804    ]
805
806    /// The commands that apply at the caret and their keys, worked out once when the palette
807    /// opens rather than on every keystroke in the search field.
808    @State private var applicable: [(id: String, title: String, keys: String?)]?
809
810    var body: some View {
811        let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
812        NavigationStack {
813            List(shown, id: \.id) { command in
814                Button {
815                    choose(command.id)
816                    dismiss()
817                } label: {
818                    HStack {
819                        Text(command.title).foregroundStyle(.primary)
820                        Spacer()
821                        if let keys = command.keys {
822                            Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
823                        }
824                    }
825                }
826            }
827            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
828            .navigationTitle("Commands")
829            .navigationBarTitleDisplayMode(.inline)
830            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
831        }
832        .onAppear {
833            guard applicable == nil else { return }
834            let context = editor.editContext()
835            applicable = (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) })
836                .filter { editor.applies($0.id, in: context) }
837                .map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) }
838        }
839    }
840}
841/// A table as CSV or TSV, for the save dialog.
842struct TableFile: FileDocument {
843    static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
844    let text: String
845    let type: UTType
846
847    init(text: String, type: UTType) {
848        self.text = text
849        self.type = type
850    }
851
852    init(configuration: ReadConfiguration) throws {
853        text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
854        type = configuration.contentType
855    }
856
857    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
858        FileWrapper(regularFileWithContents: Data(text.utf8))
859    }
860}
861/// A plotted table, as the Mac's plot sheet shows it.
862struct PlotScreen: View {
863    let plot: TablePlot.Plot
864    @Environment(\.dismiss) private var dismiss
865
866    var body: some View {
867        NavigationStack {
868            PlotChart(plot)
869                .navigationTitle("Plot")
870                .navigationBarTitleDisplayMode(.inline)
871                .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
872        }
873    }
874}
875/// A file from the photo picker, copied out of the picker's temporary place with its name.
876struct PickedFile: Transferable {
877    let url: URL
878
879    static var transferRepresentation: some TransferRepresentation {
880        FileRepresentation(importedContentType: .item) { received in
881            let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
882            try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
883            let url = folder.appendingPathComponent(received.file.lastPathComponent)
884            try FileManager.default.copyItem(at: received.file, to: url)
885            return PickedFile(url: url)
886        }
887    }
888}
889
890/// The passphrase sheet for org-crypt, its new text applied in the editor.
891struct CryptScreen: View {
892    let request: CryptRequest
893    let session: DocumentSession
894    let editor: MobileEditor?
895    let report: (String) -> Void
896    @Environment(\.dismiss) private var dismiss
897
898    var body: some View {
899        NavigationStack {
900            CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
901                dismiss()
902                if let message { report(message) }
903            }
904            .navigationBarTitleDisplayMode(.inline)
905        }
906    }
907
908    private func apply(_ new: String) {
909        guard let editor else { return }
910        let context = editor.editContext()
911        let caret = min(context.caret, (new as NSString).length)
912        _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
913    }
914}
915#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