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