Sources/OrgstarMobile/EditorScreen.swift

65a97fc9c9a3370a0d84c11f1152fd3ced3089b2
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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