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