Sources/Orgstar/ColumnViewSheet.swift

210 lines · 8986 bytes

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