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