Sources/OrgstarMobile/EditorScreen.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgstarMobile/EditorScreen.swift history · blame · raw

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