Sources/OrgstarMobile/EditorScreen.swift

d32d29c0620e94a09a204185d1a2004a8d58c518
orgstar/Sources/OrgstarMobile/EditorScreen.swift history · blame · raw

401 lines · 17382 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.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
136            editor.onAppCommand = { id in
137                switch id {
138                case "app.clock.in": message = clock.clockIn(session)
139                case "app.clock.out": message = clock.clockOut(session)
140                case "app.clock.cancel": message = clock.clockOut(session, cancel: true)
141                case "app.clock.goto":
142                    if let location = clock.location(session) { model.openRequest = .offset(location.path, location.offset) } else { message = "No active clock" }
143                default: message = "Not available on iOS yet"
144                }
145            }
146            self.editor = editor
147        }
148        if let editor { session.attach(editor) }
149        if let offset { editor?.reveal(offset) }
150        if session.conflict != nil {
151            sheet = .conflict
152        } else if case let copies = session.syncConflictCopies().count, copies > 0 {
153            message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
154        }
155    }
156}
157
158/// The editor's text view, with the Org key bar over the keyboard.
159struct EditorTextView: UIViewRepresentable {
160    let editor: MobileEditor
161    let palette: () -> Void
162
163    func makeUIView(context: Context) -> UITextView {
164        let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
165        bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
166        bar.view.backgroundColor = .clear
167        bar.sizingOptions = []
168        editor.textView.inputAccessoryView = bar.view
169        context.coordinator.bar = bar
170        return editor.textView
171    }
172
173    func updateUIView(_ view: UITextView, context: Context) {}
174
175    func makeCoordinator() -> Coordinator { Coordinator() }
176
177    final class Coordinator {
178        var bar: UIViewController?
179    }
180}
181
182/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
183/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
184struct KeyBar: View {
185    let editor: MobileEditor
186    let palette: () -> Void
187
188    private static let keys: [(label: String, symbol: String?, keys: String)] = [
189        ("Fold", "arrow.right.to.line", "TAB"),
190        ("Overview", "arrow.left.to.line", "S-TAB"),
191        ("Promote", "arrow.left", "M-<left>"),
192        ("Demote", "arrow.right", "M-<right>"),
193        ("Move up", "arrow.up", "M-<up>"),
194        ("Move down", "arrow.down", "M-<down>"),
195        ("New heading or item", "plus", "M-RET"),
196        ("TODO", nil, "C-c C-t"),
197        ("Act at point", "checkmark.square", "C-c C-c"),
198        ("Schedule", "calendar", "C-c C-s"),
199        ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
200        ("Tags", "tag", "C-c C-q"),
201        ("Open link", "link", "C-c C-o"),
202    ]
203
204    var body: some View {
205        ScrollView(.horizontal, showsIndicators: false) {
206            HStack(spacing: 4) {
207                Button("Commands", systemImage: "command", action: palette)
208                ForEach(Self.keys, id: \.keys) { key in
209                    Button {
210                        editor.run(keys: key.keys)
211                    } label: {
212                        if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
213                    }
214                    .accessibilityLabel(key.label)
215                }
216                Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
217            }
218            .labelStyle(.iconOnly)
219            .buttonStyle(.bordered)
220            .padding(.horizontal, 8)
221            .padding(.vertical, 6)
222        }
223        .background(.bar)
224    }
225}
226
227/// A command's question: text with choices, a date, or fast selection by keys.
228struct PromptSheet: View {
229    let prompt: Prompt
230    let answer: (String?) -> Void
231    @State private var text = ""
232    @State private var date = Date()
233    @State private var keys: [FastSelection.Input] = []
234
235    var body: some View {
236        NavigationStack {
237            Form {
238                if let fast = prompt.fast {
239                    fastSection(fast)
240                } else {
241                    Section {
242                        TextField(prompt.message, text: $text)
243                            .autocorrectionDisabled()
244                            .textInputAutocapitalization(.never)
245                            .onSubmit { answer(text) }
246                    } footer: {
247                        if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
248                    }
249                    if prompt.date != nil {
250                        DatePicker("Date", selection: $date, displayedComponents: [.date])
251                            .datePickerStyle(.graphical)
252                            .onChange(of: date) { text = Self.stamp(date) }
253                    }
254                    if !prompt.choices.isEmpty {
255                        let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
256                        Section("Choices") {
257                            ForEach(matching.prefix(50), id: \.self) { choice in
258                                Button(choice) { choose(choice) }
259                            }
260                        }
261                    }
262                }
263            }
264            .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
265            .navigationBarTitleDisplayMode(.inline)
266            .toolbar {
267                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
268                if prompt.fast == nil || prompt.fast?.multiple == true {
269                    ToolbarItem(placement: .confirmationAction) {
270                        Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
271                            .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
272                    }
273                }
274            }
275        }
276        .onAppear {
277            text = prompt.initial
278            if let day = prompt.date?.defaultDate { date = day }
279        }
280    }
281
282    /// With a separator (tags), what's typed after the last one.
283    private var lastPart: String {
284        guard let separator = prompt.completionSeparator else { return text }
285        return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
286    }
287
288    private func choose(_ choice: String) {
289        guard let separator = prompt.completionSeparator else {
290            text = choice
291            if prompt.date == nil { answer(choice) }
292            return
293        }
294        var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
295        if parts.isEmpty { parts = [""] }
296        parts[parts.count - 1] = choice
297        text = parts.joined(separator: String(separator)) + String(separator)
298    }
299
300    @ViewBuilder
301    private func fastSection(_ fast: FastSelection) -> some View {
302        let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
303        Section {
304            ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
305                Button {
306                    if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
307                } label: {
308                    HStack {
309                        Text(option.name).foregroundStyle(.primary)
310                        Spacer()
311                        if current.contains(option.name) { Image(systemName: "checkmark") }
312                        Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
313                    }
314                }
315            }
316            if !fast.multiple {
317                Button("No keyword") { answer(" ") }
318            }
319        } footer: {
320            if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
321        }
322    }
323
324    static func stamp(_ date: Date) -> String {
325        let formatter = DateFormatter()
326        formatter.locale = Locale(identifier: "en_US_POSIX")
327        formatter.dateFormat = "yyyy-MM-dd"
328        return formatter.string(from: date)
329    }
330}
331
332/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
333struct BlockEditSheet: View {
334    let edit: BlockEdit
335    let finish: (String?) -> Void
336    @State private var text = ""
337    @FocusState private var focused: Bool
338
339    var body: some View {
340        NavigationStack {
341            TextEditor(text: $text)
342                .font(.body.monospaced())
343                .autocorrectionDisabled()
344                .textInputAutocapitalization(.never)
345                .focused($focused)
346                .padding(.horizontal, 8)
347                .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
348                .navigationBarTitleDisplayMode(.inline)
349                .toolbar {
350                    ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
351                    ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text) } }
352                }
353        }
354        .onAppear {
355            text = edit.content
356            focused = true
357        }
358    }
359}
360
361/// Every command that applies at the caret, by name.
362struct CommandPalette: View {
363    let editor: MobileEditor
364    @State private var query = ""
365    @Environment(\.dismiss) private var dismiss
366
367    private static let viewCommands: [(id: String, title: String)] = [
368        ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
369        ("edit.undo", "Undo"), ("edit.redo", "Redo"),
370        ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
371        ("app.clock.goto", "Go to Clocked Entry"),
372    ]
373
374    var body: some View {
375        let context = editor.editContext()
376        let all = Self.viewCommands + Commands.everything.map { ($0.id, $0.title) }
377        let shown = all.filter { editor.applies($0.id, in: context) && (query.isEmpty || $0.title.localizedCaseInsensitiveContains(query)) }
378        NavigationStack {
379            List(shown, id: \.id) { command in
380                Button {
381                    dismiss()
382                    // After the sheet goes, so a command's own prompt can show.
383                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { editor.run(command.id) }
384                } label: {
385                    HStack {
386                        Text(command.title).foregroundStyle(.primary)
387                        Spacer()
388                        if let keys = editor.keymap.keyLabels(for: command.id).first {
389                            Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
390                        }
391                    }
392                }
393            }
394            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
395            .navigationTitle("Commands")
396            .navigationBarTitleDisplayMode(.inline)
397            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
398        }
399    }
400}
401#endif