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