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