Sources/Orgstar/ColumnViewSheet.swift

design-themes-widgets
orgstar/Sources/Orgstar/ColumnViewSheet.swift history · blame · raw

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