Sources/OrgstarMobile/EditorScreen.swift

fb4402de470e935f9add3b08fd338ec154a65045
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form