Sources/Orgstar/Keys.swift
267 lines · 12014 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(labelColor)
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 slot: String {
146 switch state {
147 case "insert": "state-insert"
148 case "replace": "state-replace"
149 case "visual", "visual-line", "visual-block": "state-visual"
150 default: "state-normal"
151 }
152 }
153
154 private var color: Color {
155 theme.color(slot) ?? ["state-insert": Color.green, "state-replace": .red, "state-visual": .orange][slot] ?? .blue
156 }
157
158 /// The theme's background on light fills, white on dark ones: whichever contrasts more.
159 private var labelColor: Color {
160 let (theme, slot) = (theme, slot)
161 return theme.dynamic(.white) { dark in
162 let colors = dark ? theme.dark : theme.light
163 guard let fill = colors[slot], let background = colors["background"] else { return nil }
164 let white = RGBA(red: 1, green: 1, blue: 1)
165 return Self.contrast(background, fill) > Self.contrast(white, fill) ? background : white
166 }
167 }
168
169 /// The WCAG contrast ratio of two opaque colors.
170 nonisolated static func contrast(_ a: RGBA, _ b: RGBA) -> Double {
171 func luminance(_ c: RGBA) -> Double {
172 let linear = [c.red, c.green, c.blue].map { $0 <= 0.03928 ? $0 / 12.92 : pow(($0 + 0.055) / 1.055, 2.4) }
173 return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]
174 }
175 let (x, y) = (luminance(a), luminance(b))
176 return (max(x, y) + 0.05) / (min(x, y) + 0.05)
177 }
178}
179
180extension EchoArea {
181 /// What completion matches: the text after the last separator, or all of it.
182 private func completing(_ separator: Character?) -> Substring {
183 guard let separator, let last = answer.lastIndex(of: separator) else { return answer[...] }
184 return answer[answer.index(after: last)...]
185 }
186
187 /// Puts `choice` in place of what's being completed; with a separator, adds one after it.
188 func complete(_ choice: String, _ prompt: Prompt) {
189 guard let separator = prompt.completionSeparator else {
190 answer = choice
191 return
192 }
193 let start = answer.lastIndex(of: separator).map { answer.index(after: $0) } ?? answer.startIndex
194 answer = String(answer[..<start]) + (start == answer.startIndex ? String(separator) : "") + choice + String(separator)
195 }
196
197 /// Choices matching what's typed, best first.
198 func filteredChoices(_ choices: [String]) -> [String] {
199 let typed = String(completing(commands.prompt?.prompt.completionSeparator))
200 guard !typed.isEmpty else { return choices }
201 return choices.compactMap { choice in FuzzyMatch.score(typed, choice).map { (choice, $0) } }
202 .sorted { $0.1 > $1.1 }
203 .map(\.0)
204 }
205}
206
207/// Commands this build leaves out of the palette and menus; their keys say so when pressed.
208#if APPSTORE
209let hiddenCommandIDs = AppStoreCommands.hidden
210#else
211let hiddenCommandIDs: Set<String> = []
212#endif
213
214/// M-x and ⇧⌘P: every command by title, with its keys.
215struct PaletteView: View {
216 let commands: AppCommands
217 let run: (String) -> Void
218 @State private var query = ""
219 /// The highlighted match, moved by ↑/↓ or C-p/C-n and run by Return.
220 @State private var selected = 0
221 @Environment(\.dismiss) private var dismiss
222
223 private var matches: [EditorCommand] {
224 let scored: [(command: EditorCommand, score: Int)] = EditorCommands.all.filter { $0.inPalette && !hiddenCommandIDs.contains($0.id) }.compactMap { command in
225 guard let score = FuzzyMatch.score(query, command.localizedTitle) ?? FuzzyMatch.score(query, command.title) else { return nil }
226 return (command, score)
227 }
228 return scored.sorted { $0.score != $1.score ? $0.score > $1.score : $0.command.localizedTitle < $1.command.localizedTitle }.map(\.command)
229 }
230
231 var body: some View {
232 let matches = matches
233 let current = min(selected, matches.count - 1)
234 VStack(spacing: 0) {
235 TextField("Run command", text: $query)
236 .textFieldStyle(.plain)
237 .font(.title3)
238 .padding(12)
239 .onSubmit { if current >= 0 { run(matches[current].id) } }
240 .movesSelection($selected, current: current, count: matches.count)
241 .onChange(of: query) { selected = 0 }
242 Divider()
243 ScrollViewReader { proxy in
244 List(matches.indices, id: \.self) { index in
245 let command = matches[index]
246 Button {
247 run(command.id)
248 } label: {
249 HStack {
250 Text(command.localizedTitle)
251 Spacer()
252 if let keys = commands.keyLabel(for: command.id) {
253 Text(keys).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
254 }
255 }
256 .contentShape(Rectangle())
257 }
258 .buttonStyle(.plain)
259 .selectedRow(index == current)
260 }
261 .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } }
262 }
263 }
264 .frame(width: 520, height: 360)
265 .onExitCommand { dismiss() }
266 }
267}