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