Sources/Orgstar/Keys.swift

9a511fe327c1d8fb2a0d773d34e47e3a8ee09d7b
orgstar/Sources/Orgstar/Keys.swift history · blame · raw

179 lines · 7008 bytes

  1import OrgApp
  2import OrgCore
  3import OrgEditorAppKit
  4import SwiftUI
  5
  6struct KeyHint: Hashable {
  7    let key: String
  8    let title: String
  9}
 10
 11/// The minibuffer line: a pending prefix, or the last message for a few seconds. After a
 12/// short pause on a prefix, the keys that can follow it.
 13struct EchoArea: View {
 14    let commands: AppCommands
 15    @State private var showingHints = false
 16    @State private var answer = ""
 17    @FocusState private var answerFocused: Bool
 18
 19    var body: some View {
 20        VStack(alignment: .leading, spacing: 0) {
 21            if showingHints, commands.pendingKeys != nil, !commands.keyHints.isEmpty {
 22                Divider()
 23                LazyVGrid(columns: [GridItem(.adaptive(minimum: 220), alignment: .leading)], alignment: .leading, spacing: 4) {
 24                    ForEach(commands.keyHints, id: \.self) { hint in
 25                        HStack(spacing: 8) {
 26                            Text(hint.key).font(.system(.body, design: .monospaced)).foregroundStyle(.tint)
 27                            Text(hint.title).foregroundStyle(hint.title == "+prefix" ? .secondary : .primary).lineLimit(1)
 28                        }
 29                    }
 30                }
 31                .padding(10)
 32            }
 33            if let request = commands.prompt {
 34                if !request.prompt.choices.isEmpty {
 35                    Divider()
 36                    let matches = filteredChoices(request.prompt.choices)
 37                    ScrollView {
 38                        VStack(alignment: .leading, spacing: 2) {
 39                            ForEach(matches.prefix(12), id: \.self) { choice in
 40                                Button(choice) { commands.answer(choice) }
 41                                    .buttonStyle(.plain)
 42                                    .font(.system(.callout, design: .monospaced))
 43                                    .foregroundStyle(choice == matches.first ? .primary : .secondary)
 44                            }
 45                        }
 46                        .frame(maxWidth: .infinity, alignment: .leading)
 47                        .padding(10)
 48                    }
 49                    .frame(maxHeight: 200)
 50                }
 51                Divider()
 52                HStack(spacing: 6) {
 53                    Text(request.prompt.message).font(.system(.callout, design: .monospaced)).foregroundStyle(.secondary)
 54                    TextField("", text: $answer)
 55                        .textFieldStyle(.plain)
 56                        .font(.system(.callout, design: .monospaced))
 57                        .focused($answerFocused)
 58                        .onSubmit {
 59                            if request.prompt.choices.isEmpty {
 60                                commands.answer(answer)
 61                            } else if let first = filteredChoices(request.prompt.choices).first {
 62                                commands.answer(first)
 63                            }
 64                        }
 65                        .onExitCommand { commands.answer(nil) }
 66                }
 67                .padding(.horizontal, 10)
 68                .padding(.vertical, 4)
 69                .onAppear {
 70                    answer = request.prompt.initial
 71                    answerFocused = true
 72                }
 73                .id(request.id)
 74            } else if commands.editorState != nil || commands.pendingKeys != nil || commands.message != nil {
 75                Divider()
 76                HStack(spacing: 8) {
 77                    if let state = commands.editorState { StateTag(state: state) }
 78                    Text(commands.pendingKeys.map { $0 + "-" } ?? commands.message ?? "")
 79                        .font(.system(.callout, design: .monospaced))
 80                        .lineLimit(1)
 81                }
 82                .padding(.horizontal, 10)
 83                .padding(.vertical, 4)
 84                .frame(maxWidth: .infinity, alignment: .leading)
 85            }
 86        }
 87        .background(.bar)
 88        .task(id: commands.pendingKeys) {
 89            showingHints = false
 90            guard commands.pendingKeys != nil else { return }
 91            try? await Task.sleep(for: .milliseconds(600))
 92            if !Task.isCancelled { showingHints = true }
 93        }
 94    }
 95}
 96
 97/// The evil state, as Doom's modeline shows it.
 98struct StateTag: View {
 99    let state: String
100
101    var body: some View {
102        Text(label)
103            .font(.system(.caption, design: .monospaced).bold())
104            .foregroundStyle(.white)
105            .padding(.horizontal, 6)
106            .padding(.vertical, 1)
107            .background(color, in: RoundedRectangle(cornerRadius: 4))
108            .accessibilityLabel("\(label.capitalized) state")
109    }
110
111    private var label: String {
112        switch state {
113        case "visual-line": "V-LINE"
114        default: state.uppercased()
115        }
116    }
117
118    private var color: Color {
119        switch state {
120        case "insert": .green
121        case "visual", "visual-line": .orange
122        default: .blue
123        }
124    }
125}
126
127extension EchoArea {
128    /// Choices matching what's typed, best first.
129    func filteredChoices(_ choices: [String]) -> [String] {
130        guard !answer.isEmpty else { return choices }
131        return choices.compactMap { choice in FuzzyMatch.score(answer, choice).map { (choice, $0) } }
132            .sorted { $0.1 > $1.1 }
133            .map(\.0)
134    }
135}
136
137/// M-x and ⇧⌘P: every command by title, with its keys.
138struct PaletteView: View {
139    let keymap: Keymap
140    let run: (String) -> Void
141    @State private var query = ""
142    @Environment(\.dismiss) private var dismiss
143
144    private var matches: [EditorCommand] {
145        let scored: [(command: EditorCommand, score: Int)] = EditorCommands.all.filter(\.inPalette).compactMap { command in
146            guard let score = FuzzyMatch.score(query, command.title) else { return nil }
147            return (command, score)
148        }
149        return scored.sorted { $0.score != $1.score ? $0.score > $1.score : $0.command.title < $1.command.title }.map(\.command)
150    }
151
152    var body: some View {
153        let matches = matches
154        VStack(spacing: 0) {
155            TextField("Run command", text: $query)
156                .textFieldStyle(.plain)
157                .font(.title3)
158                .padding(12)
159                .onSubmit { if let first = matches.first { run(first.id) } }
160            Divider()
161            List(matches, id: \.id) { command in
162                Button {
163                    run(command.id)
164                } label: {
165                    HStack {
166                        Text(command.title)
167                        Spacer()
168                        if let keys = keymap.keys(for: command.id) {
169                            Text(KeySequence.format(keys)).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary)
170                        }
171                    }
172                }
173                .buttonStyle(.plain)
174            }
175        }
176        .frame(width: 520, height: 360)
177        .onExitCommand { dismiss() }
178    }
179}