Sources/Orgstar/Keys.swift
388 lines · 16564 bytes
1import OrgApp
2import OrgCore
3import OrgEditorAppKit
4import OrgPresentation
5import SwiftUI
6
7struct KeyHint: Hashable {
8 let key: String
9 let title: String
10}
11
12/// The minibuffer line: a question, a pending prefix, or the last message until the next key
13/// or click. After a short pause on a prefix, the keys that can follow it.
14struct EchoArea: View {
15 let commands: AppCommands
16 @Environment(\.orgTheme) private var theme
17 @Environment(\.colorScheme) private var colorScheme
18 @State private var showingHints = false
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 == "+prefix" ? String(localized: "+prefix", comment: "Key hint: the key starts a longer sequence") : hint.title)
29 .foregroundStyle(hint.title == "+prefix" ? .secondary : .primary).lineLimit(1)
30 }
31 }
32 }
33 .padding(10)
34 }
35 if let request = commands.prompt {
36 PromptView(request: request, reply: commands.answer)
37 .id(request.id)
38 } else if let text = commands.pendingKeys.map({ $0 + "-" }) ?? commands.message {
39 Text(text)
40 .font(.system(.callout, design: .monospaced))
41 .lineLimit(1)
42 .padding(.horizontal, 10)
43 .padding(.vertical, 4)
44 .frame(maxWidth: .infinity, alignment: .leading)
45 }
46 }
47 .foregroundStyle(theme.color("modeline-foreground") ?? .primary)
48 .background { if let bg = theme.color("modeline-background", in: colorScheme) { bg } else { Rectangle().fill(.bar) } }
49 .task(id: commands.pendingKeys) {
50 showingHints = false
51 guard commands.pendingKeys != nil else { return }
52 try? await Task.sleep(for: .milliseconds(600))
53 if !Task.isCancelled { showingHints = true }
54 }
55 }
56}
57
58/// The evil state, as Doom's modeline shows it.
59struct StateTag: View {
60 let state: String
61 @Environment(\.orgTheme) private var theme
62
63 var body: some View {
64 Text(label)
65 .font(.system(.caption, design: .monospaced).bold())
66 .foregroundStyle(labelColor)
67 .padding(.horizontal, 6)
68 .padding(.vertical, 1)
69 .background(color, in: RoundedRectangle(cornerRadius: 4))
70 .accessibilityLabel("\(label.capitalized) state")
71 }
72
73 private var label: String {
74 switch state {
75 case "visual-line": "V-LINE"
76 case "visual-block": "V-BLOCK"
77 default: state.uppercased()
78 }
79 }
80
81 private var slot: String {
82 switch state {
83 case "insert": "state-insert"
84 case "replace": "state-replace"
85 case "visual", "visual-line", "visual-block": "state-visual"
86 default: "state-normal"
87 }
88 }
89
90 private var color: Color {
91 theme.color(slot) ?? ["state-insert": Color.green, "state-replace": .red, "state-visual": .orange][slot] ?? .blue
92 }
93
94 /// The theme's background on light fills, white on dark ones: whichever contrasts more.
95 private var labelColor: Color {
96 let (theme, slot) = (theme, slot)
97 return theme.dynamic(.white) { dark in
98 let colors = dark ? theme.dark : theme.light
99 guard let fill = colors[slot], let background = colors["background"] else { return nil }
100 let white = RGBA(red: 1, green: 1, blue: 1)
101 return Self.contrast(background, fill) > Self.contrast(white, fill) ? background : white
102 }
103 }
104
105 /// The WCAG contrast ratio of two opaque colors.
106 nonisolated static func contrast(_ a: RGBA, _ b: RGBA) -> Double {
107 func luminance(_ c: RGBA) -> Double {
108 let linear = [c.red, c.green, c.blue].map { $0 <= 0.03928 ? $0 / 12.92 : pow(($0 + 0.055) / 1.055, 2.4) }
109 return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]
110 }
111 let (x, y) = (luminance(a), luminance(b))
112 return (max(x, y) + 0.05) / (min(x, y) + 0.05)
113 }
114}
115
116/// A question a command asks: fast selection, or a text field with its choices, filtered as
117/// it is typed, and a calendar for dates. The echo area shows it, and `PromptBar` in windows
118/// without one.
119struct PromptView: View {
120 let request: PromptRequest
121 /// Ends the prompt with an answer, or nil to cancel.
122 let reply: (String?) -> Void
123 @State private var answer = ""
124 @FocusState private var answerFocused: Bool
125 /// The highlighted choice, moved by ↑/↓ or C-p/C-n.
126 @State private var selected = 0
127 /// The highlight was moved, so Return answers with it even where any text is accepted.
128 @State private var moved = false
129
130 private var prompt: Prompt { request.prompt }
131
132 var body: some View {
133 if let fast = prompt.fast {
134 Divider()
135 FastSelectionView(selection: fast, message: prompt.message) { reply($0) }
136 } else {
137 let matches = filteredChoices(prompt.choices)
138 let current = min(selected, matches.count - 1)
139 if let detail = request.detail {
140 Divider()
141 Text(detail)
142 .font(.system(.callout, design: .monospaced))
143 .frame(maxWidth: .infinity, alignment: .leading)
144 .padding(.horizontal, 10)
145 .padding(.vertical, 6)
146 }
147 if !prompt.choices.isEmpty {
148 Divider()
149 ScrollViewReader { proxy in
150 ScrollView {
151 LazyVStack(alignment: .leading, spacing: 2) {
152 ForEach(matches.indices, id: \.self) { index in
153 let choice = matches[index]
154 Button {
155 if prompt.completionSeparator != nil { complete(choice) } else { reply(choice) }
156 } label: {
157 Text(choice)
158 .frame(maxWidth: .infinity, alignment: .leading)
159 .padding(.horizontal, 4)
160 .background(index == current ? Color.accentColor.opacity(0.25) : .clear, in: RoundedRectangle(cornerRadius: 3))
161 .contentShape(Rectangle())
162 }
163 .buttonStyle(.plain)
164 .font(.system(.callout, design: .monospaced))
165 .accessibilityAddTraits(index == current ? .isSelected : [])
166 }
167 }
168 .padding(10)
169 }
170 .frame(maxHeight: 200)
171 .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } }
172 }
173 }
174 if let read = prompt.date {
175 Divider()
176 DatePickerView(answer: answer, read: read) { reply($0) }
177 }
178 Divider()
179 HStack(spacing: 6) {
180 Text(prompt.message).font(.system(.callout, design: .monospaced)).foregroundStyle(.secondary)
181 .lineLimit(1)
182 .truncationMode(.middle)
183 TextField("", text: $answer)
184 .frame(minWidth: 240)
185 .textFieldStyle(.plain)
186 .font(.system(.callout, design: .monospaced))
187 .focused($answerFocused)
188 .onSubmit {
189 if current >= 0, moved || prompt.requireMatch {
190 reply(matches[current])
191 } else if prompt.choices.isEmpty || !prompt.requireMatch {
192 reply(answer)
193 }
194 }
195 .onKeyPress(.tab) {
196 guard current >= 0 else { return .ignored }
197 complete(matches[current])
198 return .handled
199 }
200 .movesSelection(Binding(get: { selected }, set: { selected = $0; moved = true }), current: current, count: matches.count)
201 .onKeyPress(keys: [.leftArrow, .rightArrow, .upArrow, .downArrow]) { press in
202 guard let read = prompt.date, press.modifiers == .shift else { return .ignored }
203 let days = [KeyEquivalent.leftArrow: -1, .rightArrow: 1, .upArrow: -7, .downArrow: 7][press.key]!
204 answer = DatePickerView.shifted(answer, read, by: days)
205 return .handled
206 }
207 .onExitCommand { reply(nil) }
208 .onChange(of: answer) {
209 selected = 0
210 moved = false
211 }
212 if !prompt.choices.isEmpty {
213 Text(verbatim: "\(max(current + 1, 0))/\(matches.count)")
214 .font(.system(.callout, design: .monospaced))
215 .foregroundStyle(.secondary)
216 .accessibilityLabel("Choice \(max(current + 1, 0)) of \(matches.count)")
217 }
218 }
219 .padding(.horizontal, 10)
220 .padding(.vertical, 4)
221 .onAppear {
222 answer = prompt.initial
223 answerFocused = true
224 }
225 }
226 }
227
228 /// What completion matches: the text after the last separator, or all of it.
229 private func completing(_ separator: Character?) -> Substring {
230 guard let separator, let last = answer.lastIndex(of: separator) else { return answer[...] }
231 return answer[answer.index(after: last)...]
232 }
233
234 /// Puts `choice` in place of what's being completed; with a separator, adds one after it.
235 func complete(_ choice: String) {
236 guard let separator = prompt.completionSeparator else {
237 answer = choice
238 return
239 }
240 let start = answer.lastIndex(of: separator).map { answer.index(after: $0) } ?? answer.startIndex
241 answer = String(answer[..<start]) + (start == answer.startIndex ? String(separator) : "") + choice + String(separator)
242 }
243
244 /// Choices matching what's typed, best first.
245 func filteredChoices(_ choices: [String]) -> [String] {
246 let typed = String(completing(prompt.completionSeparator))
247 guard !typed.isEmpty else { return choices }
248 return choices.compactMap { choice in FuzzyMatch.score(typed, choice).map { (choice, $0) } }
249 .sorted { $0.1 > $1.1 }
250 .map(\.0)
251 }
252}
253
254/// A window's own question at its foot, styled as the echo area, for windows without one.
255struct PromptBar: View {
256 @Binding var request: PromptRequest?
257 @Environment(\.orgTheme) private var theme
258 @Environment(\.colorScheme) private var colorScheme
259
260 var body: some View {
261 if let current = request {
262 VStack(alignment: .leading, spacing: 0) {
263 PromptView(request: current) { text in
264 request = nil
265 current.reply(text)
266 }
267 .id(current.id)
268 }
269 .foregroundStyle(theme.color("modeline-foreground") ?? .primary)
270 .background { if let bg = theme.color("modeline-background", in: colorScheme) { bg } else { Rectangle().fill(.bar) } }
271 }
272 }
273}
274
275/// Messages: the echo area's recent messages, newest last (`view-echo-area-messages`).
276struct MessagesView: View {
277 let messages: [String]
278 @Environment(\.dismiss) private var dismiss
279
280 var body: some View {
281 VStack(alignment: .leading, spacing: 0) {
282 Text("Messages").font(.headline).padding(12)
283 Divider()
284 if messages.isEmpty {
285 ContentUnavailableView("No Messages", systemImage: "text.bubble")
286 } else {
287 ScrollView {
288 Text(messages.joined(separator: "\n"))
289 .font(.system(.callout, design: .monospaced))
290 .textSelection(.enabled)
291 .frame(maxWidth: .infinity, alignment: .leading)
292 .padding(12)
293 }
294 .defaultScrollAnchor(.bottom)
295 }
296 Divider()
297 HStack {
298 Spacer()
299 Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
300 }
301 .padding(12)
302 }
303 .frame(width: 560, height: 360)
304 }
305}
306
307/// Commands this build leaves out of the palette and menus; their keys say so when pressed.
308#if APPSTORE
309let hiddenCommandIDs = AppStoreCommands.hidden
310#else
311let hiddenCommandIDs: Set<String> = []
312#endif
313
314/// M-x and ⇧⌘P: every command by title, with its keys. An empty query lists the commands run
315/// from here most recently, then the rest; matches rank commands used often a little higher.
316struct PaletteView: View {
317 let commands: AppCommands
318 let run: (String) -> Void
319 @State private var query = ""
320 /// The highlighted match, moved by ↑/↓ or C-p/C-n and run by Return.
321 @State private var selected = 0
322 @Environment(\.dismiss) private var dismiss
323
324 private var matches: (recent: [EditorCommand], rest: [EditorCommand]) {
325 // A user command's `when` leaves it out where it doesn't apply.
326 let context = commands.editor?.context()
327 func offered(_ command: EditorCommand) -> Bool {
328 guard case .text(let user as UserCommand) = command.action else { return true }
329 return context.map(user.applies) ?? false
330 }
331 return CommandRanking.rank(EditorCommands.all.filter { $0.inPalette && !hiddenCommandIDs.contains($0.id) && offered($0) }, query: query,
332 id: \.id, titles: { [$0.localizedTitle, $0.title] })
333 }
334
335 var body: some View {
336 let ranked = matches
337 let matches = ranked.recent + ranked.rest
338 let current = min(selected, matches.count - 1)
339 VStack(spacing: 0) {
340 TextField("Run command", text: $query)
341 .textFieldStyle(.plain)
342 .font(.title3)
343 .padding(12)
344 .onSubmit { if current >= 0 { choose(matches[current].id) } }
345 .movesSelection($selected, current: current, count: matches.count)
346 .onChange(of: query) { selected = 0 }
347 Divider()
348 ScrollViewReader { proxy in
349 List {
350 if !ranked.recent.isEmpty {
351 Section("Recent") { rows(matches, 0..<ranked.recent.count, current) }
352 Section("All Commands") { rows(matches, ranked.recent.count..<matches.count, current) }
353 } else {
354 rows(matches, matches.indices, current)
355 }
356 }
357 .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } }
358 }
359 }
360 .frame(width: 520, height: 360)
361 .onExitCommand { dismiss() }
362 }
363
364 private func rows(_ matches: [EditorCommand], _ indices: Range<Int>, _ current: Int) -> some View {
365 ForEach(indices, id: \.self) { index in
366 let command = matches[index]
367 Button {
368 choose(command.id)
369 } label: {
370 HStack {
371 Text(command.localizedTitle)
372 Spacer()
373 if let keys = commands.keyLabel(for: command.id) {
374 Text(keys).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
375 }
376 }
377 .contentShape(Rectangle())
378 }
379 .buttonStyle(.plain)
380 .selectedRow(index == current)
381 }
382 }
383
384 private func choose(_ id: String) {
385 CommandUsage.shared.record(id)
386 run(id)
387 }
388}