Sources/Orgstar/Keys.swift
220 lines · 9612 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 case "visual-block": "V-BLOCK"
138 default: state.uppercased()
139 }
140 }
141
142 private var color: Color {
143 switch state {
144 case "insert": theme.color("state-insert") ?? .green
145 case "visual", "visual-line", "visual-block": theme.color("state-visual") ?? .orange
146 default: theme.color("state-normal") ?? .blue
147 }
148 }
149}
150
151extension EchoArea {
152 /// What completion matches: the text after the last separator, or all of it.
153 private func completing(_ separator: Character?) -> Substring {
154 guard let separator, let last = answer.lastIndex(of: separator) else { return answer[...] }
155 return answer[answer.index(after: last)...]
156 }
157
158 /// Puts `choice` in place of what's being completed; with a separator, adds one after it.
159 func complete(_ choice: String, _ prompt: Prompt) {
160 guard let separator = prompt.completionSeparator else {
161 answer = choice
162 return
163 }
164 let start = answer.lastIndex(of: separator).map { answer.index(after: $0) } ?? answer.startIndex
165 answer = String(answer[..<start]) + (start == answer.startIndex ? String(separator) : "") + choice + String(separator)
166 }
167
168 /// Choices matching what's typed, best first.
169 func filteredChoices(_ choices: [String]) -> [String] {
170 let typed = String(completing(commands.prompt?.prompt.completionSeparator))
171 guard !typed.isEmpty else { return choices }
172 return choices.compactMap { choice in FuzzyMatch.score(typed, choice).map { (choice, $0) } }
173 .sorted { $0.1 > $1.1 }
174 .map(\.0)
175 }
176}
177
178/// M-x and ⇧⌘P: every command by title, with its keys.
179struct PaletteView: View {
180 let commands: AppCommands
181 let run: (String) -> Void
182 @State private var query = ""
183 @Environment(\.dismiss) private var dismiss
184
185 private var matches: [EditorCommand] {
186 let scored: [(command: EditorCommand, score: Int)] = EditorCommands.all.filter(\.inPalette).compactMap { command in
187 guard let score = FuzzyMatch.score(query, command.title) else { return nil }
188 return (command, score)
189 }
190 return scored.sorted { $0.score != $1.score ? $0.score > $1.score : $0.command.title < $1.command.title }.map(\.command)
191 }
192
193 var body: some View {
194 let matches = matches
195 VStack(spacing: 0) {
196 TextField("Run command", text: $query)
197 .textFieldStyle(.plain)
198 .font(.title3)
199 .padding(12)
200 .onSubmit { if let first = matches.first { run(first.id) } }
201 Divider()
202 List(matches, id: \.id) { command in
203 Button {
204 run(command.id)
205 } label: {
206 HStack {
207 Text(command.title)
208 Spacer()
209 if let keys = commands.keyLabel(for: command.id) {
210 Text(keys).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
211 }
212 }
213 }
214 .buttonStyle(.plain)
215 }
216 }
217 .frame(width: 520, height: 360)
218 .onExitCommand { dismiss() }
219 }
220}