Sources/Orgstar/Keys.swift
209 lines · 8871 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 Divider()
59 HStack(spacing: 6) {
60 Text(request.prompt.message).font(.system(.callout, design: .monospaced)).foregroundStyle(.secondary)
61 .lineLimit(1)
62 .truncationMode(.middle)
63 TextField("", text: $answer)
64 .frame(minWidth: 240)
65 .textFieldStyle(.plain)
66 .font(.system(.callout, design: .monospaced))
67 .focused($answerFocused)
68 .onSubmit {
69 if request.prompt.choices.isEmpty || !request.prompt.requireMatch {
70 commands.answer(answer)
71 } else if let first = filteredChoices(request.prompt.choices).first {
72 commands.answer(first)
73 }
74 }
75 .onKeyPress(.tab) {
76 guard let first = filteredChoices(request.prompt.choices).first else { return .ignored }
77 complete(first, request.prompt)
78 return .handled
79 }
80 .onExitCommand { commands.answer(nil) }
81 }
82 .padding(.horizontal, 10)
83 .padding(.vertical, 4)
84 .onAppear {
85 answer = request.prompt.initial
86 answerFocused = true
87 }
88 .id(request.id)
89 } else if let text = commands.pendingKeys.map({ $0 + "-" }) ?? commands.message {
90 Text(text)
91 .font(.system(.callout, design: .monospaced))
92 .lineLimit(1)
93 .padding(.horizontal, 10)
94 .padding(.vertical, 4)
95 .frame(maxWidth: .infinity, alignment: .leading)
96 }
97 }
98 .foregroundStyle(theme.color("modeline-foreground") ?? .primary)
99 .background { if let bg = theme.color("modeline-background") { bg } else { Rectangle().fill(.bar) } }
100 .task(id: commands.pendingKeys) {
101 showingHints = false
102 guard commands.pendingKeys != nil else { return }
103 try? await Task.sleep(for: .milliseconds(600))
104 if !Task.isCancelled { showingHints = true }
105 }
106 }
107}
108
109/// The evil state, as Doom's modeline shows it.
110struct StateTag: View {
111 let state: String
112 @Environment(\.orgTheme) private var theme
113
114 var body: some View {
115 Text(label)
116 .font(.system(.caption, design: .monospaced).bold())
117 .foregroundStyle(.white)
118 .padding(.horizontal, 6)
119 .padding(.vertical, 1)
120 .background(color, in: RoundedRectangle(cornerRadius: 4))
121 .accessibilityLabel("\(label.capitalized) state")
122 }
123
124 private var label: String {
125 switch state {
126 case "visual-line": "V-LINE"
127 default: state.uppercased()
128 }
129 }
130
131 private var color: Color {
132 switch state {
133 case "insert": theme.color("state-insert") ?? .green
134 case "visual", "visual-line": theme.color("state-visual") ?? .orange
135 default: theme.color("state-normal") ?? .blue
136 }
137 }
138}
139
140extension EchoArea {
141 /// What completion matches: the text after the last separator, or all of it.
142 private func completing(_ separator: Character?) -> Substring {
143 guard let separator, let last = answer.lastIndex(of: separator) else { return answer[...] }
144 return answer[answer.index(after: last)...]
145 }
146
147 /// Puts `choice` in place of what's being completed; with a separator, adds one after it.
148 func complete(_ choice: String, _ prompt: Prompt) {
149 guard let separator = prompt.completionSeparator else {
150 answer = choice
151 return
152 }
153 let start = answer.lastIndex(of: separator).map { answer.index(after: $0) } ?? answer.startIndex
154 answer = String(answer[..<start]) + (start == answer.startIndex ? String(separator) : "") + choice + String(separator)
155 }
156
157 /// Choices matching what's typed, best first.
158 func filteredChoices(_ choices: [String]) -> [String] {
159 let typed = String(completing(commands.prompt?.prompt.completionSeparator))
160 guard !typed.isEmpty else { return choices }
161 return choices.compactMap { choice in FuzzyMatch.score(typed, choice).map { (choice, $0) } }
162 .sorted { $0.1 > $1.1 }
163 .map(\.0)
164 }
165}
166
167/// M-x and ⇧⌘P: every command by title, with its keys.
168struct PaletteView: View {
169 let commands: AppCommands
170 let run: (String) -> Void
171 @State private var query = ""
172 @Environment(\.dismiss) private var dismiss
173
174 private var matches: [EditorCommand] {
175 let scored: [(command: EditorCommand, score: Int)] = EditorCommands.all.filter(\.inPalette).compactMap { command in
176 guard let score = FuzzyMatch.score(query, command.title) else { return nil }
177 return (command, score)
178 }
179 return scored.sorted { $0.score != $1.score ? $0.score > $1.score : $0.command.title < $1.command.title }.map(\.command)
180 }
181
182 var body: some View {
183 let matches = matches
184 VStack(spacing: 0) {
185 TextField("Run command", text: $query)
186 .textFieldStyle(.plain)
187 .font(.title3)
188 .padding(12)
189 .onSubmit { if let first = matches.first { run(first.id) } }
190 Divider()
191 List(matches, id: \.id) { command in
192 Button {
193 run(command.id)
194 } label: {
195 HStack {
196 Text(command.title)
197 Spacer()
198 if let keys = commands.keyLabel(for: command.id) {
199 Text(keys).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
200 }
201 }
202 }
203 .buttonStyle(.plain)
204 }
205 }
206 .frame(width: 520, height: 360)
207 .onExitCommand { dismiss() }
208 }
209}