Sources/Orgstar/ColumnViewSheet.swift
189 lines · 8131 bytes
1import OrgApp
2import OrgCore
3import SwiftUI
4
5/// `org-columns`: one row per entry, one column per column-format field, with summaries.
6/// Click a cell to select it; Return or a double-click edits it (`e`), `n` and `p` move to the
7/// next or previous allowed value, and Go to Entry shows its heading.
8struct ColumnViewSheet: View {
9 @State var view: ColumnView.View
10 /// Runs a command at a heading's start; the step tells what came of it.
11 let run: (any OrgCommand, Int, [String: String]) -> CommandStep
12 /// The document's text and tree now, to capture the view again and offer allowed values.
13 let document: () -> (text: String, tree: OrgTree)?
14 let jump: (Int) -> Void
15 @Environment(\.dismiss) private var dismiss
16 @State private var selected: (row: Int, column: Int)?
17 @State private var editing: (row: Int, column: Int)?
18 @State private var draft = ""
19 @State private var message: String?
20 /// A question the edit asks (a state note).
21 @State private var prompt: PromptRequest?
22 @FocusState private var focused: Bool
23
24 var body: some View {
25 VStack(alignment: .leading, spacing: 0) {
26 HStack {
27 Text("Column View").font(.headline)
28 Spacer()
29 Button("Go to Entry") {
30 guard let selected else { return }
31 jump(view.rows[selected.row].start)
32 dismiss()
33 }
34 .disabled(selected == nil)
35 Button("Done") { dismiss() }.keyboardShortcut(.cancelAction)
36 }
37 .padding(10)
38 Divider()
39 ScrollView([.horizontal, .vertical]) {
40 ColumnViewGrid(view: view, verticalSpacing: 4) { r, c in cellView(r, c) }
41 .font(.system(.body, design: .monospaced))
42 .padding(10)
43 }
44 .defaultScrollAnchor(.topLeading)
45 PromptBar(request: $prompt)
46 if let message {
47 Text(message).font(.callout).foregroundStyle(.secondary).padding(8)
48 }
49 }
50 .frame(minWidth: 640, minHeight: 360)
51 .focusable()
52 .focused($focused)
53 .focusEffectDisabled()
54 .onAppear { focused = true }
55 .onKeyPress(phases: .down) { press in key(press) }
56 }
57
58 private func cellView(_ r: Int, _ c: Int) -> some View {
59 let row = view.rows[r]
60 let isSelected = selected.map { $0 == (r, c) } ?? false
61 return Group {
62 if let editing, editing == (r, c) {
63 editor(r, c)
64 } else {
65 Text(cell(row, c))
66 .lineLimit(1)
67 .frame(maxWidth: view.specs[c].width.map { CGFloat($0) * 8.5 }, alignment: .leading)
68 .padding(.horizontal, 2)
69 .background(isSelected ? Color.accentColor.opacity(0.25) : .clear, in: RoundedRectangle(cornerRadius: 3))
70 .contentShape(Rectangle())
71 .onTapGesture(count: 2) { startEditing(r, c) }
72 .onTapGesture {
73 selected = (r, c)
74 focused = true
75 }
76 .accessibilityAddTraits(.isButton)
77 .accessibilityAction(named: "Edit") { startEditing(r, c) }
78 .accessibilityAction(named: "Go to Entry") {
79 jump(row.start)
80 dismiss()
81 }
82 }
83 }
84 }
85
86 /// A field for the value, with the allowed values in a menu.
87 private func editor(_ r: Int, _ c: Int) -> some View {
88 let spec = view.specs[c]
89 let allowed = document().flatMap { PropertyValues.allowed(spec.property, at: view.rows[r].start, text: $0.text, tree: $0.tree)?.values } ?? []
90 return HStack(spacing: 4) {
91 TextField(spec.title, text: $draft)
92 .textFieldStyle(.roundedBorder)
93 .frame(minWidth: 120)
94 .onSubmit { commit(r, c, draft) }
95 .onExitCommand { editing = nil }
96 if !allowed.isEmpty {
97 Menu {
98 ForEach(allowed, id: \.self) { value in Button(value.isEmpty ? "(none)" : value) { commit(r, c, value) } }
99 } label: {
100 Image(systemName: "chevron.down")
101 }
102 .menuStyle(.borderlessButton)
103 .fixedSize()
104 }
105 }
106 }
107
108 /// ITEM with the heading's stars, as org shows it.
109 private func cell(_ row: ColumnView.Row, _ i: Int) -> String {
110 guard view.specs[i].property == "ITEM" else { return row.values[i] }
111 return String(repeating: "*", count: row.level) + " " + row.values[i]
112 }
113
114 private func key(_ press: KeyPress) -> KeyPress.Result {
115 guard editing == nil, prompt == nil else { return .ignored }
116 guard let current = selected else {
117 if [.downArrow, .upArrow, .leftArrow, .rightArrow].contains(press.key), !view.rows.isEmpty {
118 selected = (0, 0)
119 return .handled
120 }
121 return .ignored
122 }
123 switch press.key {
124 case .downArrow: selected = (min(current.row + 1, view.rows.count - 1), current.column)
125 case .upArrow: selected = (max(current.row - 1, 0), current.column)
126 case .rightArrow: selected = (current.row, min(current.column + 1, view.specs.count - 1))
127 case .leftArrow: selected = (current.row, max(current.column - 1, 0))
128 case .return: startEditing(current.row, current.column)
129 default:
130 switch press.characters {
131 case "e": startEditing(current.row, current.column)
132 case "n", "p":
133 let spec = view.specs[current.column]
134 perform(NextColumnValue(property: spec.property, summary: spec.summary, previous: press.characters == "p"), row: current.row)
135 default: return .ignored
136 }
137 }
138 return .handled
139 }
140
141 private func startEditing(_ r: Int, _ c: Int) {
142 selected = (r, c)
143 let spec = view.specs[c]
144 if ["CLOCKSUM", "CLOCKSUM_T", "ALLTAGS", "BLOCKED", "CLOSED", "FILE", "TIMESTAMP", "TIMESTAMP_IA"].contains(spec.property) {
145 message = "This special column cannot be edited"
146 return
147 }
148 let row = view.rows[r]
149 draft = row.raw.indices.contains(c) ? row.raw[c] : row.values[c]
150 editing = (r, c)
151 }
152
153 private func commit(_ r: Int, _ c: Int, _ value: String) {
154 editing = nil
155 perform(SetColumnValue(property: view.specs[c].property, value: value), row: r)
156 }
157
158 private func perform(_ command: any OrgCommand, row: Int, answers: [String: String] = [:]) {
159 handle(run(command, view.rows[row].start, answers), command: command, start: view.rows[row].start, answers: answers)
160 }
161
162 private func handle(_ step: CommandStep, command: any OrgCommand, start: Int, answers: [String: String]) {
163 switch step {
164 case .commit:
165 message = nil
166 refresh()
167 case .failed(let text):
168 message = text
169 case .prompt(let question):
170 prompt = PromptRequest(prompt: question) { reply in
171 focused = true
172 guard let reply else { return }
173 let answers = answers.merging([question.key: reply]) { $1 }
174 handle(run(command, start, answers), command: command, start: start, answers: answers)
175 }
176 return
177 default:
178 message = String(localized: "\(CommandTitle.localized(command.title)) can't run here", comment: "A command that doesn't apply in column view")
179 }
180 focused = true
181 }
182
183 /// The view again, over the same entries, keeping the selected cell.
184 private func refresh() {
185 guard let document = document(), let new = try? ColumnView.refresh(view, text: document.text, tree: document.tree) else { return }
186 view = new
187 if let selected, selected.row >= new.rows.count { self.selected = nil }
188 }
189}