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