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