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