Sources/OrgstarMobile/EditorScreen.swift
402 lines · 17457 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 @Environment(ClockModel.self) private var clock
21 @Environment(MobileModel.self) private var model
22 @Environment(\.openURL) private var openURL
23
24 struct PromptRequest: Identifiable {
25 let id = UUID()
26 let prompt: Prompt
27 let reply: (String?) -> Void
28 }
29
30 /// One sheet at a time: two presenters on this screen interfere.
31 enum Sheet: Identifiable {
32 case palette, conflict, syncCopies, recovery
33 case block(BlockEdit)
34
35 var id: String {
36 switch self {
37 case .palette: "palette"
38 case .conflict: "conflict"
39 case .syncCopies: "syncCopies"
40 case .recovery: "recovery"
41 case .block(let edit): "block \(edit.range)"
42 }
43 }
44 }
45
46 var body: some View {
47 Group {
48 if let editor {
49 EditorTextView(editor: editor, palette: { sheet = .palette })
50 .ignoresSafeArea(.container, edges: .bottom)
51 } else {
52 ProgressView()
53 }
54 }
55 .navigationTitle((path as NSString).lastPathComponent + (session.dirtyPaths.contains(path) ? " •" : ""))
56 .navigationBarTitleDisplayMode(.inline)
57 .toolbar(.hidden, for: .tabBar)
58 .toolbar {
59 ToolbarItemGroup(placement: .primaryAction) {
60 if session.conflict != nil {
61 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
62 }
63 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
64 Menu("More", systemImage: "ellipsis.circle") {
65 Button("Commands", systemImage: "command") { sheet = .palette }
66 Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
67 if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) }
68 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
69 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
70 }
71 }
72 }
73 .safeAreaInset(edge: .top) {
74 if let message {
75 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
76 .onTapGesture { self.message = nil }
77 .task(id: message) {
78 try? await Task.sleep(for: .seconds(4))
79 if self.message == message { self.message = nil }
80 }
81 }
82 }
83 .sheet(item: $prompt) { request in
84 PromptSheet(prompt: request.prompt) { answer in
85 prompt = nil
86 request.reply(answer)
87 }
88 }
89 .sheet(item: $sheet) { sheet in
90 switch sheet {
91 case .palette: if let editor { CommandPalette(editor: editor) }
92 case .conflict: ConflictSheet(session: session)
93 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
94 case .recovery: RecoverySheet(session: session) { message = $0 }
95 case .block(let edit):
96 BlockEditSheet(edit: edit) { content in
97 self.sheet = nil
98 if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
99 }
100 }
101 }
102 .onChange(of: session.conflict) { _, conflict in
103 if conflict != nil, session.path == path { sheet = .conflict }
104 }
105 .onChange(of: session.lastError) { _, error in
106 if let error { message = error; session.lastError = nil }
107 }
108 .onAppear(perform: start)
109 .onChange(of: session.revealRequest?.id) {
110 if let offset = session.revealRequest?.offset, session.path == path { editor?.reveal(offset) }
111 }
112 .onDisappear {
113 // Typing the reader shows next, and a save, don't wait for the autosave delay.
114 if session.dirtyPaths.contains(path) { _ = session.save(path) }
115 }
116 }
117
118 private func start() {
119 if session.path != path { session.open(path) }
120 if editor == nil, let document = session.document {
121 let editor = MobileEditor(document: document, editable: document.isEditable)
122 editor.options = session.options
123 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
124 editor.onChange = { [weak session] in session?.bufferChanged(path) }
125 editor.onMessage = { message = $0 }
126 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
127 editor.onLink = { link in
128 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
129 case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")"
130 case .openExternally(let url): openURL(url)
131 case .message(let text): message = text
132 }
133 }
134 editor.onEditBlock = { edit in sheet = .block(edit) }
135 editor.onTangle = { scope in message = session.tangle(scope) }
136 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
137 editor.onAppCommand = { id in
138 switch id {
139 case "app.clock.in": message = clock.clockIn(session)
140 case "app.clock.out": message = clock.clockOut(session)
141 case "app.clock.cancel": message = clock.clockOut(session, cancel: true)
142 case "app.clock.goto":
143 if let location = clock.location(session) { model.openRequest = .offset(location.path, location.offset) } else { message = "No active clock" }
144 default: message = "Not available on iOS yet"
145 }
146 }
147 self.editor = editor
148 }
149 if let editor { session.attach(editor) }
150 if let offset { editor?.reveal(offset) }
151 if session.conflict != nil {
152 sheet = .conflict
153 } else if case let copies = session.syncConflictCopies().count, copies > 0 {
154 message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
155 }
156 }
157}
158
159/// The editor's text view, with the Org key bar over the keyboard.
160struct EditorTextView: UIViewRepresentable {
161 let editor: MobileEditor
162 let palette: () -> Void
163
164 func makeUIView(context: Context) -> UITextView {
165 let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
166 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
167 bar.view.backgroundColor = .clear
168 bar.sizingOptions = []
169 editor.textView.inputAccessoryView = bar.view
170 context.coordinator.bar = bar
171 return editor.textView
172 }
173
174 func updateUIView(_ view: UITextView, context: Context) {}
175
176 func makeCoordinator() -> Coordinator { Coordinator() }
177
178 final class Coordinator {
179 var bar: UIViewController?
180 }
181}
182
183/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
184/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
185struct KeyBar: View {
186 let editor: MobileEditor
187 let palette: () -> Void
188
189 private static let keys: [(label: String, symbol: String?, keys: String)] = [
190 ("Fold", "arrow.right.to.line", "TAB"),
191 ("Overview", "arrow.left.to.line", "S-TAB"),
192 ("Promote", "arrow.left", "M-<left>"),
193 ("Demote", "arrow.right", "M-<right>"),
194 ("Move up", "arrow.up", "M-<up>"),
195 ("Move down", "arrow.down", "M-<down>"),
196 ("New heading or item", "plus", "M-RET"),
197 ("TODO", nil, "C-c C-t"),
198 ("Act at point", "checkmark.square", "C-c C-c"),
199 ("Schedule", "calendar", "C-c C-s"),
200 ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
201 ("Tags", "tag", "C-c C-q"),
202 ("Open link", "link", "C-c C-o"),
203 ]
204
205 var body: some View {
206 ScrollView(.horizontal, showsIndicators: false) {
207 HStack(spacing: 4) {
208 Button("Commands", systemImage: "command", action: palette)
209 ForEach(Self.keys, id: \.keys) { key in
210 Button {
211 editor.run(keys: key.keys)
212 } label: {
213 if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
214 }
215 .accessibilityLabel(key.label)
216 }
217 Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
218 }
219 .labelStyle(.iconOnly)
220 .buttonStyle(.bordered)
221 .padding(.horizontal, 8)
222 .padding(.vertical, 6)
223 }
224 .background(.bar)
225 }
226}
227
228/// A command's question: text with choices, a date, or fast selection by keys.
229struct PromptSheet: View {
230 let prompt: Prompt
231 let answer: (String?) -> Void
232 @State private var text = ""
233 @State private var date = Date()
234 @State private var keys: [FastSelection.Input] = []
235
236 var body: some View {
237 NavigationStack {
238 Form {
239 if let fast = prompt.fast {
240 fastSection(fast)
241 } else {
242 Section {
243 TextField(prompt.message, text: $text)
244 .autocorrectionDisabled()
245 .textInputAutocapitalization(.never)
246 .onSubmit { answer(text) }
247 } footer: {
248 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
249 }
250 if prompt.date != nil {
251 DatePicker("Date", selection: $date, displayedComponents: [.date])
252 .datePickerStyle(.graphical)
253 .onChange(of: date) { text = Self.stamp(date) }
254 }
255 if !prompt.choices.isEmpty {
256 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
257 Section("Choices") {
258 ForEach(matching.prefix(50), id: \.self) { choice in
259 Button(choice) { choose(choice) }
260 }
261 }
262 }
263 }
264 }
265 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
266 .navigationBarTitleDisplayMode(.inline)
267 .toolbar {
268 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
269 if prompt.fast == nil || prompt.fast?.multiple == true {
270 ToolbarItem(placement: .confirmationAction) {
271 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
272 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
273 }
274 }
275 }
276 }
277 .onAppear {
278 text = prompt.initial
279 if let day = prompt.date?.defaultDate { date = day }
280 }
281 }
282
283 /// With a separator (tags), what's typed after the last one.
284 private var lastPart: String {
285 guard let separator = prompt.completionSeparator else { return text }
286 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
287 }
288
289 private func choose(_ choice: String) {
290 guard let separator = prompt.completionSeparator else {
291 text = choice
292 if prompt.date == nil { answer(choice) }
293 return
294 }
295 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
296 if parts.isEmpty { parts = [""] }
297 parts[parts.count - 1] = choice
298 text = parts.joined(separator: String(separator)) + String(separator)
299 }
300
301 @ViewBuilder
302 private func fastSection(_ fast: FastSelection) -> some View {
303 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
304 Section {
305 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
306 Button {
307 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
308 } label: {
309 HStack {
310 Text(option.name).foregroundStyle(.primary)
311 Spacer()
312 if current.contains(option.name) { Image(systemName: "checkmark") }
313 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
314 }
315 }
316 }
317 if !fast.multiple {
318 Button("No keyword") { answer(" ") }
319 }
320 } footer: {
321 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
322 }
323 }
324
325 static func stamp(_ date: Date) -> String {
326 let formatter = DateFormatter()
327 formatter.locale = Locale(identifier: "en_US_POSIX")
328 formatter.dateFormat = "yyyy-MM-dd"
329 return formatter.string(from: date)
330 }
331}
332
333/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
334struct BlockEditSheet: View {
335 let edit: BlockEdit
336 let finish: (String?) -> Void
337 @State private var text = ""
338 @FocusState private var focused: Bool
339
340 var body: some View {
341 NavigationStack {
342 TextEditor(text: $text)
343 .font(.body.monospaced())
344 .autocorrectionDisabled()
345 .textInputAutocapitalization(.never)
346 .focused($focused)
347 .padding(.horizontal, 8)
348 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
349 .navigationBarTitleDisplayMode(.inline)
350 .toolbar {
351 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
352 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text) } }
353 }
354 }
355 .onAppear {
356 text = edit.content
357 focused = true
358 }
359 }
360}
361
362/// Every command that applies at the caret, by name.
363struct CommandPalette: View {
364 let editor: MobileEditor
365 @State private var query = ""
366 @Environment(\.dismiss) private var dismiss
367
368 private static let viewCommands: [(id: String, title: String)] = [
369 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
370 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
371 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
372 ("app.clock.goto", "Go to Clocked Entry"),
373 ]
374
375 var body: some View {
376 let context = editor.editContext()
377 let all = Self.viewCommands + Commands.everything.map { ($0.id, $0.title) }
378 let shown = all.filter { editor.applies($0.id, in: context) && (query.isEmpty || $0.title.localizedCaseInsensitiveContains(query)) }
379 NavigationStack {
380 List(shown, id: \.id) { command in
381 Button {
382 dismiss()
383 // After the sheet goes, so a command's own prompt can show.
384 DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { editor.run(command.id) }
385 } label: {
386 HStack {
387 Text(command.title).foregroundStyle(.primary)
388 Spacer()
389 if let keys = editor.keymap.keyLabels(for: command.id).first {
390 Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
391 }
392 }
393 }
394 }
395 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
396 .navigationTitle("Commands")
397 .navigationBarTitleDisplayMode(.inline)
398 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
399 }
400 }
401}
402#endif