Sources/OrgstarMobile/EditorScreen.swift

1d52ac3e828cb73639dc1c0cd5b6c9f0795b14a7
orgstar/Sources/OrgstarMobile/EditorScreen.swift history · blame · raw

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