Sources/OrgstarMobile/EditorScreen.swift

af47263e617152bd4a51f0c0faa6dfbdaf79d2c9
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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