Sources/Orgstar/Keys.swift

4b4dc0135e1d59d493a0a49865fcd155aeea59e0
orgstar/Sources/Orgstar/Keys.swift history · blame · raw

219 lines · 9557 bytes

  1import OrgApp
  2import OrgCore
  3import OrgEditorAppKit
  4import SwiftUI
  5
  6struct KeyHint: Hashable {
  7    let key: String
  8    let title: String
  9}
 10
 11/// The minibuffer line: a pending prefix, or the last message for a few seconds. After a
 12/// short pause on a prefix, the keys that can follow it.
 13struct EchoArea: View {
 14    let commands: AppCommands
 15    @Environment(\.orgTheme) private var theme
 16    @State private var showingHints = false
 17    @State private var answer = ""
 18    @FocusState private var answerFocused: Bool
 19
 20    var body: some View {
 21        VStack(alignment: .leading, spacing: 0) {
 22            if showingHints, commands.pendingKeys != nil, !commands.keyHints.isEmpty {
 23                Divider()
 24                LazyVGrid(columns: [GridItem(.adaptive(minimum: 220), alignment: .leading)], alignment: .leading, spacing: 4) {
 25                    ForEach(commands.keyHints, id: \.self) { hint in
 26                        HStack(spacing: 8) {
 27                            Text(hint.key).font(.system(.body, design: .monospaced)).foregroundStyle(.tint)
 28                            Text(hint.title).foregroundStyle(hint.title == "+prefix" ? .secondary : .primary).lineLimit(1)
 29                        }
 30                    }
 31                }
 32                .padding(10)
 33            }
 34            if let request = commands.prompt, let fast = request.prompt.fast {
 35                Divider()
 36                FastSelectionView(selection: fast, message: request.prompt.message) { commands.answer($0) }
 37                    .id(request.id)
 38            } else if let request = commands.prompt {
 39                if !request.prompt.choices.isEmpty {
 40                    Divider()
 41                    let matches = filteredChoices(request.prompt.choices)
 42                    ScrollView {
 43                        VStack(alignment: .leading, spacing: 2) {
 44                            ForEach(matches.prefix(12), id: \.self) { choice in
 45                                Button(choice) {
 46                                    if request.prompt.completionSeparator != nil { complete(choice, request.prompt) } else { commands.answer(choice) }
 47                                }
 48                                    .buttonStyle(.plain)
 49                                    .font(.system(.callout, design: .monospaced))
 50                                    .foregroundStyle(choice == matches.first ? .primary : .secondary)
 51                            }
 52                        }
 53                        .frame(maxWidth: .infinity, alignment: .leading)
 54                        .padding(10)
 55                    }
 56                    .frame(maxHeight: 200)
 57                }
 58                if let read = request.prompt.date {
 59                    Divider()
 60                    DatePickerView(answer: answer, read: read) { commands.answer($0) }
 61                }
 62                Divider()
 63                HStack(spacing: 6) {
 64                    Text(request.prompt.message).font(.system(.callout, design: .monospaced)).foregroundStyle(.secondary)
 65                        .lineLimit(1)
 66                        .truncationMode(.middle)
 67                    TextField("", text: $answer)
 68                        .frame(minWidth: 240)
 69                        .textFieldStyle(.plain)
 70                        .font(.system(.callout, design: .monospaced))
 71                        .focused($answerFocused)
 72                        .onSubmit {
 73                            if request.prompt.choices.isEmpty || !request.prompt.requireMatch {
 74                                commands.answer(answer)
 75                            } else if let first = filteredChoices(request.prompt.choices).first {
 76                                commands.answer(first)
 77                            }
 78                        }
 79                        .onKeyPress(.tab) {
 80                            guard let first = filteredChoices(request.prompt.choices).first else { return .ignored }
 81                            complete(first, request.prompt)
 82                            return .handled
 83                        }
 84                        .onKeyPress(keys: [.leftArrow, .rightArrow, .upArrow, .downArrow]) { press in
 85                            guard let read = request.prompt.date, press.modifiers == .shift else { return .ignored }
 86                            let days = [KeyEquivalent.leftArrow: -1, .rightArrow: 1, .upArrow: -7, .downArrow: 7][press.key]!
 87                            answer = DatePickerView.shifted(answer, read, by: days)
 88                            return .handled
 89                        }
 90                        .onExitCommand { commands.answer(nil) }
 91                }
 92                .padding(.horizontal, 10)
 93                .padding(.vertical, 4)
 94                .onAppear {
 95                    answer = request.prompt.initial
 96                    answerFocused = true
 97                }
 98                .id(request.id)
 99            } else if let text = commands.pendingKeys.map({ $0 + "-" }) ?? commands.message {
100                Text(text)
101                    .font(.system(.callout, design: .monospaced))
102                    .lineLimit(1)
103                    .padding(.horizontal, 10)
104                .padding(.vertical, 4)
105                .frame(maxWidth: .infinity, alignment: .leading)
106            }
107        }
108        .foregroundStyle(theme.color("modeline-foreground") ?? .primary)
109        .background { if let bg = theme.color("modeline-background") { bg } else { Rectangle().fill(.bar) } }
110        .task(id: commands.pendingKeys) {
111            showingHints = false
112            guard commands.pendingKeys != nil else { return }
113            try? await Task.sleep(for: .milliseconds(600))
114            if !Task.isCancelled { showingHints = true }
115        }
116    }
117}
118
119/// The evil state, as Doom's modeline shows it.
120struct StateTag: View {
121    let state: String
122    @Environment(\.orgTheme) private var theme
123
124    var body: some View {
125        Text(label)
126            .font(.system(.caption, design: .monospaced).bold())
127            .foregroundStyle(.white)
128            .padding(.horizontal, 6)
129            .padding(.vertical, 1)
130            .background(color, in: RoundedRectangle(cornerRadius: 4))
131            .accessibilityLabel("\(label.capitalized) state")
132    }
133
134    private var label: String {
135        switch state {
136        case "visual-line": "V-LINE"
137        default: state.uppercased()
138        }
139    }
140
141    private var color: Color {
142        switch state {
143        case "insert": theme.color("state-insert") ?? .green
144        case "visual", "visual-line": theme.color("state-visual") ?? .orange
145        default: theme.color("state-normal") ?? .blue
146        }
147    }
148}
149
150extension EchoArea {
151    /// What completion matches: the text after the last separator, or all of it.
152    private func completing(_ separator: Character?) -> Substring {
153        guard let separator, let last = answer.lastIndex(of: separator) else { return answer[...] }
154        return answer[answer.index(after: last)...]
155    }
156
157    /// Puts `choice` in place of what's being completed; with a separator, adds one after it.
158    func complete(_ choice: String, _ prompt: Prompt) {
159        guard let separator = prompt.completionSeparator else {
160            answer = choice
161            return
162        }
163        let start = answer.lastIndex(of: separator).map { answer.index(after: $0) } ?? answer.startIndex
164        answer = String(answer[..<start]) + (start == answer.startIndex ? String(separator) : "") + choice + String(separator)
165    }
166
167    /// Choices matching what's typed, best first.
168    func filteredChoices(_ choices: [String]) -> [String] {
169        let typed = String(completing(commands.prompt?.prompt.completionSeparator))
170        guard !typed.isEmpty else { return choices }
171        return choices.compactMap { choice in FuzzyMatch.score(typed, choice).map { (choice, $0) } }
172            .sorted { $0.1 > $1.1 }
173            .map(\.0)
174    }
175}
176
177/// M-x and ⇧⌘P: every command by title, with its keys.
178struct PaletteView: View {
179    let commands: AppCommands
180    let run: (String) -> Void
181    @State private var query = ""
182    @Environment(\.dismiss) private var dismiss
183
184    private var matches: [EditorCommand] {
185        let scored: [(command: EditorCommand, score: Int)] = EditorCommands.all.filter(\.inPalette).compactMap { command in
186            guard let score = FuzzyMatch.score(query, command.title) else { return nil }
187            return (command, score)
188        }
189        return scored.sorted { $0.score != $1.score ? $0.score > $1.score : $0.command.title < $1.command.title }.map(\.command)
190    }
191
192    var body: some View {
193        let matches = matches
194        VStack(spacing: 0) {
195            TextField("Run command", text: $query)
196                .textFieldStyle(.plain)
197                .font(.title3)
198                .padding(12)
199                .onSubmit { if let first = matches.first { run(first.id) } }
200            Divider()
201            List(matches, id: \.id) { command in
202                Button {
203                    run(command.id)
204                } label: {
205                    HStack {
206                        Text(command.title)
207                        Spacer()
208                        if let keys = commands.keyLabel(for: command.id) {
209                            Text(keys).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
210                        }
211                    }
212                }
213                .buttonStyle(.plain)
214            }
215        }
216        .frame(width: 520, height: 360)
217        .onExitCommand { dismiss() }
218    }
219}