Sources/OrgstarMobile/EditorScreen.swift
865 lines · 41881 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 @State private var editor: MobileEditor?
20 @State private var prompt: PromptRequest?
21 @State private var message: String?
22 @State private var sheet: Sheet?
23 @State private var trust = TrustStore()
24 /// The command chosen in the palette, run once the palette is gone.
25 @State private var chosen: String?
26 @Environment(ClockModel.self) private var clock
27 @Environment(MobileModel.self) private var model
28 @Environment(\.openURL) private var openURL
29
30 /// The session's options with `buffer-file-name` and the agenda files, for clock tables.
31 private var editorOptions: EditingOptions {
32 var options = session.options
33 options.filePath = path
34 options.agendaFiles = workspace.agendaFilePaths()
35 options.timer = TimerModel.shared.timer
36 return options
37 }
38
39 struct PromptRequest: Identifiable {
40 let id = UUID()
41 let prompt: Prompt
42 let reply: (String?) -> Void
43 }
44
45 /// One sheet at a time: two presenters on this screen interfere.
46 /// `org-table-import`'s file picker is up.
47 @State private var importingTable = false
48 /// The table at the caret, for `org-table-export`'s save dialog.
49 @State private var exportedTable: TableFile?
50 /// org-attach's file picker is up, for this method.
51 @State private var attaching: Attachments.Method?
52 @State private var attachingPhotos = false
53 @State private var photos: [PhotosPickerItem] = []
54 /// A file shown in Quick Look.
55 @State private var previewed: URL?
56
57 enum Sheet: Identifiable {
58 case palette, conflict, syncCopies, recovery
59 /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
60 case refile(String)
61 case block(BlockEdit)
62 case columns(ColumnView.View)
63 case plot(TablePlot.Plot)
64 case crypt(CryptRequest)
65
66 var id: String {
67 switch self {
68 case .palette: "palette"
69 case .refile(let command): command
70 case .conflict: "conflict"
71 case .syncCopies: "syncCopies"
72 case .recovery: "recovery"
73 case .block(let edit): "block \(edit.range)"
74 case .columns: "columns"
75 case .plot: "plot"
76 case .crypt(let request): request.id.uuidString
77 }
78 }
79 }
80
81 var body: some View {
82 Group {
83 if let editor {
84 EditorTextView(editor: editor, palette: { sheet = .palette })
85 .ignoresSafeArea(.container, edges: .bottom)
86 } else {
87 ProgressView()
88 }
89 }
90 .navigationTitle(session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""))
91 .navigationBarTitleDisplayMode(.inline)
92 .toolbar(.hidden, for: .tabBar)
93 .toolbar {
94 ToolbarItemGroup(placement: .primaryAction) {
95 if session.conflict != nil {
96 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
97 }
98 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
99 Menu("More", systemImage: "ellipsis.circle") {
100 Button("Commands", systemImage: "command") { sheet = .palette }
101 Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
102 Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") }
103 Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") }
104 Menu("Table", systemImage: "tablecells") {
105 Button("Import Table from File…", systemImage: "square.and.arrow.down") { importingTable = true }
106 Button("Export Table as CSV…", systemImage: "square.and.arrow.up") { exportTable(csv: true) }
107 Button("Export Table as TSV…", systemImage: "square.and.arrow.up") { exportTable(csv: false) }
108 Button("Plot Table", systemImage: "chart.xyaxis.line") { plotTable() }
109 }
110 Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) {
111 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
112 }
113 RecentClockMenu(clock: clock) { editor?.run($0) }
114 Menu("Attachments", systemImage: "paperclip") {
115 Button("Attach File…", systemImage: "doc.badge.plus") { attaching = .cp }
116 Button("Attach Photo or Video…", systemImage: "photo.badge.plus") { attachingPhotos = true }
117 Button("Attach File from URL…", systemImage: "link.badge.plus") { attachActions.run("app.attach.url") }
118 Button("New Attachment…", systemImage: "square.and.pencil") { attachActions.run("app.attach.new") }
119 Button("Open Attachment…", systemImage: "paperclip") { attachActions.run("app.attach.open") }
120 Button("Show Attachment Folder", systemImage: "folder") { attachActions.run("app.attach.reveal") }
121 Button("Delete Attachment…", systemImage: "trash") { attachActions.run("app.attach.delete") }
122 Button("Delete All Attachments…", systemImage: "trash.slash") { attachActions.run("app.attach.delete-all") }
123 Button("Sync Attachments", systemImage: "arrow.triangle.2.circlepath") { attachActions.run("app.attach.sync") }
124 Button("Set Attachment Folder…", systemImage: "folder.badge.gearshape") { attachActions.run("app.attach.set-directory") }
125 Button("Unset Attachment Folder", systemImage: "folder.badge.minus") { attachActions.run("app.attach.unset-directory") }
126 }
127 Menu("Encryption", systemImage: "lock") {
128 Button("Encrypt Entry…", systemImage: "lock") { crypt("app.crypt.encrypt-entry") }
129 Button("Decrypt Entry…", systemImage: "lock.open") { crypt("app.crypt.open-entry") }
130 Button("Decrypt Entry in File…", systemImage: "lock.open.trianglebadge.exclamationmark") { crypt("app.crypt.decrypt-entry") }
131 Button("Encrypt Tagged Entries…", systemImage: "lock.rectangle.stack") { crypt("app.crypt.encrypt-entries") }
132 Button("Forget Encryption Passphrase", systemImage: "key.slash") { crypt("app.crypt.forget-passphrase") }
133 }
134 if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) { message = $0 } }
135 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
136 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
137 }
138 }
139 }
140 .safeAreaInset(edge: .top) {
141 VStack(spacing: 0) {
142 if let timer = TimerModel.shared.timer {
143 TimelineView(.periodic(from: .now, by: 1)) { context in
144 Text(timer.modeLine(now: context.date)).font(.callout.monospacedDigit())
145 }
146 .frame(maxWidth: .infinity).padding(4).background(.bar)
147 }
148 if let message {
149 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
150 .onTapGesture { self.message = nil }
151 .task(id: message) {
152 try? await Task.sleep(for: .seconds(4))
153 if self.message == message { self.message = nil }
154 }
155 }
156 }
157 }
158 .sheet(item: $prompt) { request in
159 PromptSheet(prompt: request.prompt) { answer in
160 prompt = nil
161 request.reply(answer)
162 }
163 }
164 .sheet(item: $sheet, onDismiss: {
165 // After the sheet has gone, so a command's own prompt can show.
166 if let id = chosen {
167 chosen = nil
168 editor?.run(id)
169 }
170 }) { sheet in
171 switch sheet {
172 case .palette: if let editor { CommandPalette(editor: editor) { chosen = $0 } }
173 case .conflict: ConflictSheet(session: session)
174 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
175 case .recovery: RecoverySheet(session: session) { message = $0 }
176 case .refile(let command):
177 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
178 create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
179 self.sheet = nil
180 switch session.createRefileChild(under: parent, title: child) {
181 case .success(let target):
182 guard let path = session.path, let editor else { return }
183 message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
184 case .failure(.message(let text)): message = text
185 }
186 }) { target in
187 self.sheet = nil
188 guard let target else { return }
189 if command == "app.refile.goto" {
190 model.openRequest = .offset(target.path, target.start ?? Int.max)
191 } else {
192 refile(to: target, keep: command == "app.refile.copy")
193 }
194 }
195 case .block(let edit):
196 BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
197 self.sheet = nil
198 if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
199 }
200 case .columns(let view):
201 ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
202 case .plot(let plot):
203 PlotScreen(plot: plot)
204 case .crypt(let request):
205 CryptScreen(request: request, session: session, editor: editor) { message = $0 }
206 }
207 }
208 .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
209 importTable(result)
210 }
211 .background {
212 // A second importer on the same view would replace the first.
213 Color.clear.fileImporter(isPresented: Binding(get: { attaching != nil }, set: { if !$0 { attaching = nil } }),
214 allowedContentTypes: [.item, .folder], allowsMultipleSelection: true) { result in
215 let method = attaching ?? .cp
216 switch result {
217 case .success(let urls): attachActions.attach(urls, method: method)
218 case .failure(let error): message = error.localizedDescription
219 }
220 }
221 }
222 .photosPicker(isPresented: $attachingPhotos, selection: $photos, matching: .any(of: [.images, .videos]))
223 .onChange(of: photos) { _, items in
224 guard !items.isEmpty else { return }
225 photos = []
226 attachPhotos(items)
227 }
228 .quickLookPreview($previewed)
229 .fileExporter(isPresented: Binding(get: { exportedTable != nil }, set: { if !$0 { exportedTable = nil } }),
230 document: exportedTable, contentType: exportedTable?.type ?? .commaSeparatedText,
231 defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in
232 if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." }
233 }
234 .onChange(of: session.conflict) { _, conflict in
235 if conflict != nil, session.path == path { sheet = .conflict }
236 }
237 .onChange(of: session.lastError) { _, error in
238 if let error { message = error; session.lastError = nil }
239 }
240 .onAppear(perform: start)
241 .onChange(of: session.revealRequest?.id) {
242 if let offset = session.revealRequest?.offset, session.path == path { editor?.reveal(offset) }
243 }
244 .onChange(of: model.settingsVersion) {
245 editor?.options = editorOptions
246 editor?.themeSpec = model.theme
247 editor?.keymap = model.keymap
248 editor?.modal = model.modalKeys
249 }
250 .onChange(of: model.showMarkup) { editor?.showMarkup = model.showMarkup }
251 .onChange(of: TimerModel.shared.timer) { editor?.options = editorOptions }
252 .onDisappear {
253 // Typing the reader shows next, and a save, don't wait for the autosave delay.
254 if session.dirtyPaths.contains(path) { _ = session.save(path) }
255 }
256 }
257
258 /// Store Link, Store ID Link and Insert Link, with the links stored while the app runs.
259 private func link(_ id: String) {
260 guard let editor else { return }
261 switch id {
262 case "org.link.store":
263 message = StoredLink.add(Links.store(in: editor.editContext(), path: Links.abbreviate(path, home: NSHomeDirectory())), to: &model.storedLinks)
264 case "org.id.store-link":
265 if case .commit = editor.perform(CreateID()),
266 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
267 message = StoredLink.add(link, to: &model.storedLinks)
268 }
269 default:
270 _ = editor.perform(InsertLink(stored: model.storedLinks, file: path))
271 }
272 }
273
274 /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
275 private func run(_ job: BabelJob) {
276 let go = {
277 message = "Running \(job.language) block…"
278 session.startBabel(job) { message = $0 }
279 }
280 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
281 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
282 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
283 switch answer {
284 case "always":
285 trust.trust(path: path, content: job.blockText)
286 go()
287 case "yes": go()
288 default: message = "Not run"
289 }
290 }
291 }
292
293 private func start() {
294 if session.path != path { session.open(path) }
295 if editor == nil, let document = session.document {
296 let editor = MobileEditor(
297 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
298 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
299 )
300 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
301 editor.onChange = { [weak session] in session?.bufferChanged(path) }
302 editor.onMessage = { message = $0 }
303 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
304 editor.onLink = { link in follow(link) }
305 editor.onEditBlock = { edit in sheet = .block(edit) }
306 editor.onColumnView = { view in sheet = .columns(view) }
307 editor.onTangle = { scope in message = session.tangle(scope) }
308 editor.onBabel = { job in run(job) }
309 editor.onRefreshSetup = { session.refreshSetup() }
310 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
311 editor.keymap = model.keymap
312 editor.modal = model.modalKeys
313 editor.onAppCommand = { id in
314 if id == "app.save" {
315 _ = session.save(path)
316 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
317 sheet = .refile(id)
318 } else if id == "app.table-import" {
319 importingTable = true
320 } else if id == "app.table-export" {
321 exportTable(csv: true)
322 } else if id == "app.plot" {
323 plotTable()
324 } else if id.hasPrefix("app.crypt.") {
325 crypt(id)
326 } else if id.hasPrefix("app.attach.") {
327 attachActions.run(id)
328 } else if id == "app.toggle-markup" {
329 model.showMarkup.toggle()
330 } else if MobileEditor.linkCommands.contains(id) {
331 link(id)
332 } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
333 message = "Not available on iOS yet"
334 }
335 }
336 self.editor = editor
337 }
338 if let editor { session.attach(editor) }
339 if let offset { editor?.reveal(offset) }
340 if session.conflict != nil {
341 sheet = .conflict
342 } else if case let copies = session.syncConflictCopies().count, copies > 0 {
343 message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
344 }
345 }
346}
347
348extension EditorScreen {
349 /// Follows a link; files the editor doesn't open show in Quick Look.
350 private func follow(_ link: OrgLink) {
351 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
352 case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")"
353 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
354 case .message(let text): message = text
355 }
356 }
357
358 /// org-attach's commands for the entry at the caret.
359 private var attachActions: AttachActions {
360 AttachActions(
361 entry: {
362 guard let editor else { return nil }
363 let context = editor.editContext()
364 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
365 },
366 apply: { new in
367 guard let editor else { return }
368 let context = editor.editContext()
369 let caret = min(context.caret, (new as NSString).length)
370 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
371 },
372 show: { message = $0 },
373 ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
374 storeLink: { _ = StoredLink.add($0, to: &model.storedLinks) },
375 open: { follow(OrgLink(type: "file", path: $0, raw: "file:" + $0)) },
376 reveal: { dir in
377 if let url = URL(string: "shareddocuments://" + (dir.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? dir)) { openURL(url) }
378 },
379 pick: { attaching = $0 })
380 }
381
382 /// Photos and videos attached under the names Photos gives them.
383 private func attachPhotos(_ items: [PhotosPickerItem]) {
384 Task { @MainActor in
385 var urls: [URL] = []
386 for item in items {
387 if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
388 }
389 if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
390 if !urls.isEmpty { attachActions.attach(urls, method: .mv) }
391 }
392 }
393
394 /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
395 private func importTable(_ result: Result<URL, Error>) {
396 guard case .success(let url) = result, let editor else { return }
397 let scoped = url.startAccessingSecurityScopedResource()
398 defer { if scoped { url.stopAccessingSecurityScopedResource() } }
399 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
400 _ = editor.perform(ImportTable(contents: contents))
401 }
402
403 /// org-crypt's commands at the caret, through the passphrase sheet.
404 private func crypt(_ id: String) {
405 guard let editor else { return }
406 let context = editor.editContext()
407 switch id {
408 case "app.crypt.forget-passphrase":
409 CryptPassphrases.forget(path)
410 message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
411 case "app.crypt.encrypt-entries":
412 sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
413 default:
414 guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
415 let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
416 if id == "app.crypt.encrypt-entry" {
417 guard !encrypted else { return message = "The entry is encrypted already" }
418 sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
419 } else {
420 guard encrypted else { return message = "Not an encrypted entry" }
421 sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
422 }
423 }
424 }
425
426 /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
427 /// one, else shown.
428 private func plotTable() {
429 guard let editor else { return }
430 let context = editor.editContext()
431 do {
432 let plot = try TablePlot.plot(context.text, at: context.caret)
433 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
434 try PlotOutput.write(plot, to: url)
435 message = "Plot written to \(url.lastPathComponent)"
436 if editor.showsImages { editor.restyleAll() }
437 } else {
438 sheet = .plot(plot)
439 }
440 } catch {
441 message = "\(error)"
442 }
443 }
444
445 /// `org-table-export` of the table at the caret, as CSV or TSV.
446 private func exportTable(csv: Bool) {
447 guard let editor else { return }
448 let context = editor.editContext()
449 guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
450 return message = "No table at point"
451 }
452 exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
453 }
454
455 /// `org-refile` of the entry at the caret, to a target worked out again from the files
456 /// now, as the agenda's Refile… does.
457 func refile(to target: RefileTarget, keep: Bool = false) {
458 guard let editor, let path = session.path else { return }
459 let caret = editor.editContext().caret
460 guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
461 message = "Can't find \(target.label) any more."
462 return
463 }
464 message = session.refile(to: current, from: (path, caret), keep: keep)
465 }
466}
467
468/// The editor's text view, with the Org key bar over the keyboard.
469struct EditorTextView: UIViewRepresentable {
470 let editor: MobileEditor
471 let palette: () -> Void
472
473 func makeUIView(context: Context) -> UITextView {
474 let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
475 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
476 bar.view.backgroundColor = .clear
477 bar.sizingOptions = []
478 editor.textView.inputAccessoryView = bar.view
479 context.coordinator.bar = bar
480 return editor.textView
481 }
482
483 func updateUIView(_ view: UITextView, context: Context) {}
484
485 func makeCoordinator() -> Coordinator { Coordinator() }
486
487 final class Coordinator {
488 var bar: UIViewController?
489 }
490}
491
492/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
493/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
494struct KeyBar: View {
495 let editor: MobileEditor
496 let palette: () -> Void
497
498 private static let keys: [(label: String, symbol: String?, keys: String)] = [
499 ("Fold", "arrow.right.to.line", "TAB"),
500 ("Overview", "arrow.left.to.line", "S-TAB"),
501 ("Promote", "arrow.left", "M-<left>"),
502 ("Demote", "arrow.right", "M-<right>"),
503 ("Move up", "arrow.up", "M-<up>"),
504 ("Move down", "arrow.down", "M-<down>"),
505 ("New heading or item", "plus", "M-RET"),
506 ("TODO", nil, "C-c C-t"),
507 ("Act at point", "checkmark.square", "C-c C-c"),
508 ("Schedule", "calendar", "C-c C-s"),
509 ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
510 ("Tags", "tag", "C-c C-q"),
511 ("Open link", "link", "C-c C-o"),
512 ]
513
514 var body: some View {
515 ScrollView(.horizontal, showsIndicators: false) {
516 HStack(spacing: 4) {
517 Button("Commands", systemImage: "command", action: palette)
518 ForEach(Self.keys, id: \.keys) { key in
519 Button {
520 editor.run(keys: key.keys)
521 } label: {
522 if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
523 }
524 .accessibilityLabel(key.label)
525 }
526 Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
527 }
528 .labelStyle(.iconOnly)
529 .buttonStyle(.bordered)
530 .padding(.horizontal, 8)
531 .padding(.vertical, 6)
532 }
533 .background(.bar)
534 }
535}
536
537/// A command's question: text with choices, a date, or fast selection by keys.
538struct PromptSheet: View {
539 let prompt: Prompt
540 let answer: (String?) -> Void
541 @State private var text = ""
542 @State private var date = Date()
543 @State private var keys: [FastSelection.Input] = []
544
545 var body: some View {
546 NavigationStack {
547 Form {
548 if let fast = prompt.fast {
549 fastSection(fast)
550 } else {
551 Section {
552 TextField(prompt.message, text: $text)
553 .autocorrectionDisabled()
554 .textInputAutocapitalization(.never)
555 .onSubmit { answer(text) }
556 } footer: {
557 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
558 }
559 if prompt.date != nil {
560 DatePicker("Date", selection: $date, displayedComponents: [.date])
561 .datePickerStyle(.graphical)
562 .onChange(of: date) { text = Self.stamp(date) }
563 }
564 if !prompt.choices.isEmpty {
565 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
566 Section("Choices") {
567 ForEach(matching.prefix(50), id: \.self) { choice in
568 Button(choice) { choose(choice) }
569 }
570 }
571 }
572 }
573 }
574 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
575 .navigationBarTitleDisplayMode(.inline)
576 .toolbar {
577 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
578 if prompt.fast == nil || prompt.fast?.multiple == true {
579 ToolbarItem(placement: .confirmationAction) {
580 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
581 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
582 }
583 }
584 }
585 }
586 .onAppear {
587 text = prompt.initial
588 if let day = prompt.date?.defaultDate { date = day }
589 }
590 }
591
592 /// With a separator (tags), what's typed after the last one.
593 private var lastPart: String {
594 guard let separator = prompt.completionSeparator else { return text }
595 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
596 }
597
598 private func choose(_ choice: String) {
599 guard let separator = prompt.completionSeparator else {
600 text = choice
601 if prompt.date == nil { answer(choice) }
602 return
603 }
604 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
605 if parts.isEmpty { parts = [""] }
606 parts[parts.count - 1] = choice
607 text = parts.joined(separator: String(separator)) + String(separator)
608 }
609
610 @ViewBuilder
611 private func fastSection(_ fast: FastSelection) -> some View {
612 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
613 Section {
614 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
615 Button {
616 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
617 } label: {
618 HStack {
619 Text(option.name).foregroundStyle(.primary)
620 Spacer()
621 if current.contains(option.name) { Image(systemName: "checkmark") }
622 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
623 }
624 }
625 }
626 if !fast.multiple {
627 Button("No keyword") { answer(" ") }
628 }
629 } footer: {
630 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
631 }
632 }
633
634 static func stamp(_ date: Date) -> String {
635 let formatter = DateFormatter()
636 formatter.locale = Locale(identifier: "en_US_POSIX")
637 formatter.dateFormat = "yyyy-MM-dd"
638 return formatter.string(from: date)
639 }
640}
641
642/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
643/// A src block's code is highlighted as its language.
644struct BlockEditSheet: View {
645 let edit: BlockEdit
646 let theme: MobileTheme
647 let finish: (String?) -> Void
648 @State private var text: String?
649
650 var body: some View {
651 NavigationStack {
652 Group {
653 if let text {
654 CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
655 }
656 }
657 .padding(.horizontal, 8)
658 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
659 .navigationBarTitleDisplayMode(.inline)
660 .toolbar {
661 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
662 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
663 }
664 }
665 .onAppear { text = edit.content }
666 }
667}
668
669/// A text view for code, restyled with the editor's highlighter after each change.
670struct CodeTextView: UIViewRepresentable {
671 let text: String
672 let language: String?
673 let theme: MobileTheme
674 let changed: (String) -> Void
675
676 func makeUIView(context: Context) -> UITextView {
677 let view = UITextView()
678 view.autocorrectionType = .no
679 view.autocapitalizationType = .none
680 view.smartQuotesType = .no
681 view.smartDashesType = .no
682 view.spellCheckingType = .no
683 view.keyboardDismissMode = .interactive
684 view.backgroundColor = .clear
685 view.text = text
686 view.delegate = context.coordinator
687 context.coordinator.style(view)
688 DispatchQueue.main.async { view.becomeFirstResponder() }
689 return view
690 }
691
692 func updateUIView(_ view: UITextView, context: Context) {
693 context.coordinator.parent = self
694 }
695
696 func makeCoordinator() -> Coordinator { Coordinator(self) }
697
698 @MainActor
699 final class Coordinator: NSObject, UITextViewDelegate {
700 var parent: CodeTextView
701 init(_ parent: CodeTextView) { self.parent = parent }
702
703 func textViewDidChange(_ view: UITextView) {
704 parent.changed(view.text)
705 style(view)
706 }
707
708 /// The theme's font and color, then the language's token colors.
709 func style(_ view: UITextView) {
710 let storage = view.textStorage
711 let whole = NSRange(location: 0, length: storage.length)
712 let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
713 storage.beginEditing()
714 storage.setAttributes(base, range: whole)
715 if let language = parent.language {
716 for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
717 guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
718 storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
719 }
720 }
721 storage.endEditing()
722 view.typingAttributes = base
723 }
724 }
725}
726
727/// Every command that applies at the caret, by name.
728struct CommandPalette: View {
729 let editor: MobileEditor
730 /// Called with the chosen command before the palette closes.
731 let choose: (String) -> Void
732 @State private var query = ""
733 @Environment(\.dismiss) private var dismiss
734
735 private static let viewCommands: [(id: String, title: String)] = [
736 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
737 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
738 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
739 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
740 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
741 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
742 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
743 ("app.toggle-markup", "Show or Hide Markup"),
744 ("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"),
745 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
746 ("org.table.expand", "Expand Table Columns"),
747 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
748 ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
749 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
750 ("app.attach.attach", "Attach File…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
751 ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
752 ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
753 ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
754 ]
755
756 /// The commands that apply at the caret and their keys, worked out once when the palette
757 /// opens rather than on every keystroke in the search field.
758 @State private var applicable: [(id: String, title: String, keys: String?)]?
759
760 var body: some View {
761 let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
762 NavigationStack {
763 List(shown, id: \.id) { command in
764 Button {
765 choose(command.id)
766 dismiss()
767 } label: {
768 HStack {
769 Text(command.title).foregroundStyle(.primary)
770 Spacer()
771 if let keys = command.keys {
772 Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
773 }
774 }
775 }
776 }
777 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
778 .navigationTitle("Commands")
779 .navigationBarTitleDisplayMode(.inline)
780 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
781 }
782 .onAppear {
783 guard applicable == nil else { return }
784 let context = editor.editContext()
785 applicable = (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) })
786 .filter { editor.applies($0.id, in: context) }
787 .map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) }
788 }
789 }
790}
791/// A table as CSV or TSV, for the save dialog.
792struct TableFile: FileDocument {
793 static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
794 let text: String
795 let type: UTType
796
797 init(text: String, type: UTType) {
798 self.text = text
799 self.type = type
800 }
801
802 init(configuration: ReadConfiguration) throws {
803 text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
804 type = configuration.contentType
805 }
806
807 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
808 FileWrapper(regularFileWithContents: Data(text.utf8))
809 }
810}
811/// A plotted table, as the Mac's plot sheet shows it.
812struct PlotScreen: View {
813 let plot: TablePlot.Plot
814 @Environment(\.dismiss) private var dismiss
815
816 var body: some View {
817 NavigationStack {
818 PlotChart(plot)
819 .navigationTitle("Plot")
820 .navigationBarTitleDisplayMode(.inline)
821 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
822 }
823 }
824}
825/// A file from the photo picker, copied out of the picker's temporary place with its name.
826struct PickedFile: Transferable {
827 let url: URL
828
829 static var transferRepresentation: some TransferRepresentation {
830 FileRepresentation(importedContentType: .item) { received in
831 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
832 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
833 let url = folder.appendingPathComponent(received.file.lastPathComponent)
834 try FileManager.default.copyItem(at: received.file, to: url)
835 return PickedFile(url: url)
836 }
837 }
838}
839
840/// The passphrase sheet for org-crypt, its new text applied in the editor.
841struct CryptScreen: View {
842 let request: CryptRequest
843 let session: DocumentSession
844 let editor: MobileEditor?
845 let report: (String) -> Void
846 @Environment(\.dismiss) private var dismiss
847
848 var body: some View {
849 NavigationStack {
850 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
851 dismiss()
852 if let message { report(message) }
853 }
854 .navigationBarTitleDisplayMode(.inline)
855 }
856 }
857
858 private func apply(_ new: String) {
859 guard let editor else { return }
860 let context = editor.editContext()
861 let caret = min(context.caret, (new as NSString).length)
862 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
863 }
864}
865#endif