Sources/OrgstarMobile/EditorScreen.swift
653 lines · 30098 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import SwiftUI
6import UIKit
7import UniformTypeIdentifiers
8
9/// Editing a file: the text with Org's folding and styling, a bar of Org keys over the keyboard,
10/// and every command in a palette. The editor is the open file's live state, so autosave and
11/// merging go through the session as on the Mac.
12struct EditorScreen: View {
13 let path: String
14 let offset: Int?
15 let workspace: WorkspaceModel
16 let session: DocumentSession
17 @State private var editor: MobileEditor?
18 @State private var prompt: PromptRequest?
19 @State private var message: String?
20 @State private var sheet: Sheet?
21 @State private var trust = TrustStore()
22 /// The command chosen in the palette, run once the palette is gone.
23 @State private var chosen: String?
24 @Environment(ClockModel.self) private var clock
25 @Environment(MobileModel.self) private var model
26 @Environment(\.openURL) private var openURL
27
28 /// The session's options with `buffer-file-name` and the agenda files, for clock tables.
29 private var editorOptions: EditingOptions {
30 var options = session.options
31 options.filePath = path
32 options.agendaFiles = workspace.agendaFilePaths()
33 return options
34 }
35
36 struct PromptRequest: Identifiable {
37 let id = UUID()
38 let prompt: Prompt
39 let reply: (String?) -> Void
40 }
41
42 /// One sheet at a time: two presenters on this screen interfere.
43 /// `org-table-import`'s file picker is up.
44 @State private var importingTable = false
45 /// The table at the caret, for `org-table-export`'s save dialog.
46 @State private var exportedTable: TableFile?
47
48 enum Sheet: Identifiable {
49 case palette, conflict, syncCopies, recovery
50 /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
51 case refile(String)
52 case block(BlockEdit)
53 case columns(ColumnView.View)
54
55 var id: String {
56 switch self {
57 case .palette: "palette"
58 case .refile(let command): command
59 case .conflict: "conflict"
60 case .syncCopies: "syncCopies"
61 case .recovery: "recovery"
62 case .block(let edit): "block \(edit.range)"
63 case .columns: "columns"
64 }
65 }
66 }
67
68 var body: some View {
69 Group {
70 if let editor {
71 EditorTextView(editor: editor, palette: { sheet = .palette })
72 .ignoresSafeArea(.container, edges: .bottom)
73 } else {
74 ProgressView()
75 }
76 }
77 .navigationTitle(session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""))
78 .navigationBarTitleDisplayMode(.inline)
79 .toolbar(.hidden, for: .tabBar)
80 .toolbar {
81 ToolbarItemGroup(placement: .primaryAction) {
82 if session.conflict != nil {
83 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
84 }
85 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
86 Menu("More", systemImage: "ellipsis.circle") {
87 Button("Commands", systemImage: "command") { sheet = .palette }
88 Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
89 Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") }
90 Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") }
91 Menu("Table", systemImage: "tablecells") {
92 Button("Import Table from File…", systemImage: "square.and.arrow.down") { importingTable = true }
93 Button("Export Table as CSV…", systemImage: "square.and.arrow.up") { exportTable(csv: true) }
94 Button("Export Table as TSV…", systemImage: "square.and.arrow.up") { exportTable(csv: false) }
95 }
96 Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) {
97 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
98 }
99 RecentClockMenu(clock: clock) { editor?.run($0) }
100 if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) { message = $0 } }
101 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
102 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
103 }
104 }
105 }
106 .safeAreaInset(edge: .top) {
107 if let message {
108 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
109 .onTapGesture { self.message = nil }
110 .task(id: message) {
111 try? await Task.sleep(for: .seconds(4))
112 if self.message == message { self.message = nil }
113 }
114 }
115 }
116 .sheet(item: $prompt) { request in
117 PromptSheet(prompt: request.prompt) { answer in
118 prompt = nil
119 request.reply(answer)
120 }
121 }
122 .sheet(item: $sheet, onDismiss: {
123 // After the sheet has gone, so a command's own prompt can show.
124 if let id = chosen {
125 chosen = nil
126 editor?.run(id)
127 }
128 }) { sheet in
129 switch sheet {
130 case .palette: if let editor { CommandPalette(editor: editor) { chosen = $0 } }
131 case .conflict: ConflictSheet(session: session)
132 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
133 case .recovery: RecoverySheet(session: session) { message = $0 }
134 case .refile(let command):
135 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
136 create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
137 self.sheet = nil
138 switch session.createRefileChild(under: parent, title: child) {
139 case .success(let target):
140 guard let path = session.path, let editor else { return }
141 message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
142 case .failure(.message(let text)): message = text
143 }
144 }) { target in
145 self.sheet = nil
146 guard let target else { return }
147 if command == "app.refile.goto" {
148 model.openRequest = .offset(target.path, target.start ?? Int.max)
149 } else {
150 refile(to: target, keep: command == "app.refile.copy")
151 }
152 }
153 case .block(let edit):
154 BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
155 self.sheet = nil
156 if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
157 }
158 case .columns(let view):
159 ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
160 }
161 }
162 .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
163 importTable(result)
164 }
165 .fileExporter(isPresented: Binding(get: { exportedTable != nil }, set: { if !$0 { exportedTable = nil } }),
166 document: exportedTable, contentType: exportedTable?.type ?? .commaSeparatedText,
167 defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in
168 if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." }
169 }
170 .onChange(of: session.conflict) { _, conflict in
171 if conflict != nil, session.path == path { sheet = .conflict }
172 }
173 .onChange(of: session.lastError) { _, error in
174 if let error { message = error; session.lastError = nil }
175 }
176 .onAppear(perform: start)
177 .onChange(of: session.revealRequest?.id) {
178 if let offset = session.revealRequest?.offset, session.path == path { editor?.reveal(offset) }
179 }
180 .onChange(of: model.settingsVersion) {
181 editor?.options = editorOptions
182 editor?.themeSpec = model.theme
183 editor?.keymap = model.keymap
184 editor?.modal = model.modalKeys
185 }
186 .onChange(of: model.showMarkup) { editor?.showMarkup = model.showMarkup }
187 .onDisappear {
188 // Typing the reader shows next, and a save, don't wait for the autosave delay.
189 if session.dirtyPaths.contains(path) { _ = session.save(path) }
190 }
191 }
192
193 /// Store Link, Store ID Link and Insert Link, with the links stored while the app runs.
194 private func link(_ id: String) {
195 guard let editor else { return }
196 switch id {
197 case "org.link.store":
198 message = StoredLink.add(Links.store(in: editor.editContext(), path: Links.abbreviate(path, home: NSHomeDirectory())), to: &model.storedLinks)
199 case "org.id.store-link":
200 if case .commit = editor.perform(CreateID()),
201 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
202 message = StoredLink.add(link, to: &model.storedLinks)
203 }
204 default:
205 _ = editor.perform(InsertLink(stored: model.storedLinks, file: path))
206 }
207 }
208
209 /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
210 private func run(_ job: BabelJob) {
211 let go = {
212 message = "Running \(job.language) block…"
213 session.startBabel(job) { message = $0 }
214 }
215 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
216 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
217 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
218 switch answer {
219 case "always":
220 trust.trust(path: path, content: job.blockText)
221 go()
222 case "yes": go()
223 default: message = "Not run"
224 }
225 }
226 }
227
228 private func start() {
229 if session.path != path { session.open(path) }
230 if editor == nil, let document = session.document {
231 let editor = MobileEditor(
232 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
233 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
234 )
235 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
236 editor.onChange = { [weak session] in session?.bufferChanged(path) }
237 editor.onMessage = { message = $0 }
238 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
239 editor.onLink = { link in
240 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
241 case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")"
242 case .openExternally(let url): openURL(url)
243 case .message(let text): message = text
244 }
245 }
246 editor.onEditBlock = { edit in sheet = .block(edit) }
247 editor.onColumnView = { view in sheet = .columns(view) }
248 editor.onTangle = { scope in message = session.tangle(scope) }
249 editor.onBabel = { job in run(job) }
250 editor.onRefreshSetup = { session.refreshSetup() }
251 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
252 editor.keymap = model.keymap
253 editor.modal = model.modalKeys
254 editor.onAppCommand = { id in
255 if id == "app.save" {
256 _ = session.save(path)
257 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
258 sheet = .refile(id)
259 } else if id == "app.table-import" {
260 importingTable = true
261 } else if id == "app.table-export" {
262 exportTable(csv: true)
263 } else if id == "app.toggle-markup" {
264 model.showMarkup.toggle()
265 } else if MobileEditor.linkCommands.contains(id) {
266 link(id)
267 } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
268 message = "Not available on iOS yet"
269 }
270 }
271 self.editor = editor
272 }
273 if let editor { session.attach(editor) }
274 if let offset { editor?.reveal(offset) }
275 if session.conflict != nil {
276 sheet = .conflict
277 } else if case let copies = session.syncConflictCopies().count, copies > 0 {
278 message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
279 }
280 }
281}
282
283extension EditorScreen {
284 /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
285 private func importTable(_ result: Result<URL, Error>) {
286 guard case .success(let url) = result, let editor else { return }
287 let scoped = url.startAccessingSecurityScopedResource()
288 defer { if scoped { url.stopAccessingSecurityScopedResource() } }
289 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
290 _ = editor.perform(ImportTable(contents: contents))
291 }
292
293 /// `org-table-export` of the table at the caret, as CSV or TSV.
294 private func exportTable(csv: Bool) {
295 guard let editor else { return }
296 let context = editor.editContext()
297 guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
298 return message = "No table at point"
299 }
300 exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
301 }
302
303 /// `org-refile` of the entry at the caret, to a target worked out again from the files
304 /// now, as the agenda's Refile… does.
305 func refile(to target: RefileTarget, keep: Bool = false) {
306 guard let editor, let path = session.path else { return }
307 let caret = editor.editContext().caret
308 guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
309 message = "Can't find \(target.label) any more."
310 return
311 }
312 message = session.refile(to: current, from: (path, caret), keep: keep)
313 }
314}
315
316/// The editor's text view, with the Org key bar over the keyboard.
317struct EditorTextView: UIViewRepresentable {
318 let editor: MobileEditor
319 let palette: () -> Void
320
321 func makeUIView(context: Context) -> UITextView {
322 let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
323 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
324 bar.view.backgroundColor = .clear
325 bar.sizingOptions = []
326 editor.textView.inputAccessoryView = bar.view
327 context.coordinator.bar = bar
328 return editor.textView
329 }
330
331 func updateUIView(_ view: UITextView, context: Context) {}
332
333 func makeCoordinator() -> Coordinator { Coordinator() }
334
335 final class Coordinator {
336 var bar: UIViewController?
337 }
338}
339
340/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
341/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
342struct KeyBar: View {
343 let editor: MobileEditor
344 let palette: () -> Void
345
346 private static let keys: [(label: String, symbol: String?, keys: String)] = [
347 ("Fold", "arrow.right.to.line", "TAB"),
348 ("Overview", "arrow.left.to.line", "S-TAB"),
349 ("Promote", "arrow.left", "M-<left>"),
350 ("Demote", "arrow.right", "M-<right>"),
351 ("Move up", "arrow.up", "M-<up>"),
352 ("Move down", "arrow.down", "M-<down>"),
353 ("New heading or item", "plus", "M-RET"),
354 ("TODO", nil, "C-c C-t"),
355 ("Act at point", "checkmark.square", "C-c C-c"),
356 ("Schedule", "calendar", "C-c C-s"),
357 ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
358 ("Tags", "tag", "C-c C-q"),
359 ("Open link", "link", "C-c C-o"),
360 ]
361
362 var body: some View {
363 ScrollView(.horizontal, showsIndicators: false) {
364 HStack(spacing: 4) {
365 Button("Commands", systemImage: "command", action: palette)
366 ForEach(Self.keys, id: \.keys) { key in
367 Button {
368 editor.run(keys: key.keys)
369 } label: {
370 if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
371 }
372 .accessibilityLabel(key.label)
373 }
374 Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
375 }
376 .labelStyle(.iconOnly)
377 .buttonStyle(.bordered)
378 .padding(.horizontal, 8)
379 .padding(.vertical, 6)
380 }
381 .background(.bar)
382 }
383}
384
385/// A command's question: text with choices, a date, or fast selection by keys.
386struct PromptSheet: View {
387 let prompt: Prompt
388 let answer: (String?) -> Void
389 @State private var text = ""
390 @State private var date = Date()
391 @State private var keys: [FastSelection.Input] = []
392
393 var body: some View {
394 NavigationStack {
395 Form {
396 if let fast = prompt.fast {
397 fastSection(fast)
398 } else {
399 Section {
400 TextField(prompt.message, text: $text)
401 .autocorrectionDisabled()
402 .textInputAutocapitalization(.never)
403 .onSubmit { answer(text) }
404 } footer: {
405 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
406 }
407 if prompt.date != nil {
408 DatePicker("Date", selection: $date, displayedComponents: [.date])
409 .datePickerStyle(.graphical)
410 .onChange(of: date) { text = Self.stamp(date) }
411 }
412 if !prompt.choices.isEmpty {
413 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
414 Section("Choices") {
415 ForEach(matching.prefix(50), id: \.self) { choice in
416 Button(choice) { choose(choice) }
417 }
418 }
419 }
420 }
421 }
422 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
423 .navigationBarTitleDisplayMode(.inline)
424 .toolbar {
425 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
426 if prompt.fast == nil || prompt.fast?.multiple == true {
427 ToolbarItem(placement: .confirmationAction) {
428 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
429 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
430 }
431 }
432 }
433 }
434 .onAppear {
435 text = prompt.initial
436 if let day = prompt.date?.defaultDate { date = day }
437 }
438 }
439
440 /// With a separator (tags), what's typed after the last one.
441 private var lastPart: String {
442 guard let separator = prompt.completionSeparator else { return text }
443 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
444 }
445
446 private func choose(_ choice: String) {
447 guard let separator = prompt.completionSeparator else {
448 text = choice
449 if prompt.date == nil { answer(choice) }
450 return
451 }
452 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
453 if parts.isEmpty { parts = [""] }
454 parts[parts.count - 1] = choice
455 text = parts.joined(separator: String(separator)) + String(separator)
456 }
457
458 @ViewBuilder
459 private func fastSection(_ fast: FastSelection) -> some View {
460 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
461 Section {
462 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
463 Button {
464 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
465 } label: {
466 HStack {
467 Text(option.name).foregroundStyle(.primary)
468 Spacer()
469 if current.contains(option.name) { Image(systemName: "checkmark") }
470 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
471 }
472 }
473 }
474 if !fast.multiple {
475 Button("No keyword") { answer(" ") }
476 }
477 } footer: {
478 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
479 }
480 }
481
482 static func stamp(_ date: Date) -> String {
483 let formatter = DateFormatter()
484 formatter.locale = Locale(identifier: "en_US_POSIX")
485 formatter.dateFormat = "yyyy-MM-dd"
486 return formatter.string(from: date)
487 }
488}
489
490/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
491/// A src block's code is highlighted as its language.
492struct BlockEditSheet: View {
493 let edit: BlockEdit
494 let theme: MobileTheme
495 let finish: (String?) -> Void
496 @State private var text: String?
497
498 var body: some View {
499 NavigationStack {
500 Group {
501 if let text {
502 CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
503 }
504 }
505 .padding(.horizontal, 8)
506 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
507 .navigationBarTitleDisplayMode(.inline)
508 .toolbar {
509 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
510 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
511 }
512 }
513 .onAppear { text = edit.content }
514 }
515}
516
517/// A text view for code, restyled with the editor's highlighter after each change.
518struct CodeTextView: UIViewRepresentable {
519 let text: String
520 let language: String?
521 let theme: MobileTheme
522 let changed: (String) -> Void
523
524 func makeUIView(context: Context) -> UITextView {
525 let view = UITextView()
526 view.autocorrectionType = .no
527 view.autocapitalizationType = .none
528 view.smartQuotesType = .no
529 view.smartDashesType = .no
530 view.spellCheckingType = .no
531 view.keyboardDismissMode = .interactive
532 view.backgroundColor = .clear
533 view.text = text
534 view.delegate = context.coordinator
535 context.coordinator.style(view)
536 DispatchQueue.main.async { view.becomeFirstResponder() }
537 return view
538 }
539
540 func updateUIView(_ view: UITextView, context: Context) {
541 context.coordinator.parent = self
542 }
543
544 func makeCoordinator() -> Coordinator { Coordinator(self) }
545
546 @MainActor
547 final class Coordinator: NSObject, UITextViewDelegate {
548 var parent: CodeTextView
549 init(_ parent: CodeTextView) { self.parent = parent }
550
551 func textViewDidChange(_ view: UITextView) {
552 parent.changed(view.text)
553 style(view)
554 }
555
556 /// The theme's font and color, then the language's token colors.
557 func style(_ view: UITextView) {
558 let storage = view.textStorage
559 let whole = NSRange(location: 0, length: storage.length)
560 let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
561 storage.beginEditing()
562 storage.setAttributes(base, range: whole)
563 if let language = parent.language {
564 for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
565 guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
566 storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
567 }
568 }
569 storage.endEditing()
570 view.typingAttributes = base
571 }
572 }
573}
574
575/// Every command that applies at the caret, by name.
576struct CommandPalette: View {
577 let editor: MobileEditor
578 /// Called with the chosen command before the palette closes.
579 let choose: (String) -> Void
580 @State private var query = ""
581 @Environment(\.dismiss) private var dismiss
582
583 private static let viewCommands: [(id: String, title: String)] = [
584 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
585 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
586 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
587 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
588 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
589 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
590 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
591 ("app.toggle-markup", "Show or Hide Markup"),
592 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"),
593 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
594 ("org.table.expand", "Expand Table Columns"),
595 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"),
596 ]
597
598 /// The commands that apply at the caret and their keys, worked out once when the palette
599 /// opens rather than on every keystroke in the search field.
600 @State private var applicable: [(id: String, title: String, keys: String?)]?
601
602 var body: some View {
603 let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
604 NavigationStack {
605 List(shown, id: \.id) { command in
606 Button {
607 choose(command.id)
608 dismiss()
609 } label: {
610 HStack {
611 Text(command.title).foregroundStyle(.primary)
612 Spacer()
613 if let keys = command.keys {
614 Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
615 }
616 }
617 }
618 }
619 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
620 .navigationTitle("Commands")
621 .navigationBarTitleDisplayMode(.inline)
622 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
623 }
624 .onAppear {
625 guard applicable == nil else { return }
626 let context = editor.editContext()
627 applicable = (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) })
628 .filter { editor.applies($0.id, in: context) }
629 .map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) }
630 }
631 }
632}
633/// A table as CSV or TSV, for the save dialog.
634struct TableFile: FileDocument {
635 static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
636 let text: String
637 let type: UTType
638
639 init(text: String, type: UTType) {
640 self.text = text
641 self.type = type
642 }
643
644 init(configuration: ReadConfiguration) throws {
645 text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
646 type = configuration.contentType
647 }
648
649 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
650 FileWrapper(regularFileWithContents: Data(text.utf8))
651 }
652}
653#endif