Sources/OrgstarMobile/EditorScreen.swift
1292 lines · 65689 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; returns why one did nothing.
27 var onPaneCommand: ((String) -> String?)? = 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 /// The file's sync conflict copies and recovery versions, for their toolbar buttons.
40 @State private var syncCopies = 0
41 @State private var recoveries = 0
42 @Environment(MobileModel.self) private var model
43 @Environment(\.openURL) private var openURL
44
45 /// The session's options with `buffer-file-name` and the agenda files, for clock tables.
46 private var editorOptions: EditingOptions {
47 var options = session.options
48 options.filePath = path
49 options.agendaFiles = workspace.agendaFilePaths()
50 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
51 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
52 options.timer = TimerModel.shared.timer
53 return options
54 }
55
56 struct PromptRequest: Identifiable {
57 let id = UUID()
58 let prompt: Prompt
59 let reply: (String?) -> Void
60 }
61
62 /// One sheet at a time: two presenters on this screen interfere.
63 /// `org-table-import`'s file picker is up.
64 @State private var importingTable = false
65 /// The table at the caret, for `org-table-export`'s save dialog.
66 @State private var exportedTable: TableFile?
67 /// org-attach's file picker is up, for this method.
68 @State private var attaching: Attachments.Method?
69 @State private var attachingPhotos = false
70 @State private var takingPhoto = false
71 @State private var scanning = false
72 @State private var photos: [PhotosPickerItem] = []
73 /// A file shown in Quick Look.
74 @State private var previewed: URL?
75 /// The project whose publishing folder the folder picker is choosing.
76 @State private var publishFolder: PublishFolderRequest?
77 @State private var choosingPublishFolder = false
78
79 struct PublishFolderRequest {
80 let project: String
81 /// Publishes again, with the folder.
82 let then: () -> Void
83 }
84
85 enum Sheet: Identifiable {
86 case palette, conflict, syncCopies, recovery, export
87 /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
88 case refile(String)
89 case block(BlockEdit)
90 case columns(ColumnView.View)
91 case plot(TablePlot.Plot)
92 case crypt(CryptRequest)
93 case backlinks
94 case graph
95 /// Rename Tag or Rename TODO Keyword, starting from this name.
96 case rename(ReplaceKind, String)
97 case lint
98 /// The subtree at this offset, to export.
99 case exportSubtree(Int)
100
101 var id: String {
102 switch self {
103 case .palette: "palette"
104 case .refile(let command): command
105 case .conflict: "conflict"
106 case .syncCopies: "syncCopies"
107 case .recovery: "recovery"
108 case .export: "export"
109 case .block(let edit): "block \(edit.range)"
110 case .columns: "columns"
111 case .plot: "plot"
112 case .crypt(let request): request.id.uuidString
113 case .backlinks: "backlinks"
114 case .graph: "graph"
115 case .rename(let kind, _): kind.rawValue
116 case .lint: "lint"
117 case .exportSubtree: "exportSubtree"
118 }
119 }
120 }
121
122 private var pane: EditorPane? { givenPane ?? holder.pane }
123
124 /// Export Subtree…, which shows the export formats for the subtree at the caret.
125 static let exportSubtreeCommand = "app.export-subtree-dialog"
126
127 /// The pane commands, as the Mac's View menu has them.
128 static let paneCommands = ["app.split-right", "app.split-below", "app.pane-next", "app.pane-close", "app.pane-only"]
129
130 var body: some View {
131 Group {
132 if let editor, let textView {
133 EditorTextView(editor: editor, view: textView, palette: { sheet = .palette })
134 .ignoresSafeArea(.container, edges: .bottom)
135 } else {
136 ProgressView()
137 }
138 }
139 .modifier(EditorTitle(title: session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""), shown: !inSplit))
140 .toolbar(.hidden, for: .tabBar)
141 .toolbar {
142 if !inSplit || isFocused {
143 ToolbarItemGroup(placement: .primaryAction) {
144 if pane?.conflict != nil {
145 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
146 }
147 if syncCopies > 0 {
148 Button("Resolve Sync Conflicts…", systemImage: "doc.on.doc") { sheet = .syncCopies }
149 }
150 // On iPhone, in Commands, so the file name has room at the largest text sizes.
151 if recoveries > 0, sizeClass == .regular {
152 Button("Recovery Versions…", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
153 }
154 Button("Find", systemImage: "magnifyingglass") {
155 textView?.interactions.lazy.compactMap { $0 as? UIFindInteraction }.first?.presentFindNavigator(showingReplace: false)
156 }
157 // Redo on a long press, as the system's back buttons offer history.
158 Menu {
159 Button("Redo", systemImage: "arrow.uturn.forward") { editor?.run("edit.redo") }
160 } label: {
161 Label("Undo", systemImage: "arrow.uturn.backward")
162 } primaryAction: {
163 editor?.run("edit.undo")
164 }
165 // On iPhone, Export is in Commands, so the file name has room.
166 if sizeClass == .regular, let tree = session.document(of: path)?.tree {
167 ExportMenu(path: path, tree: tree, report: { message = $0 }, exportSubtree: exportSubtree)
168 }
169 Button("Commands", systemImage: "command") { sheet = .palette }
170 }
171 }
172 }
173 .safeAreaInset(edge: .top) {
174 VStack(spacing: 0) {
175 if let timer = TimerModel.shared.timer {
176 TimelineView(.periodic(from: .now, by: 1)) { context in
177 Text(timer.modeLine(now: context.date)).font(.callout.monospacedDigit())
178 }
179 .frame(maxWidth: .infinity).padding(4).background(.bar)
180 }
181 }
182 }
183 .message($message, edge: .top)
184 .sheet(item: $prompt) { request in
185 PromptSheet(prompt: request.prompt) { answer in
186 prompt = nil
187 request.reply(answer)
188 }
189 }
190 .sheet(item: $sheet, onDismiss: {
191 countVersions()
192 // After the sheet has gone, so a command's own prompt can show.
193 if let id = chosen {
194 chosen = nil
195 editor?.run(id)
196 }
197 }) { sheet in
198 switch sheet {
199 case .palette: if let editor { CommandPalette(editor: editor, panes: onPaneCommand != nil && sizeClass == .regular, split: inSplit,
200 recoveries: recoveries, syncCopies: syncCopies) { chosen = $0 } }
201 case .conflict: ConflictSheet(session: session)
202 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
203 case .recovery: RecoverySheet(session: session) { message = $0 }
204 case .refile(let command):
205 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
206 create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
207 self.sheet = nil
208 switch session.createRefileChild(under: parent, title: child) {
209 case .success(let target):
210 guard let path = session.path, let editor else { return }
211 message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
212 case .failure(.message(let text)): message = text
213 }
214 }) { target in
215 self.sheet = nil
216 guard let target else { return }
217 if command == "app.refile.goto" {
218 model.openRequest = .offset(target.path, target.start ?? Int.max)
219 } else {
220 refile(to: target, keep: command == "app.refile.copy")
221 }
222 }
223 case .block(let edit):
224 BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
225 self.sheet = nil
226 if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
227 }
228 case .columns(let view):
229 ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
230 case .plot(let plot):
231 PlotScreen(plot: plot)
232 case .crypt(let request):
233 CryptScreen(request: request, session: session, editor: editor) { message = $0 }
234 case .export:
235 if let tree = session.document(of: path)?.tree { ExportScreen(path: path, tree: tree) { message = $0 } }
236 case .exportSubtree(let caret):
237 if let tree = session.document(of: path)?.tree { SubtreeExportScreen(path: path, tree: tree, caret: caret) }
238 case .backlinks:
239 BacklinksScreen(workspace: workspace, session: session, path: path, caret: editor?.editContext().caret ?? 0) { location in
240 if location.path == path { editor?.reveal(location.start) } else { model.openRequest = .heading(location) }
241 }
242 case .graph:
243 RoamGraphScreen(workspace: workspace, session: session, path: path, caret: editor?.editContext().caret ?? 0) { location in
244 if location.path == path { editor?.reveal(location.start) } else { model.openRequest = .heading(location) }
245 }
246 case .rename(let kind, let initial):
247 RenameScreen(kind: kind, workspace: workspace, session: session, initial: initial) { message = $0 }
248 case .lint:
249 LintScreen(workspace: workspace, session: session, path: path) { offset in editor?.reveal(offset) }
250 }
251 }
252 .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
253 importTable(result)
254 }
255 .background {
256 // A second importer on the same view would replace the first.
257 Color.clear.fileImporter(isPresented: Binding(get: { attaching != nil }, set: { if !$0 { attaching = nil } }),
258 allowedContentTypes: [.item, .folder], allowsMultipleSelection: true) { result in
259 let method = attaching ?? .cp
260 switch result {
261 case .success(let urls): attachActions.attach(urls, method: method)
262 case .failure(let error): message = error.localizedDescription
263 }
264 }
265 }
266 .background {
267 Color.clear.fileImporter(isPresented: $choosingPublishFolder, allowedContentTypes: [.folder]) { result in
268 guard let request = publishFolder else { return }
269 publishFolder = nil
270 switch result {
271 case .success(let url):
272 if !PublishFolders.shared.set(url, for: request.project) { message = "orgstar can use \(url.lastPathComponent) only until it quits" }
273 request.then()
274 case .failure(let error): message = error.localizedDescription
275 }
276 }
277 }
278 .photosPicker(isPresented: $attachingPhotos, selection: $photos, matching: .any(of: [.images, .videos]))
279 .fullScreenCover(isPresented: $takingPhoto) {
280 CameraPicker { data in
281 takingPhoto = false
282 if let data { attachActions.yankImage(data, ext: "jpg", prefix: "photo") }
283 }
284 .ignoresSafeArea()
285 }
286 .fullScreenCover(isPresented: $scanning) {
287 DocumentScanner { data in
288 scanning = false
289 if let data { attachActions.yankImage(data, ext: "pdf", prefix: "scan") }
290 }
291 .ignoresSafeArea()
292 }
293 .onChange(of: photos) { _, items in
294 guard !items.isEmpty else { return }
295 photos = []
296 attachPhotos(items)
297 }
298 .quickLookPreview($previewed)
299 .fileExporter(isPresented: Binding(get: { exportedTable != nil }, set: { if !$0 { exportedTable = nil } }),
300 document: exportedTable, contentType: exportedTable?.type ?? .commaSeparatedText,
301 defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in
302 if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." }
303 }
304 .onChange(of: pane?.conflict) { _, conflict in
305 countVersions()
306 if conflict != nil, isFocused { sheet = .conflict }
307 }
308 .onChange(of: session.lastError) { _, error in
309 guard let error else { return }
310 // The title says what failed.
311 message = session.lastErrorTitle.map { "\($0)\n\(error)" } ?? error
312 session.lastError = nil
313 }
314 .onReceive(NotificationCenter.default.publisher(for: OrgExport.refused)) { message = $0.object as? String }
315 .onAppear(perform: start)
316 // A pane command moved focus here.
317 .onChange(of: isFocused) {
318 countVersions()
319 if isFocused { model.handoffPath = path }
320 guard isFocused, let textView, !textView.isFirstResponder else { return }
321 editor?.focus(textView)
322 textView.becomeFirstResponder()
323 }
324 .onChange(of: pane?.revealRequest?.id) {
325 if let offset = pane?.revealRequest?.offset, pane?.path == path { editor?.reveal(offset) }
326 }
327 .onChange(of: model.settingsVersion) {
328 editor?.options = editorOptions
329 editor?.themeSpec = model.theme
330 editor?.keymap = model.keymap
331 editor?.modal = model.modalKeys
332 }
333 .onChange(of: model.showMarkup) { editor?.showMarkup = model.showMarkup }
334 .onChange(of: TimerModel.shared.timer) { editor?.options = editorOptions }
335 .onDisappear {
336 // Typing the reader shows next, and a save, don't wait for the autosave delay.
337 if session.dirtyPaths.contains(path) { _ = session.save(path) }
338 if model.handoffPath == path { model.handoffPath = nil }
339 }
340 }
341
342 /// Store Link, Store ID Link and Insert Link, with the links stored while the app runs.
343 private func link(_ id: String) {
344 guard let editor else { return }
345 switch id {
346 case "org.link.store":
347 let context = editor.editContext()
348 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
349 message = StoredLink.add(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)), to: &model.storedLinks)
350 case "org.id.store-link":
351 if case .commit = editor.perform(CreateID()),
352 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
353 message = StoredLink.add(link, to: &model.storedLinks)
354 }
355 default:
356 _ = editor.perform(InsertLink(stored: model.storedLinks, file: path))
357 }
358 }
359
360 /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
361 private func run(_ job: BabelJob) {
362 let go = {
363 message = "Running \(job.language) block…"
364 session.startBabel(job) { message = $0 }
365 }
366 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
367 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
368 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
369 switch answer {
370 case "always":
371 trust.trust(path: path, content: job.blockText)
372 go()
373 case "yes": go()
374 default: message = "Not run"
375 }
376 }
377 }
378
379 private func start() {
380 let pane: EditorPane
381 if let existing = self.pane {
382 pane = existing
383 } else {
384 pane = session.makePane()
385 holder.pane = pane
386 let store = model.editors, path = path
387 holder.release = { [weak session] in
388 store.release(pane.id, path: path)
389 session?.closePane(pane)
390 }
391 }
392 if pane.path != path { session.open(path, in: pane) }
393 model.editors.prune(session)
394 guard let editor = model.editors.editor(for: path, session: session, make: makeEditor) else { return }
395 let view = model.editors.view(for: pane.id, of: editor)
396 editor.onFocus[ObjectIdentifier(view)] = { [weak session] in
397 session?.focused = pane
398 bind(editor)
399 onFocus()
400 }
401 // A pane a split adds leaves focus where it was, as `split-window` does.
402 if isFocused {
403 session.focused = pane
404 bind(editor)
405 editor.focus(view)
406 model.handoffPath = path
407 }
408 // A kept editor missed settings changed while it was off screen.
409 editor.options = editorOptions
410 self.editor = editor
411 textView = view
412 if let offset { editor.reveal(offset) }
413 if let template = SnippetLibrary.shared.takeTemplate(for: path) { DispatchQueue.main.async { _ = editor.perform(ExpandNamedSnippet(snippet: template)) } }
414 countVersions()
415 if pane.conflict != nil {
416 sheet = .conflict
417 } else if syncCopies > 0 {
418 message = String(localized: "\(syncCopies) sync conflict copies of this file; Resolve Sync Conflicts… in the toolbar compares them.")
419 }
420 }
421
422 /// Counts the focused file's sync conflict copies and recovery versions.
423 private func countVersions() {
424 guard isFocused else { return }
425 syncCopies = session.syncConflictCopies().count
426 recoveries = session.recoveryVersions().count
427 }
428
429 private func makeEditor() -> MobileEditor? {
430 guard let document = session.document(of: path) else { return nil }
431 let editor = MobileEditor(
432 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
433 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
434 )
435 let path = path
436 editor.fileName = path
437 editor.attachmentPath = { DocumentSession.attachmentPath($0, at: $1, tree: $2, path: path) }
438 return editor
439 }
440
441 /// The editor's callbacks go to this screen: it's shown here, or its view here took focus.
442 private func bind(_ editor: MobileEditor) {
443 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
444 editor.completionSource = { [index = workspace.index, path] query in await CompletionSources.answer(query, index: index, excluding: path) }
445 editor.createID = { [weak session] item in session.flatMap { CompletionSources.createID(item, session: $0) } }
446 editor.otherBuffers = { [weak session, path] in session.map { CompletionSources.otherBuffers($0, excluding: path) } ?? [] }
447 editor.onChange = { [weak session] in session?.bufferChanged(path) }
448 editor.onSelect = { [weak model] in model?.handoff.changed() }
449 editor.onMessage = { message = $0 }
450 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
451 editor.onLink = { link in follow(link) }
452 editor.onEditBlock = { edit in sheet = .block(edit) }
453 editor.onColumnView = { view in sheet = .columns(view) }
454 editor.onTangle = { scope in if ProAccess.shared.allows(.babel) { message = session.tangle(scope) } }
455 editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } }
456 editor.onRefreshSetup = { session.refreshSetup() }
457 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
458 editor.keymap = model.keymap
459 editor.modal = model.modalKeys
460 // Dropped files are copies the drop made, so they are attached, not linked or opened.
461 editor.onFiles = { attachActions.drop($0, method: .attach, attachMethod: .mv) }
462 editor.onImage = { attachActions.yankImage($0, ext: $1) }
463 editor.onAppCommand = { id in
464 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
465 if Self.paneCommands.contains(id) {
466 if let onPaneCommand { if let text = onPaneCommand(id) { message = text } } else { message = MobileEditor.unavailable(command: id) }
467 } else if id == "app.save" {
468 _ = session.save(path)
469 } else if id == "app.archive" {
470 if let caret = self.editor?.editContext().caret { message = session.archive(from: (path, caret)) }
471 } else if id == "app.copy-rich-text" {
472 if let text = session.document(of: path)?.text { message = ExportItems.copy(path: path, text: text, theme: model.theme) }
473 } else if id == "app.export-dialog" {
474 sheet = .export
475 } else if id == EditorScreen.exportSubtreeCommand {
476 exportSubtree()
477 } else if id == "app.export.html-open" {
478 exportHTMLAndOpen()
479 } else if id == "app.export-body-only" {
480 let on = !ExportSettings.saved(for: path).bodyOnly
481 ExportItems.setBodyOnly(on, path: path)
482 message = on ? "Export: body only" : "Export: whole document"
483 } else if id == "app.export.icalendar-agenda" || id == "app.export.icalendar-combined" {
484 agendaCalendars(combined: id == "app.export.icalendar-combined")
485 } else if id.hasPrefix("app.publish") {
486 publish(id)
487 } else if AppStoreCommands.unavailable(id) {
488 message = "Attachments can't be linked on iPhone and iPad; Attach File… copies the file."
489 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
490 sheet = .refile(id)
491 } else if id == "app.table-import" {
492 importingTable = true
493 } else if id == "app.table-export" || id == "app.table-export.tsv" {
494 exportTable(csv: id == "app.table-export")
495 } else if id == "app.word-count" {
496 message = wordCount()
497 } else if id == "app.recovery" {
498 sheet = .recovery
499 } else if id == "app.sync-conflicts" {
500 sheet = .syncCopies
501 } else if id == "app.attach.photo" {
502 attachingPhotos = true
503 } else if id == "app.attach.camera" {
504 takingPhoto = true
505 } else if id == "app.attach.scan" {
506 scanning = true
507 } else if id == "app.plot" {
508 plotTable()
509 } else if id.hasPrefix("app.crypt.") {
510 crypt(id)
511 } else if id.hasPrefix("app.attach.") {
512 attachActions.run(id)
513 } else if id == "app.node.graph" {
514 sheet = .graph
515 } else if id.hasPrefix("app.dailies.") || id.hasPrefix("app.node.") {
516 roamActions.run(id)
517 } else if id == "app.backlinks" {
518 sheet = .backlinks
519 } else if let kind = ReplaceKind(command: id), kind != .replace {
520 let context = self.editor?.editContext()
521 sheet = .rename(kind, context.map { kind.initial(text: $0.text, caret: $0.caret, keywords: $0.tree.settings.todoKeywordNames) } ?? "")
522 } else if id == "app.lint" {
523 if FileLint.applies(to: path) { sheet = .lint } else { message = String(localized: "Lint File works on Org files", comment: "Lint File in a file that isn't Org") }
524 } else if id == "app.working-copy.sync" {
525 if let root = model.workingCopy.root(containing: path, roots: workspace.rootPaths) {
526 model.workingCopy.sync(root, session: session)
527 } else {
528 message = String(localized: "This folder doesn't sync with Working Copy; turn it on in Settings ▸ Working Copy.", comment: "Sync with Working Copy in a folder that isn't set up")
529 }
530 } else if id == "app.toggle-markup" {
531 model.showMarkup.toggle()
532 } else if MobileEditor.linkCommands.contains(id) {
533 link(id)
534 } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
535 message = MobileEditor.unavailable(command: id)
536 }
537 }
538 }
539}
540
541extension EditorScreen {
542 /// Follows a link; files the editor doesn't open show in Quick Look.
543 private func follow(_ link: OrgLink) {
544 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
545 case .shown:
546 // A link to another file shows it on its own screen; this pane keeps its file.
547 guard let pane, let target = pane.path, target != path else { message = nil; return }
548 let caret = session.caret(of: target) ?? 0
549 session.open(path, in: pane)
550 model.openRequest = .offset(target, caret)
551 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
552 case .message(let text): message = text
553 case .choose(let question, let paths):
554 let labels = paths.map { ($0 as NSString).lastPathComponent }
555 prompt = PromptRequest(prompt: Prompt(key: "file", message: question, choices: labels)) { answer in
556 guard let answer, let index = labels.firstIndex(of: answer) else { return }
557 follow(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]))
558 }
559 case .elisp(let form):
560 // Once trusted, as `org-link-elisp-confirm-function` asks.
561 let go = { _ = Task { message = await session.evaluateLink(form) } }
562 let content = "elisp:" + form
563 if trust.isTrusted(path: path, content: content) { return go() }
564 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Execute \(form) as Elisp?", choices: ["yes", "no", "always"])) { answer in
565 switch answer {
566 case "always":
567 trust.trust(path: path, content: content)
568 go()
569 case "yes": go()
570 default: message = "Not run"
571 }
572 }
573 }
574 }
575
576 /// org-roam's daily notes and nodes.
577 private var roamActions: RoamActions {
578 RoamActions(
579 session: session, roots: { workspace.rootPaths },
580 nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
581 show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
582 open: { file, offset in
583 if file == path { editor?.reveal(offset) } else { model.openRequest = .offset(file, offset) }
584 },
585 insertLink: { link, title in
586 guard let editor else { return }
587 let context = editor.editContext()
588 let range = context.selection.first ?? context.caret..<context.caret
589 let selected = (context.text as NSString).substring(with: NSRange(range))
590 let text = Links.makeString(link, selected.isEmpty ? title : selected)
591 let end = range.lowerBound + (text as NSString).length
592 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
593 },
594 refresh: { Task { await workspace.refresh() } })
595 }
596
597 /// org-attach's commands for the entry at the caret.
598 private var attachActions: AttachActions {
599 AttachActions(
600 entry: {
601 guard let editor else { return nil }
602 let context = editor.editContext()
603 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
604 },
605 apply: { new, caret in
606 guard let editor else { return }
607 let context = editor.editContext()
608 let caret = min(caret ?? context.caret, (new as NSString).length)
609 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
610 },
611 show: { message = $0 },
612 ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
613 storeLink: { _ = StoredLink.add($0, to: &model.storedLinks) },
614 open: { follow(OrgLink(type: "file", path: $0, raw: "file:" + $0)) },
615 reveal: { dir in
616 if let url = URL(string: "shareddocuments://" + (dir.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? dir)) { openURL(url) }
617 },
618 pick: { attaching = $0 })
619 }
620
621 /// Photos and videos attached under the names Photos gives them, linked at the caret.
622 private func attachPhotos(_ items: [PhotosPickerItem]) {
623 Task { @MainActor in
624 var urls: [URL] = []
625 for item in items {
626 if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
627 }
628 if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
629 if !urls.isEmpty { attachActions.drop(urls, method: .attach, attachMethod: .mv) }
630 }
631 }
632
633 /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
634 private func importTable(_ result: Result<URL, Error>) {
635 guard case .success(let url) = result, let editor else { return }
636 let scoped = url.startAccessingSecurityScopedResource()
637 defer { if scoped { url.stopAccessingSecurityScopedResource() } }
638 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
639 _ = editor.perform(ImportTable(contents: contents))
640 }
641
642 /// The export formats for the subtree at the caret, as the Mac's export sheet's scope.
643 private func exportSubtree() {
644 guard let context = editor?.editContext() else { return }
645 guard ExportScope.subtree(context.text, at: context.caret) != nil else { return message = "Not in a subtree" }
646 sheet = .exportSubtree(context.caret)
647 }
648
649 /// `org-html-export-to-html` and open: the page in Quick Look, from a temporary file.
650 private func exportHTMLAndOpen() {
651 guard let text = session.document(of: path)?.text else { return }
652 let html = OrgExport.html(text, path: path, theme: model.theme, bodyOnly: ExportSettings.saved(for: path).bodyOnly)
653 let name = ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: OrgPreferences.orgSettings()), extension: "html")
654 .lastPathComponent
655 do {
656 previewed = try HTMLPreview.write(html, directory: URL(fileURLWithPath: path).deletingLastPathComponent(), name: name)
657 } catch {
658 message = "Can't export \(name): \(error.localizedDescription)"
659 }
660 }
661
662 /// The agenda files' calendars written beside them, or combined in one shown in Quick Look,
663 /// whose share button saves or sends it.
664 private func agendaCalendars(combined: Bool) {
665 guard let calendars = AgendaCalendars(model: model) else { return message = "No agenda files" }
666 guard combined else { return message = calendars.exportEach() }
667 do {
668 previewed = try calendars.combined()
669 } catch {
670 message = "Can't export: \(error.localizedDescription)"
671 }
672 }
673
674 /// `org-publish` and its variants, for the `[[publish]]` projects in config.toml.
675 private func publish(_ id: String) {
676 guard let all = publishProjects() else { return }
677 let current = Publish.projects(containing: path, in: all)
678 switch id {
679 case "app.publish.all":
680 publish(all.map(\.name))
681 case "app.publish.current-file":
682 guard let project = current.first else { return message = "File is not part of any known project" }
683 publish([project.name], only: path)
684 case "app.publish.current-project":
685 guard let project = current.first else { return message = "File is not part of any known project" }
686 publish([project.name])
687 default:
688 prompt = PromptRequest(prompt: Prompt(key: "project", message: "Publish project:", choices: all.map(\.name))) { answer in
689 if let answer, all.contains(where: { $0.name == answer }) { publish([answer]) }
690 }
691 }
692 }
693
694 /// The projects in config.toml, each publishing to the folder chosen for it; nil, with a
695 /// message, when there are none.
696 private func publishProjects() -> [PublishProject]? {
697 let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
698 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
699 if let problem = loaded.problems.first { message = problem }
700 guard !loaded.projects.isEmpty else {
701 message = "No [[publish]] projects in config.toml"
702 return nil
703 }
704 return PublishFolders.shared.applied(to: loaded.projects)
705 }
706
707 /// Publishes the projects named, `only` that file when given. A project that publishes
708 /// outside the folders added to orgstar asks for its folder first, once.
709 private func publish(_ names: [String], only: String? = nil) {
710 guard let all = publishProjects() else { return }
711 let chosen = all.filter { names.contains($0.name) }
712 do {
713 if let project = try PublishFolders.shared.needed(chosen, all: all, roots: workspace.rootPaths).first {
714 message = "Choose the folder \(project.name) publishes to"
715 publishFolder = PublishFolderRequest(project: project.name) { publish(names, only: only) }
716 choosingPublishFolder = true
717 return
718 }
719 if let project = try Publish.expand(chosen, all: all).first(where: { !FileManager.default.fileExists(atPath: $0.baseDirectory) }) {
720 return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))"
721 }
722 let read = { (file: String) -> String? in
723 session.openDocuments.first { $0.path == file }?.document.text ?? (try? String(contentsOfFile: file, encoding: .utf8))
724 }
725 let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme)
726 // As the Export menu: no author unless the file has #+AUTHOR:.
727 let report = try Publish.publish(chosen, all: all, only: only, author: "", read: read) { function, text, file, bodyOnly in
728 try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle, author: "")
729 }
730 message = report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files")
731 : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date")
732 } catch {
733 message = "\(error)"
734 }
735 }
736
737 /// org-crypt's commands at the caret, through the passphrase sheet.
738 private func crypt(_ id: String) {
739 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
740 guard let editor else { return }
741 let context = editor.editContext()
742 switch id {
743 case "app.crypt.forget-passphrase":
744 CryptPassphrases.forget(path)
745 message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
746 case "app.crypt.encrypt-entries":
747 sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
748 default:
749 guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
750 let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
751 if id == "app.crypt.encrypt-entry" {
752 guard !encrypted else { return message = "The entry is encrypted already" }
753 sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
754 } else {
755 guard encrypted else { return message = "Not an encrypted entry" }
756 sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
757 }
758 }
759 }
760
761 /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
762 /// one, else shown.
763 private func plotTable() {
764 guard let editor else { return }
765 let context = editor.editContext()
766 do {
767 let plot = try TablePlot.plot(context.text, at: context.caret)
768 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
769 try PlotOutput.write(plot, to: url)
770 message = "Plot written to \(url.lastPathComponent)" + (PlotOutput.note(plot).map { ". " + $0 } ?? "")
771 if editor.showsImages { editor.restyleAll() }
772 } else {
773 try PlotOutput.check(plot)
774 sheet = .plot(plot)
775 if let note = PlotOutput.note(plot) { message = note }
776 }
777 } catch {
778 message = "\(error)"
779 }
780 }
781
782 /// `org-table-export` of the table at the caret, as CSV or TSV.
783 /// Words, characters and reading time of the selection, or of the file.
784 private func wordCount() -> String {
785 guard let editor else { return "No file is open" }
786 let text = editor.document.text as NSString
787 let selection = editor.textView.selectedRange
788 let selected = selection.length > 0 && NSMaxRange(selection) <= text.length
789 let counts = TextStats.region(selected ? text.substring(with: selection) : text as String)
790 return (selected ? "Selection: " : "") + TextStats.summary(words: counts.words, characters: counts.characters)
791 }
792
793 private func exportTable(csv: Bool) {
794 guard let editor else { return }
795 let context = editor.editContext()
796 guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
797 return message = "No table at point"
798 }
799 exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
800 }
801
802 /// `org-refile` of the entry at the caret, to a target worked out again from the files
803 /// now, as the agenda's Refile… does.
804 func refile(to target: RefileTarget, keep: Bool = false) {
805 guard let editor, let path = session.path else { return }
806 let caret = editor.editContext().caret
807 guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
808 message = "Can't find \(target.label) any more."
809 return
810 }
811 message = session.refile(to: current, from: (path, caret), keep: keep)
812 }
813}
814
815/// The editor's text view, with the Org key bar over the keyboard.
816struct EditorTextView: UIViewRepresentable {
817 let editor: MobileEditor
818 /// This pane's view of the editor.
819 let view: UITextView
820 let palette: () -> Void
821
822 func makeUIView(context: Context) -> UITextView {
823 let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette).dynamicTypeSize(...KeyBar.largestSize))
824 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 2 * KeyBar.padding + KeyBar.target)
825 bar.view.backgroundColor = .clear
826 // As tall as its buttons: the input accessory takes the intrinsic height.
827 bar.sizingOptions = .intrinsicContentSize
828 bar.safeAreaRegions = []
829 bar.view.autoresizingMask = .flexibleHeight
830 view.inputAccessoryView = bar.view
831 context.coordinator.bar = bar
832 // The bar's height follows the text size.
833 view.registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) { (view: UITextView, _) in
834 view.inputAccessoryView?.invalidateIntrinsicContentSize()
835 view.reloadInputViews()
836 }
837 return view
838 }
839
840 func updateUIView(_ view: UITextView, context: Context) {}
841
842 func makeCoordinator() -> Coordinator { Coordinator() }
843
844 final class Coordinator {
845 var bar: UIViewController?
846 }
847}
848
849/// A command's question: text with choices, a date, or fast selection by keys.
850struct PromptSheet: View {
851 let prompt: Prompt
852 let answer: (String?) -> Void
853 @State private var text = ""
854 @State private var date = Date()
855 @State private var withTime = false
856 @State private var keys: [FastSelection.Input] = []
857
858 var body: some View {
859 NavigationStack {
860 Form {
861 if let fast = prompt.fast {
862 fastSection(fast)
863 } else {
864 Section {
865 TextField(prompt.message, text: $text)
866 .autocorrectionDisabled()
867 .textInputAutocapitalization(.never)
868 .onSubmit { answer(text) }
869 } footer: {
870 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
871 }
872 if prompt.date != nil {
873 DatePicker("Date", selection: $date, displayedComponents: [.date])
874 .datePickerStyle(.graphical)
875 .onChange(of: date) { text = QuestionField.stamp(date, withTime: withTime) }
876 Toggle("Time", isOn: $withTime)
877 .onChange(of: withTime) {
878 if withTime { date = QuestionField.timed(date) }
879 text = QuestionField.stamp(date, withTime: withTime)
880 }
881 if withTime { DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute) }
882 }
883 if !prompt.choices.isEmpty {
884 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
885 Section("Choices") {
886 ForEach(matching.prefix(50), id: \.self) { choice in
887 Button(choice) { choose(choice) }
888 }
889 }
890 }
891 }
892 }
893 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
894 .navigationBarTitleDisplayMode(.inline)
895 .toolbar {
896 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
897 if prompt.fast == nil || prompt.fast?.multiple == true {
898 ToolbarItem(placement: .confirmationAction) {
899 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
900 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
901 }
902 }
903 }
904 }
905 .onAppear {
906 text = prompt.initial
907 date = prompt.date?.defaultDate ?? Calendar.current.startOfDay(for: Date())
908 }
909 }
910
911 /// With a separator (tags), what's typed after the last one.
912 private var lastPart: String {
913 guard let separator = prompt.completionSeparator else { return text }
914 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
915 }
916
917 private func choose(_ choice: String) {
918 guard let separator = prompt.completionSeparator else {
919 text = choice
920 if prompt.date == nil { answer(choice) }
921 return
922 }
923 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
924 if parts.isEmpty { parts = [""] }
925 parts[parts.count - 1] = choice
926 text = parts.joined(separator: String(separator)) + String(separator)
927 }
928
929 @ViewBuilder
930 private func fastSection(_ fast: FastSelection) -> some View {
931 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
932 Section {
933 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
934 Button {
935 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
936 } label: {
937 HStack {
938 Text(option.name).foregroundStyle(.primary)
939 Spacer()
940 if current.contains(option.name) { Image(systemName: "checkmark") }
941 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
942 }
943 }
944 }
945 if !fast.multiple {
946 Button("No Keyword") { answer(" ") }
947 }
948 } footer: {
949 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
950 }
951 }
952}
953
954/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
955/// A src block's code is highlighted as its language.
956struct BlockEditSheet: View {
957 let edit: BlockEdit
958 let theme: MobileTheme
959 let finish: (String?) -> Void
960 @State private var text: String?
961
962 var body: some View {
963 NavigationStack {
964 Group {
965 if let text {
966 CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
967 }
968 }
969 .padding(.horizontal, 8)
970 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
971 .navigationBarTitleDisplayMode(.inline)
972 .toolbar {
973 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
974 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
975 }
976 }
977 .onAppear { text = edit.content }
978 }
979}
980
981/// A text view for code, restyled with the editor's highlighter after each change.
982struct CodeTextView: UIViewRepresentable {
983 let text: String
984 let language: String?
985 let theme: MobileTheme
986 let changed: (String) -> Void
987
988 func makeUIView(context: Context) -> UITextView {
989 let view = UITextView()
990 view.autocorrectionType = .no
991 view.autocapitalizationType = .none
992 view.smartQuotesType = .no
993 view.smartDashesType = .no
994 view.spellCheckingType = .no
995 view.keyboardDismissMode = .interactive
996 view.backgroundColor = .clear
997 view.text = text
998 view.delegate = context.coordinator
999 context.coordinator.style(view)
1000 DispatchQueue.main.async { view.becomeFirstResponder() }
1001 return view
1002 }
1003
1004 func updateUIView(_ view: UITextView, context: Context) {
1005 context.coordinator.parent = self
1006 }
1007
1008 func makeCoordinator() -> Coordinator { Coordinator(self) }
1009
1010 @MainActor
1011 final class Coordinator: NSObject, UITextViewDelegate {
1012 var parent: CodeTextView
1013 init(_ parent: CodeTextView) { self.parent = parent }
1014
1015 func textViewDidChange(_ view: UITextView) {
1016 parent.changed(view.text)
1017 style(view)
1018 }
1019
1020 /// The theme's font and color, then the language's token colors.
1021 func style(_ view: UITextView) {
1022 let storage = view.textStorage
1023 let whole = NSRange(location: 0, length: storage.length)
1024 let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
1025 storage.beginEditing()
1026 storage.setAttributes(base, range: whole)
1027 if let language = parent.language {
1028 for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
1029 guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
1030 storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
1031 }
1032 }
1033 storage.endEditing()
1034 view.typingAttributes = base
1035 }
1036 }
1037}
1038
1039/// The editor's commands, those that don't apply at the caret greyed with the reason.
1040struct CommandPalette: View {
1041 let editor: MobileEditor
1042 /// The pane commands are offered (on iPad), and those for more than one pane.
1043 var panes = false
1044 var split = false
1045 /// Recovery versions and sync conflict copies of the file, which their commands show.
1046 var recoveries = 0
1047 var syncCopies = 0
1048 /// Called with the chosen command before the palette closes.
1049 let choose: (String) -> Void
1050
1051 static let viewCommands: [(id: String, title: String)] = [
1052 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
1053 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
1054 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
1055 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
1056 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
1057 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
1058 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
1059 ("app.archive", "Archive Subtree"), ("app.export-dialog", "Export…"), ("app.export-subtree-dialog", "Export Subtree…"),
1060 ("app.copy-rich-text", "Copy as Rich Text"), ("app.export.html-open", "Export to HTML and Open"),
1061 ("app.export-body-only", "Turn Body-Only Export On or Off"),
1062 ("app.export.icalendar-agenda", "Export Agenda Files to iCalendar"), ("app.export.icalendar-combined", "Combine Agenda Files into iCalendar"),
1063 ("app.publish", "Publish Project…"), ("app.publish.all", "Publish All Projects"), ("app.publish.current-file", "Publish Current File"),
1064 ("app.publish.current-project", "Publish Current Project"),
1065 ("app.toggle-markup", "Show or Hide Markup"), ("app.word-count", "Word Count"),
1066 ("org.snippet.next-field", "Next Snippet Field"), ("org.snippet.previous-field", "Previous Snippet Field"),
1067 ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"), ("app.lint", "Lint File"),
1068 ("app.working-copy.sync", "Sync with Working Copy"),
1069 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.toggle-inline-images-linked", "Show or Hide Inline Images, Including Described Links"), ("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"),
1070 ("editor.complete", "Complete at Point"), ("editor.dabbrev-expand", "Expand Word"), ("editor.dabbrev-completion", "Complete Word"),
1071 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
1072 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
1073 ("org.table.expand", "Expand Table Columns"),
1074 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"),
1075 ("app.table-export.tsv", "Export Table as TSV…"), ("app.plot", "Plot Table"),
1076 ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
1077 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
1078 ("app.rename-tag", "Rename Tag…"), ("app.rename-todo-keyword", "Rename TODO Keyword…"),
1079 ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"), ("app.node.graph", "Show Node Graph"),
1080 ("app.node.rename-from-front-matter", "Rename Note from Front Matter"),
1081 ("app.node.rename", "Rename Note…"),
1082 ("app.node.rename-folder-from-front-matter", "Rename Notes in Folder from Front Matter…"),
1083 ("app.node.silo-find", "Find Note in Silo…"),
1084 ("app.node.silo-create", "New Note in Silo…"),
1085 ("app.node.sequence-new-parent", "New Sequence Note…"),
1086 ("app.node.sequence-new-child", "New Child Sequence Note…"),
1087 ("app.node.sequence-new-sibling", "New Sibling Sequence Note…"),
1088 ("app.node.sequence-new-child-of-current", "New Child of This Note…"),
1089 ("app.node.sequence-new-sibling-of-current", "New Sibling of This Note…"),
1090 ("app.node.sequence-find", "Find Sequence Relatives…"),
1091 ("app.node.sequence-next-sibling", "Next Sibling Note"),
1092 ("app.node.sequence-previous-sibling", "Previous Sibling Note"),
1093 ("app.node.sequence-reparent", "Reparent Note…"),
1094 ("app.node.sequence-reparent-recursive", "Reparent Note with Descendants…"),
1095 ("app.node.sequence-rename-as-parent", "Rename Note as Sequence Parent"),
1096 ("app.node.sequence-convert", "Convert Note Sequence Scheme"),
1097 ("app.node.sequence-link", "Insert Sequence Link…"),
1098 ("app.node.sequence-hierarchy", "Sequence Hierarchy…"),
1099 ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
1100 ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
1101 ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
1102 ("app.dailies.capture-tomorrow", "Capture to Tomorrow's Daily Note"), ("app.dailies.capture-date", "Capture to Daily Note for Date…"),
1103 ("app.dailies.next", "Next Daily Note"), ("app.dailies.previous", "Previous Daily Note"),
1104 ("app.attach.attach", "Attach File…"), ("app.attach.photo", "Attach Photo or Video…"), ("app.attach.camera", "Take Photo…"),
1105 ("app.attach.scan", "Scan Document…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
1106 ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
1107 ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
1108 ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
1109 ]
1110
1111 /// The commands and their keys, and why those that don't apply at the caret don't, worked
1112 /// out once when the palette opens rather than on every keystroke in the search field.
1113 @State private var rows: [CommandRow]?
1114
1115 var body: some View {
1116 CommandList(rows: rows ?? [], choose: choose)
1117 .onAppear {
1118 guard rows == nil else { return }
1119 rows = commandRows()
1120 }
1121 }
1122
1123 private func commandRows() -> [CommandRow] {
1124 let context = editor.editContext()
1125 let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
1126 + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
1127 return Self.commands(macros: editor.namedMacros, panes: paneCommands)
1128 .map { command in
1129 CommandRow(id: command.id, title: CommandTitle.localized(command.title), keys: editor.keymap.keyLabels(for: command.id).first,
1130 reason: reason(command.id, context))
1131 }
1132 }
1133
1134 /// The commands listed, with English titles: `panes`, the editor's, and the named macros.
1135 static func commands(macros: NamedMacros, panes: [(id: String, title: String)] = []) -> [(id: String, title: String)] {
1136 var seen = Set<String>()
1137 return (panes + viewCommands + Commands.everything.map { ($0.id, $0.title) } + macros.names.map { (NamedMacros.commandPrefix + $0, $0) })
1138 .filter { !AppStoreCommands.hidden.contains($0.id) && offered($0.id) && seen.insert($0.id).inserted }
1139 }
1140
1141 /// Commands for a camera or scanner this device lacks aren't listed.
1142 private static func offered(_ id: String) -> Bool {
1143 switch id {
1144 case "app.attach.camera": CameraPicker.isAvailable
1145 case "app.attach.scan": DocumentScanner.isAvailable
1146 default: true
1147 }
1148 }
1149
1150 private func reason(_ id: String, _ context: EditContext) -> String? {
1151 switch id {
1152 case "app.recovery": return recoveries > 0 ? nil : String(localized: "No Recovery Versions")
1153 case "app.sync-conflicts": return syncCopies > 0 ? nil : String(localized: "No sync conflict copies", comment: "Why Resolve Sync Conflicts… is greyed in the Commands list")
1154 case EditorScreen.exportSubtreeCommand:
1155 return ExportScope.subtree(context.text, at: context.caret) != nil ? nil : String(localized: "Not in a subtree", comment: "Why Export Subtree… is greyed in the Commands list")
1156 default: return editor.applies(id, in: context) ? nil : CommandReason.reason(for: id, in: context)
1157 }
1158 }
1159}
1160/// A table as CSV or TSV, for the save dialog.
1161struct TableFile: FileDocument {
1162 static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
1163 let text: String
1164 let type: UTType
1165
1166 init(text: String, type: UTType) {
1167 self.text = text
1168 self.type = type
1169 }
1170
1171 init(configuration: ReadConfiguration) throws {
1172 text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
1173 type = configuration.contentType
1174 }
1175
1176 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
1177 FileWrapper(regularFileWithContents: Data(text.utf8))
1178 }
1179}
1180/// A plotted table, as the Mac's plot sheet shows it.
1181struct PlotScreen: View {
1182 let plot: TablePlot.Plot
1183 @Environment(\.dismiss) private var dismiss
1184
1185 var body: some View {
1186 NavigationStack {
1187 PlotChart(plot)
1188 .navigationTitle("Plot")
1189 .navigationBarTitleDisplayMode(.inline)
1190 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
1191 }
1192 }
1193}
1194/// A file from the photo picker, copied out of the picker's temporary place with its name.
1195struct PickedFile: Transferable {
1196 let url: URL
1197
1198 static var transferRepresentation: some TransferRepresentation {
1199 FileRepresentation(importedContentType: .item) { received in
1200 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
1201 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
1202 let url = folder.appendingPathComponent(received.file.lastPathComponent)
1203 try FileManager.default.copyItem(at: received.file, to: url)
1204 return PickedFile(url: url)
1205 }
1206 }
1207}
1208
1209/// The passphrase sheet for org-crypt, its new text applied in the editor.
1210struct CryptScreen: View {
1211 let request: CryptRequest
1212 let session: DocumentSession
1213 let editor: MobileEditor?
1214 let report: (String) -> Void
1215 @Environment(\.dismiss) private var dismiss
1216
1217 var body: some View {
1218 NavigationStack {
1219 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
1220 dismiss()
1221 if let message { report(message) }
1222 }
1223 .navigationBarTitleDisplayMode(.inline)
1224 }
1225 }
1226
1227 private func apply(_ new: String) {
1228 guard let editor else { return }
1229 let context = editor.editContext()
1230 let caret = min(context.caret, (new as NSString).length)
1231 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
1232 }
1233}
1234/// The pane an editor screen made for itself, closed with the screen.
1235@MainActor
1236final class PaneHolder {
1237 var pane: EditorPane?
1238 nonisolated(unsafe) var release: (() -> Void)?
1239
1240 deinit {
1241 guard let release else { return }
1242 Task { @MainActor in release() }
1243 }
1244}
1245
1246/// A command's result or refusal, over the screen until it is tapped or for four seconds, and
1247/// read out by VoiceOver.
1248private struct MessageView: ViewModifier {
1249 @Binding var message: String?
1250 let edge: VerticalEdge
1251
1252 func body(content: Content) -> some View {
1253 content.overlay(alignment: edge == .top ? .top : .bottom) {
1254 if let message {
1255 Text(message).font(.callout).multilineTextAlignment(.center)
1256 .padding(.horizontal, 14).padding(.vertical, 8)
1257 .glassEffect(.regular, in: .rect(cornerRadius: 18))
1258 .padding(8)
1259 .onTapGesture { self.message = nil }
1260 .task(id: message) {
1261 try? await Task.sleep(for: .seconds(4))
1262 if self.message == message { self.message = nil }
1263 }
1264 }
1265 }
1266 .onChange(of: message) { _, message in
1267 if let message { AccessibilityNotification.Announcement(message).post() }
1268 }
1269 }
1270}
1271
1272extension View {
1273 /// Shows `message` in the one message view, at the top or bottom of the screen.
1274 func message(_ message: Binding<String?>, edge: VerticalEdge = .bottom) -> some View {
1275 modifier(MessageView(message: message, edge: edge))
1276 }
1277}
1278
1279/// The screen's title, unless a split shows the focused pane's.
1280private struct EditorTitle: ViewModifier {
1281 let title: String
1282 let shown: Bool
1283
1284 func body(content: Content) -> some View {
1285 if shown {
1286 content.navigationTitle(title).navigationBarTitleDisplayMode(.inline)
1287 } else {
1288 content
1289 }
1290 }
1291}
1292#endif