Sources/OrgstarMobile/EditorScreen.swift
590 lines · 26725 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import SwiftUI
6import UIKit
7
8/// Editing a file: the text with Org's folding and styling, a bar of Org keys over the keyboard,
9/// and every command in a palette. The editor is the open file's live state, so autosave and
10/// merging go through the session as on the Mac.
11struct EditorScreen: View {
12 let path: String
13 let offset: Int?
14 let workspace: WorkspaceModel
15 let session: DocumentSession
16 @State private var editor: MobileEditor?
17 @State private var prompt: PromptRequest?
18 @State private var message: String?
19 @State private var sheet: Sheet?
20 @State private var trust = TrustStore()
21 /// The command chosen in the palette, run once the palette is gone.
22 @State private var chosen: String?
23 @Environment(ClockModel.self) private var clock
24 @Environment(MobileModel.self) private var model
25 @Environment(\.openURL) private var openURL
26
27 /// The session's options with `buffer-file-name` and the agenda files, for clock tables.
28 private var editorOptions: EditingOptions {
29 var options = session.options
30 options.filePath = path
31 options.agendaFiles = workspace.agendaFilePaths()
32 return options
33 }
34
35 struct PromptRequest: Identifiable {
36 let id = UUID()
37 let prompt: Prompt
38 let reply: (String?) -> Void
39 }
40
41 /// One sheet at a time: two presenters on this screen interfere.
42 enum Sheet: Identifiable {
43 case palette, conflict, syncCopies, recovery
44 /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
45 case refile(String)
46 case block(BlockEdit)
47 case columns(ColumnView.View)
48
49 var id: String {
50 switch self {
51 case .palette: "palette"
52 case .refile(let command): command
53 case .conflict: "conflict"
54 case .syncCopies: "syncCopies"
55 case .recovery: "recovery"
56 case .block(let edit): "block \(edit.range)"
57 case .columns: "columns"
58 }
59 }
60 }
61
62 var body: some View {
63 Group {
64 if let editor {
65 EditorTextView(editor: editor, palette: { sheet = .palette })
66 .ignoresSafeArea(.container, edges: .bottom)
67 } else {
68 ProgressView()
69 }
70 }
71 .navigationTitle(session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""))
72 .navigationBarTitleDisplayMode(.inline)
73 .toolbar(.hidden, for: .tabBar)
74 .toolbar {
75 ToolbarItemGroup(placement: .primaryAction) {
76 if session.conflict != nil {
77 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
78 }
79 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
80 Menu("More", systemImage: "ellipsis.circle") {
81 Button("Commands", systemImage: "command") { sheet = .palette }
82 Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
83 Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") }
84 Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") }
85 Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) {
86 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
87 }
88 RecentClockMenu(clock: clock) { editor?.run($0) }
89 if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) { message = $0 } }
90 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
91 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
92 }
93 }
94 }
95 .safeAreaInset(edge: .top) {
96 if let message {
97 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
98 .onTapGesture { self.message = nil }
99 .task(id: message) {
100 try? await Task.sleep(for: .seconds(4))
101 if self.message == message { self.message = nil }
102 }
103 }
104 }
105 .sheet(item: $prompt) { request in
106 PromptSheet(prompt: request.prompt) { answer in
107 prompt = nil
108 request.reply(answer)
109 }
110 }
111 .sheet(item: $sheet, onDismiss: {
112 // After the sheet has gone, so a command's own prompt can show.
113 if let id = chosen {
114 chosen = nil
115 editor?.run(id)
116 }
117 }) { sheet in
118 switch sheet {
119 case .palette: if let editor { CommandPalette(editor: editor) { chosen = $0 } }
120 case .conflict: ConflictSheet(session: session)
121 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
122 case .recovery: RecoverySheet(session: session) { message = $0 }
123 case .refile(let command):
124 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
125 create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
126 self.sheet = nil
127 switch session.createRefileChild(under: parent, title: child) {
128 case .success(let target):
129 guard let path = session.path, let editor else { return }
130 message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
131 case .failure(.message(let text)): message = text
132 }
133 }) { target in
134 self.sheet = nil
135 guard let target else { return }
136 if command == "app.refile.goto" {
137 model.openRequest = .offset(target.path, target.start ?? Int.max)
138 } else {
139 refile(to: target, keep: command == "app.refile.copy")
140 }
141 }
142 case .block(let edit):
143 BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
144 self.sheet = nil
145 if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
146 }
147 case .columns(let view):
148 ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
149 }
150 }
151 .onChange(of: session.conflict) { _, conflict in
152 if conflict != nil, session.path == path { sheet = .conflict }
153 }
154 .onChange(of: session.lastError) { _, error in
155 if let error { message = error; session.lastError = nil }
156 }
157 .onAppear(perform: start)
158 .onChange(of: session.revealRequest?.id) {
159 if let offset = session.revealRequest?.offset, session.path == path { editor?.reveal(offset) }
160 }
161 .onChange(of: model.settingsVersion) {
162 editor?.options = editorOptions
163 editor?.themeSpec = model.theme
164 editor?.keymap = model.keymap
165 editor?.modal = model.modalKeys
166 }
167 .onChange(of: model.showMarkup) { editor?.showMarkup = model.showMarkup }
168 .onDisappear {
169 // Typing the reader shows next, and a save, don't wait for the autosave delay.
170 if session.dirtyPaths.contains(path) { _ = session.save(path) }
171 }
172 }
173
174 /// Store Link, Store ID Link and Insert Link, with the links stored while the app runs.
175 private func link(_ id: String) {
176 guard let editor else { return }
177 switch id {
178 case "org.link.store":
179 message = StoredLink.add(Links.store(in: editor.editContext(), path: Links.abbreviate(path, home: NSHomeDirectory())), to: &model.storedLinks)
180 case "org.id.store-link":
181 if case .commit = editor.perform(CreateID()),
182 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
183 message = StoredLink.add(link, to: &model.storedLinks)
184 }
185 default:
186 _ = editor.perform(InsertLink(stored: model.storedLinks, file: path))
187 }
188 }
189
190 /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
191 private func run(_ job: BabelJob) {
192 let go = {
193 message = "Running \(job.language) block…"
194 session.startBabel(job) { message = $0 }
195 }
196 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
197 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
198 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
199 switch answer {
200 case "always":
201 trust.trust(path: path, content: job.blockText)
202 go()
203 case "yes": go()
204 default: message = "Not run"
205 }
206 }
207 }
208
209 private func start() {
210 if session.path != path { session.open(path) }
211 if editor == nil, let document = session.document {
212 let editor = MobileEditor(
213 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
214 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
215 )
216 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
217 editor.onChange = { [weak session] in session?.bufferChanged(path) }
218 editor.onMessage = { message = $0 }
219 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
220 editor.onLink = { link in
221 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
222 case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")"
223 case .openExternally(let url): openURL(url)
224 case .message(let text): message = text
225 }
226 }
227 editor.onEditBlock = { edit in sheet = .block(edit) }
228 editor.onColumnView = { view in sheet = .columns(view) }
229 editor.onTangle = { scope in message = session.tangle(scope) }
230 editor.onBabel = { job in run(job) }
231 editor.onRefreshSetup = { session.refreshSetup() }
232 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
233 editor.keymap = model.keymap
234 editor.modal = model.modalKeys
235 editor.onAppCommand = { id in
236 if id == "app.save" {
237 _ = session.save(path)
238 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
239 sheet = .refile(id)
240 } else if id == "app.toggle-markup" {
241 model.showMarkup.toggle()
242 } else if MobileEditor.linkCommands.contains(id) {
243 link(id)
244 } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
245 message = "Not available on iOS yet"
246 }
247 }
248 self.editor = editor
249 }
250 if let editor { session.attach(editor) }
251 if let offset { editor?.reveal(offset) }
252 if session.conflict != nil {
253 sheet = .conflict
254 } else if case let copies = session.syncConflictCopies().count, copies > 0 {
255 message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
256 }
257 }
258}
259
260extension EditorScreen {
261 /// `org-refile` of the entry at the caret, to a target worked out again from the files
262 /// now, as the agenda's Refile… does.
263 func refile(to target: RefileTarget, keep: Bool = false) {
264 guard let editor, let path = session.path else { return }
265 let caret = editor.editContext().caret
266 guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
267 message = "Can't find \(target.label) any more."
268 return
269 }
270 message = session.refile(to: current, from: (path, caret), keep: keep)
271 }
272}
273
274/// The editor's text view, with the Org key bar over the keyboard.
275struct EditorTextView: UIViewRepresentable {
276 let editor: MobileEditor
277 let palette: () -> Void
278
279 func makeUIView(context: Context) -> UITextView {
280 let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
281 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
282 bar.view.backgroundColor = .clear
283 bar.sizingOptions = []
284 editor.textView.inputAccessoryView = bar.view
285 context.coordinator.bar = bar
286 return editor.textView
287 }
288
289 func updateUIView(_ view: UITextView, context: Context) {}
290
291 func makeCoordinator() -> Coordinator { Coordinator() }
292
293 final class Coordinator {
294 var bar: UIViewController?
295 }
296}
297
298/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
299/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
300struct KeyBar: View {
301 let editor: MobileEditor
302 let palette: () -> Void
303
304 private static let keys: [(label: String, symbol: String?, keys: String)] = [
305 ("Fold", "arrow.right.to.line", "TAB"),
306 ("Overview", "arrow.left.to.line", "S-TAB"),
307 ("Promote", "arrow.left", "M-<left>"),
308 ("Demote", "arrow.right", "M-<right>"),
309 ("Move up", "arrow.up", "M-<up>"),
310 ("Move down", "arrow.down", "M-<down>"),
311 ("New heading or item", "plus", "M-RET"),
312 ("TODO", nil, "C-c C-t"),
313 ("Act at point", "checkmark.square", "C-c C-c"),
314 ("Schedule", "calendar", "C-c C-s"),
315 ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
316 ("Tags", "tag", "C-c C-q"),
317 ("Open link", "link", "C-c C-o"),
318 ]
319
320 var body: some View {
321 ScrollView(.horizontal, showsIndicators: false) {
322 HStack(spacing: 4) {
323 Button("Commands", systemImage: "command", action: palette)
324 ForEach(Self.keys, id: \.keys) { key in
325 Button {
326 editor.run(keys: key.keys)
327 } label: {
328 if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
329 }
330 .accessibilityLabel(key.label)
331 }
332 Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
333 }
334 .labelStyle(.iconOnly)
335 .buttonStyle(.bordered)
336 .padding(.horizontal, 8)
337 .padding(.vertical, 6)
338 }
339 .background(.bar)
340 }
341}
342
343/// A command's question: text with choices, a date, or fast selection by keys.
344struct PromptSheet: View {
345 let prompt: Prompt
346 let answer: (String?) -> Void
347 @State private var text = ""
348 @State private var date = Date()
349 @State private var keys: [FastSelection.Input] = []
350
351 var body: some View {
352 NavigationStack {
353 Form {
354 if let fast = prompt.fast {
355 fastSection(fast)
356 } else {
357 Section {
358 TextField(prompt.message, text: $text)
359 .autocorrectionDisabled()
360 .textInputAutocapitalization(.never)
361 .onSubmit { answer(text) }
362 } footer: {
363 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
364 }
365 if prompt.date != nil {
366 DatePicker("Date", selection: $date, displayedComponents: [.date])
367 .datePickerStyle(.graphical)
368 .onChange(of: date) { text = Self.stamp(date) }
369 }
370 if !prompt.choices.isEmpty {
371 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
372 Section("Choices") {
373 ForEach(matching.prefix(50), id: \.self) { choice in
374 Button(choice) { choose(choice) }
375 }
376 }
377 }
378 }
379 }
380 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
381 .navigationBarTitleDisplayMode(.inline)
382 .toolbar {
383 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
384 if prompt.fast == nil || prompt.fast?.multiple == true {
385 ToolbarItem(placement: .confirmationAction) {
386 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
387 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
388 }
389 }
390 }
391 }
392 .onAppear {
393 text = prompt.initial
394 if let day = prompt.date?.defaultDate { date = day }
395 }
396 }
397
398 /// With a separator (tags), what's typed after the last one.
399 private var lastPart: String {
400 guard let separator = prompt.completionSeparator else { return text }
401 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
402 }
403
404 private func choose(_ choice: String) {
405 guard let separator = prompt.completionSeparator else {
406 text = choice
407 if prompt.date == nil { answer(choice) }
408 return
409 }
410 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
411 if parts.isEmpty { parts = [""] }
412 parts[parts.count - 1] = choice
413 text = parts.joined(separator: String(separator)) + String(separator)
414 }
415
416 @ViewBuilder
417 private func fastSection(_ fast: FastSelection) -> some View {
418 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
419 Section {
420 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
421 Button {
422 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
423 } label: {
424 HStack {
425 Text(option.name).foregroundStyle(.primary)
426 Spacer()
427 if current.contains(option.name) { Image(systemName: "checkmark") }
428 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
429 }
430 }
431 }
432 if !fast.multiple {
433 Button("No keyword") { answer(" ") }
434 }
435 } footer: {
436 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
437 }
438 }
439
440 static func stamp(_ date: Date) -> String {
441 let formatter = DateFormatter()
442 formatter.locale = Locale(identifier: "en_US_POSIX")
443 formatter.dateFormat = "yyyy-MM-dd"
444 return formatter.string(from: date)
445 }
446}
447
448/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
449/// A src block's code is highlighted as its language.
450struct BlockEditSheet: View {
451 let edit: BlockEdit
452 let theme: MobileTheme
453 let finish: (String?) -> Void
454 @State private var text: String?
455
456 var body: some View {
457 NavigationStack {
458 Group {
459 if let text {
460 CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
461 }
462 }
463 .padding(.horizontal, 8)
464 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
465 .navigationBarTitleDisplayMode(.inline)
466 .toolbar {
467 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
468 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
469 }
470 }
471 .onAppear { text = edit.content }
472 }
473}
474
475/// A text view for code, restyled with the editor's highlighter after each change.
476struct CodeTextView: UIViewRepresentable {
477 let text: String
478 let language: String?
479 let theme: MobileTheme
480 let changed: (String) -> Void
481
482 func makeUIView(context: Context) -> UITextView {
483 let view = UITextView()
484 view.autocorrectionType = .no
485 view.autocapitalizationType = .none
486 view.smartQuotesType = .no
487 view.smartDashesType = .no
488 view.spellCheckingType = .no
489 view.keyboardDismissMode = .interactive
490 view.backgroundColor = .clear
491 view.text = text
492 view.delegate = context.coordinator
493 context.coordinator.style(view)
494 DispatchQueue.main.async { view.becomeFirstResponder() }
495 return view
496 }
497
498 func updateUIView(_ view: UITextView, context: Context) {
499 context.coordinator.parent = self
500 }
501
502 func makeCoordinator() -> Coordinator { Coordinator(self) }
503
504 @MainActor
505 final class Coordinator: NSObject, UITextViewDelegate {
506 var parent: CodeTextView
507 init(_ parent: CodeTextView) { self.parent = parent }
508
509 func textViewDidChange(_ view: UITextView) {
510 parent.changed(view.text)
511 style(view)
512 }
513
514 /// The theme's font and color, then the language's token colors.
515 func style(_ view: UITextView) {
516 let storage = view.textStorage
517 let whole = NSRange(location: 0, length: storage.length)
518 let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
519 storage.beginEditing()
520 storage.setAttributes(base, range: whole)
521 if let language = parent.language {
522 for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
523 guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
524 storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
525 }
526 }
527 storage.endEditing()
528 view.typingAttributes = base
529 }
530 }
531}
532
533/// Every command that applies at the caret, by name.
534struct CommandPalette: View {
535 let editor: MobileEditor
536 /// Called with the chosen command before the palette closes.
537 let choose: (String) -> Void
538 @State private var query = ""
539 @Environment(\.dismiss) private var dismiss
540
541 private static let viewCommands: [(id: String, title: String)] = [
542 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
543 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
544 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
545 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
546 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
547 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
548 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
549 ("app.toggle-markup", "Show or Hide Markup"),
550 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"),
551 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
552 ("org.table.expand", "Expand Table Columns"),
553 ]
554
555 /// The commands that apply at the caret and their keys, worked out once when the palette
556 /// opens rather than on every keystroke in the search field.
557 @State private var applicable: [(id: String, title: String, keys: String?)]?
558
559 var body: some View {
560 let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
561 NavigationStack {
562 List(shown, id: \.id) { command in
563 Button {
564 choose(command.id)
565 dismiss()
566 } label: {
567 HStack {
568 Text(command.title).foregroundStyle(.primary)
569 Spacer()
570 if let keys = command.keys {
571 Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
572 }
573 }
574 }
575 }
576 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
577 .navigationTitle("Commands")
578 .navigationBarTitleDisplayMode(.inline)
579 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
580 }
581 .onAppear {
582 guard applicable == nil else { return }
583 let context = editor.editContext()
584 applicable = (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) })
585 .filter { editor.applies($0.id, in: context) }
586 .map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) }
587 }
588 }
589}
590#endif