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