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