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