Sources/Orgstar/Keys.swift

393d4d261fef7e5ac49bfe434dff59504a6b3544
orgstar/Sources/Orgstar/Keys.swift

336 lines · 14634 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(commands: commands, request: request)
 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. Any window with an echo area can show it.
118struct PromptView: View {
119    let commands: AppCommands
120    let request: PromptRequest
121    @State private var answer = ""
122    @FocusState private var answerFocused: Bool
123    /// The highlighted choice, moved by ↑/↓ or C-p/C-n.
124    @State private var selected = 0
125    /// The highlight was moved, so Return answers with it even where any text is accepted.
126    @State private var moved = false
127
128    private var prompt: Prompt { request.prompt }
129
130    var body: some View {
131        if let fast = prompt.fast {
132            Divider()
133            FastSelectionView(selection: fast, message: prompt.message) { commands.answer($0) }
134        } else {
135            let matches = filteredChoices(prompt.choices)
136            let current = min(selected, matches.count - 1)
137            if !prompt.choices.isEmpty {
138                Divider()
139                ScrollViewReader { proxy in
140                    ScrollView {
141                        LazyVStack(alignment: .leading, spacing: 2) {
142                            ForEach(matches.indices, id: \.self) { index in
143                                let choice = matches[index]
144                                Button {
145                                    if prompt.completionSeparator != nil { complete(choice) } else { commands.answer(choice) }
146                                } label: {
147                                    Text(choice)
148                                        .frame(maxWidth: .infinity, alignment: .leading)
149                                        .padding(.horizontal, 4)
150                                        .background(index == current ? Color.accentColor.opacity(0.25) : .clear, in: RoundedRectangle(cornerRadius: 3))
151                                        .contentShape(Rectangle())
152                                }
153                                .buttonStyle(.plain)
154                                .font(.system(.callout, design: .monospaced))
155                                .accessibilityAddTraits(index == current ? .isSelected : [])
156                            }
157                        }
158                        .padding(10)
159                    }
160                    .frame(maxHeight: 200)
161                    .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } }
162                }
163            }
164            if let read = prompt.date {
165                Divider()
166                DatePickerView(answer: answer, read: read) { commands.answer($0) }
167            }
168            Divider()
169            HStack(spacing: 6) {
170                Text(prompt.message).font(.system(.callout, design: .monospaced)).foregroundStyle(.secondary)
171                    .lineLimit(1)
172                    .truncationMode(.middle)
173                TextField("", text: $answer)
174                    .frame(minWidth: 240)
175                    .textFieldStyle(.plain)
176                    .font(.system(.callout, design: .monospaced))
177                    .focused($answerFocused)
178                    .onSubmit {
179                        if current >= 0, moved || prompt.requireMatch {
180                            commands.answer(matches[current])
181                        } else if prompt.choices.isEmpty || !prompt.requireMatch {
182                            commands.answer(answer)
183                        }
184                    }
185                    .onKeyPress(.tab) {
186                        guard current >= 0 else { return .ignored }
187                        complete(matches[current])
188                        return .handled
189                    }
190                    .movesSelection(Binding(get: { selected }, set: { selected = $0; moved = true }), current: current, count: matches.count)
191                    .onKeyPress(keys: [.leftArrow, .rightArrow, .upArrow, .downArrow]) { press in
192                        guard let read = prompt.date, press.modifiers == .shift else { return .ignored }
193                        let days = [KeyEquivalent.leftArrow: -1, .rightArrow: 1, .upArrow: -7, .downArrow: 7][press.key]!
194                        answer = DatePickerView.shifted(answer, read, by: days)
195                        return .handled
196                    }
197                    .onExitCommand { commands.answer(nil) }
198                    .onChange(of: answer) {
199                        selected = 0
200                        moved = false
201                    }
202                if !prompt.choices.isEmpty {
203                    Text(verbatim: "\(max(current + 1, 0))/\(matches.count)")
204                        .font(.system(.callout, design: .monospaced))
205                        .foregroundStyle(.secondary)
206                        .accessibilityLabel("Choice \(max(current + 1, 0)) of \(matches.count)")
207                }
208            }
209            .padding(.horizontal, 10)
210            .padding(.vertical, 4)
211            .onAppear {
212                answer = prompt.initial
213                answerFocused = true
214            }
215        }
216    }
217
218    /// What completion matches: the text after the last separator, or all of it.
219    private func completing(_ separator: Character?) -> Substring {
220        guard let separator, let last = answer.lastIndex(of: separator) else { return answer[...] }
221        return answer[answer.index(after: last)...]
222    }
223
224    /// Puts `choice` in place of what's being completed; with a separator, adds one after it.
225    func complete(_ choice: String) {
226        guard let separator = prompt.completionSeparator else {
227            answer = choice
228            return
229        }
230        let start = answer.lastIndex(of: separator).map { answer.index(after: $0) } ?? answer.startIndex
231        answer = String(answer[..<start]) + (start == answer.startIndex ? String(separator) : "") + choice + String(separator)
232    }
233
234    /// Choices matching what's typed, best first.
235    func filteredChoices(_ choices: [String]) -> [String] {
236        let typed = String(completing(prompt.completionSeparator))
237        guard !typed.isEmpty else { return choices }
238        return choices.compactMap { choice in FuzzyMatch.score(typed, choice).map { (choice, $0) } }
239            .sorted { $0.1 > $1.1 }
240            .map(\.0)
241    }
242}
243
244/// Messages: the echo area's recent messages, newest last (`view-echo-area-messages`).
245struct MessagesView: View {
246    let messages: [String]
247    @Environment(\.dismiss) private var dismiss
248
249    var body: some View {
250        VStack(alignment: .leading, spacing: 0) {
251            Text("Messages").font(.headline).padding(12)
252            Divider()
253            if messages.isEmpty {
254                ContentUnavailableView("No messages", systemImage: "text.bubble")
255            } else {
256                ScrollView {
257                    Text(messages.joined(separator: "\n"))
258                        .font(.system(.callout, design: .monospaced))
259                        .textSelection(.enabled)
260                        .frame(maxWidth: .infinity, alignment: .leading)
261                        .padding(12)
262                }
263                .defaultScrollAnchor(.bottom)
264            }
265            Divider()
266            HStack {
267                Spacer()
268                Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
269            }
270            .padding(12)
271        }
272        .frame(width: 560, height: 360)
273    }
274}
275
276/// Commands this build leaves out of the palette and menus; their keys say so when pressed.
277#if APPSTORE
278let hiddenCommandIDs = AppStoreCommands.hidden
279#else
280let hiddenCommandIDs: Set<String> = []
281#endif
282
283/// M-x and ⇧⌘P: every command by title, with its keys.
284struct PaletteView: View {
285    let commands: AppCommands
286    let run: (String) -> Void
287    @State private var query = ""
288    /// The highlighted match, moved by ↑/↓ or C-p/C-n and run by Return.
289    @State private var selected = 0
290    @Environment(\.dismiss) private var dismiss
291
292    private var matches: [EditorCommand] {
293        let scored: [(command: EditorCommand, score: Int)] = EditorCommands.all.filter { $0.inPalette && !hiddenCommandIDs.contains($0.id) }.compactMap { command in
294            guard let score = FuzzyMatch.score(query, command.localizedTitle) ?? FuzzyMatch.score(query, command.title) else { return nil }
295            return (command, score)
296        }
297        return scored.sorted { $0.score != $1.score ? $0.score > $1.score : $0.command.localizedTitle < $1.command.localizedTitle }.map(\.command)
298    }
299
300    var body: some View {
301        let matches = matches
302        let current = min(selected, matches.count - 1)
303        VStack(spacing: 0) {
304            TextField("Run command", text: $query)
305                .textFieldStyle(.plain)
306                .font(.title3)
307                .padding(12)
308                .onSubmit { if current >= 0 { run(matches[current].id) } }
309                .movesSelection($selected, current: current, count: matches.count)
310                .onChange(of: query) { selected = 0 }
311            Divider()
312            ScrollViewReader { proxy in
313                List(matches.indices, id: \.self) { index in
314                    let command = matches[index]
315                    Button {
316                        run(command.id)
317                    } label: {
318                        HStack {
319                            Text(command.localizedTitle)
320                            Spacer()
321                            if let keys = commands.keyLabel(for: command.id) {
322                                Text(keys).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
323                            }
324                        }
325                        .contentShape(Rectangle())
326                    }
327                    .buttonStyle(.plain)
328                    .selectedRow(index == current)
329                }
330                .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } }
331            }
332        }
333        .frame(width: 520, height: 360)
334        .onExitCommand { dismiss() }
335    }
336}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form