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