Sources/Orgstar/Keys.swift
374 lines · 15869 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 !prompt.choices.isEmpty {
140 Divider()
141 ScrollViewReader { proxy in
142 ScrollView {
143 LazyVStack(alignment: .leading, spacing: 2) {
144 ForEach(matches.indices, id: \.self) { index in
145 let choice = matches[index]
146 Button {
147 if prompt.completionSeparator != nil { complete(choice) } else { reply(choice) }
148 } label: {
149 Text(choice)
150 .frame(maxWidth: .infinity, alignment: .leading)
151 .padding(.horizontal, 4)
152 .background(index == current ? Color.accentColor.opacity(0.25) : .clear, in: RoundedRectangle(cornerRadius: 3))
153 .contentShape(Rectangle())
154 }
155 .buttonStyle(.plain)
156 .font(.system(.callout, design: .monospaced))
157 .accessibilityAddTraits(index == current ? .isSelected : [])
158 }
159 }
160 .padding(10)
161 }
162 .frame(maxHeight: 200)
163 .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } }
164 }
165 }
166 if let read = prompt.date {
167 Divider()
168 DatePickerView(answer: answer, read: read) { reply($0) }
169 }
170 Divider()
171 HStack(spacing: 6) {
172 Text(prompt.message).font(.system(.callout, design: .monospaced)).foregroundStyle(.secondary)
173 .lineLimit(1)
174 .truncationMode(.middle)
175 TextField("", text: $answer)
176 .frame(minWidth: 240)
177 .textFieldStyle(.plain)
178 .font(.system(.callout, design: .monospaced))
179 .focused($answerFocused)
180 .onSubmit {
181 if current >= 0, moved || prompt.requireMatch {
182 reply(matches[current])
183 } else if prompt.choices.isEmpty || !prompt.requireMatch {
184 reply(answer)
185 }
186 }
187 .onKeyPress(.tab) {
188 guard current >= 0 else { return .ignored }
189 complete(matches[current])
190 return .handled
191 }
192 .movesSelection(Binding(get: { selected }, set: { selected = $0; moved = true }), current: current, count: matches.count)
193 .onKeyPress(keys: [.leftArrow, .rightArrow, .upArrow, .downArrow]) { press in
194 guard let read = prompt.date, press.modifiers == .shift else { return .ignored }
195 let days = [KeyEquivalent.leftArrow: -1, .rightArrow: 1, .upArrow: -7, .downArrow: 7][press.key]!
196 answer = DatePickerView.shifted(answer, read, by: days)
197 return .handled
198 }
199 .onExitCommand { reply(nil) }
200 .onChange(of: answer) {
201 selected = 0
202 moved = false
203 }
204 if !prompt.choices.isEmpty {
205 Text(verbatim: "\(max(current + 1, 0))/\(matches.count)")
206 .font(.system(.callout, design: .monospaced))
207 .foregroundStyle(.secondary)
208 .accessibilityLabel("Choice \(max(current + 1, 0)) of \(matches.count)")
209 }
210 }
211 .padding(.horizontal, 10)
212 .padding(.vertical, 4)
213 .onAppear {
214 answer = prompt.initial
215 answerFocused = true
216 }
217 }
218 }
219
220 /// What completion matches: the text after the last separator, or all of it.
221 private func completing(_ separator: Character?) -> Substring {
222 guard let separator, let last = answer.lastIndex(of: separator) else { return answer[...] }
223 return answer[answer.index(after: last)...]
224 }
225
226 /// Puts `choice` in place of what's being completed; with a separator, adds one after it.
227 func complete(_ choice: String) {
228 guard let separator = prompt.completionSeparator else {
229 answer = choice
230 return
231 }
232 let start = answer.lastIndex(of: separator).map { answer.index(after: $0) } ?? answer.startIndex
233 answer = String(answer[..<start]) + (start == answer.startIndex ? String(separator) : "") + choice + String(separator)
234 }
235
236 /// Choices matching what's typed, best first.
237 func filteredChoices(_ choices: [String]) -> [String] {
238 let typed = String(completing(prompt.completionSeparator))
239 guard !typed.isEmpty else { return choices }
240 return choices.compactMap { choice in FuzzyMatch.score(typed, choice).map { (choice, $0) } }
241 .sorted { $0.1 > $1.1 }
242 .map(\.0)
243 }
244}
245
246/// A window's own question at its foot, styled as the echo area, for windows without one.
247struct PromptBar: View {
248 @Binding var request: PromptRequest?
249 @Environment(\.orgTheme) private var theme
250 @Environment(\.colorScheme) private var colorScheme
251
252 var body: some View {
253 if let current = request {
254 VStack(alignment: .leading, spacing: 0) {
255 PromptView(request: current) { text in
256 request = nil
257 current.reply(text)
258 }
259 .id(current.id)
260 }
261 .foregroundStyle(theme.color("modeline-foreground") ?? .primary)
262 .background { if let bg = theme.color("modeline-background", in: colorScheme) { bg } else { Rectangle().fill(.bar) } }
263 }
264 }
265}
266
267/// Messages: the echo area's recent messages, newest last (`view-echo-area-messages`).
268struct MessagesView: View {
269 let messages: [String]
270 @Environment(\.dismiss) private var dismiss
271
272 var body: some View {
273 VStack(alignment: .leading, spacing: 0) {
274 Text("Messages").font(.headline).padding(12)
275 Divider()
276 if messages.isEmpty {
277 ContentUnavailableView("No Messages", systemImage: "text.bubble")
278 } else {
279 ScrollView {
280 Text(messages.joined(separator: "\n"))
281 .font(.system(.callout, design: .monospaced))
282 .textSelection(.enabled)
283 .frame(maxWidth: .infinity, alignment: .leading)
284 .padding(12)
285 }
286 .defaultScrollAnchor(.bottom)
287 }
288 Divider()
289 HStack {
290 Spacer()
291 Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
292 }
293 .padding(12)
294 }
295 .frame(width: 560, height: 360)
296 }
297}
298
299/// Commands this build leaves out of the palette and menus; their keys say so when pressed.
300#if APPSTORE
301let hiddenCommandIDs = AppStoreCommands.hidden
302#else
303let hiddenCommandIDs: Set<String> = []
304#endif
305
306/// M-x and ⇧⌘P: every command by title, with its keys. An empty query lists the commands run
307/// from here most recently, then the rest; matches rank commands used often a little higher.
308struct PaletteView: View {
309 let commands: AppCommands
310 let run: (String) -> Void
311 @State private var query = ""
312 /// The highlighted match, moved by ↑/↓ or C-p/C-n and run by Return.
313 @State private var selected = 0
314 @Environment(\.dismiss) private var dismiss
315
316 private var matches: (recent: [EditorCommand], rest: [EditorCommand]) {
317 CommandRanking.rank(EditorCommands.all.filter { $0.inPalette && !hiddenCommandIDs.contains($0.id) }, query: query,
318 id: \.id, titles: { [$0.localizedTitle, $0.title] })
319 }
320
321 var body: some View {
322 let ranked = matches
323 let matches = ranked.recent + ranked.rest
324 let current = min(selected, matches.count - 1)
325 VStack(spacing: 0) {
326 TextField("Run command", text: $query)
327 .textFieldStyle(.plain)
328 .font(.title3)
329 .padding(12)
330 .onSubmit { if current >= 0 { choose(matches[current].id) } }
331 .movesSelection($selected, current: current, count: matches.count)
332 .onChange(of: query) { selected = 0 }
333 Divider()
334 ScrollViewReader { proxy in
335 List {
336 if !ranked.recent.isEmpty {
337 Section("Recent") { rows(matches, 0..<ranked.recent.count, current) }
338 Section("All Commands") { rows(matches, ranked.recent.count..<matches.count, current) }
339 } else {
340 rows(matches, matches.indices, current)
341 }
342 }
343 .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } }
344 }
345 }
346 .frame(width: 520, height: 360)
347 .onExitCommand { dismiss() }
348 }
349
350 private func rows(_ matches: [EditorCommand], _ indices: Range<Int>, _ current: Int) -> some View {
351 ForEach(indices, id: \.self) { index in
352 let command = matches[index]
353 Button {
354 choose(command.id)
355 } label: {
356 HStack {
357 Text(command.localizedTitle)
358 Spacer()
359 if let keys = commands.keyLabel(for: command.id) {
360 Text(keys).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
361 }
362 }
363 .contentShape(Rectangle())
364 }
365 .buttonStyle(.plain)
366 .selectedRow(index == current)
367 }
368 }
369
370 private func choose(_ id: String) {
371 CommandUsage.shared.record(id)
372 run(id)
373 }
374}