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