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