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