示例工程 39-focus-keyboard-commands

39-focus-keyboard-commands/Sources/Ch39Kit/Keyboard.swift

swift · 4.3 KB

import SwiftUI
 
/// 一次按键的抽象:字符 + 修饰键。用于把快捷键映射成命令。
public struct KeyInput: Hashable, Sendable {
    public let key: String
    public let command: Bool
    public let shift: Bool
    public let option: Bool
    public let control: Bool
 
    public init(
        key: String,
        command: Bool = false,
        shift: Bool = false,
        option: Bool = false,
        control: Bool = false
    ) {
        self.key = key
        self.command = command
        self.shift = shift
        self.option = option
        self.control = control
    }
 
    public var display: String {
        var parts: [String] = []
        if control { parts.append("⌃") }
        if option { parts.append("⌥") }
        if shift { parts.append("⇧") }
        if command { parts.append("⌘") }
        parts.append(key.uppercased())
        return parts.joined()
    }
}
 
public enum KeyCommand: String, CaseIterable, Sendable {
    case newDocument
    case search
    case closeWindow
    case delete
    case help
}
 
/// 快捷键表:单一真相,菜单与帮助面板都读它。
public struct Keymap: Sendable {
    public static let entries: [(input: KeyInput, command: KeyCommand)] = [
        (KeyInput(key: "n", command: true), .newDocument),
        (KeyInput(key: "f", command: true), .search),
        (KeyInput(key: "w", command: true), .closeWindow),
        (KeyInput(key: "delete", command: false), .delete),
        (KeyInput(key: "/", command: true, shift: true), .help),
    ]
 
    public static func resolve(_ input: KeyInput) -> KeyCommand? {
        entries.first { $0.input == input }?.command
    }
 
    public static func input(for command: KeyCommand) -> KeyInput? {
        entries.first { $0.command == command }?.input
    }
}
 
/// 搜索框:`@FocusState` 控制焦点,Esc 退出输入。
public struct FocusableSearch: View {
    @State private var text = ""
    @FocusState private var focused: Bool
 
    public init() {}
 
    public var body: some View {
        TextField("搜索", text: $text)
            .textFieldStyle(.roundedBorder)
            .focused($focused)
            .onAppear { focused = true }
            .onKeyPress(.escape) {
                focused = false
                return .handled
            }
            .onSubmit {
                // 中文输入法提交时才触发,避免组合期间误判。
            }
    }
}
 
/// 帮助面板:列出快捷键,数据来自 `Keymap`。
public struct ShortcutCard: View {
    public init() {}
 
    public var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("键盘快捷键")
                .font(.system(size: 18, weight: .semibold))
            ForEach(KeyCommand.allCases, id: \.self) { command in
                HStack(spacing: 12) {
                    Text(label(for: command))
                        .font(.system(size: 12))
                    Spacer()
                    Text(Keymap.input(for: command)?.display ?? "—")
                        .font(.system(size: 12, design: .monospaced))
                        .padding(.horizontal, 6)
                        .padding(.vertical, 2)
                        .background(.quaternary, in: RoundedRectangle(cornerRadius: 4))
                }
            }
        }
        .padding(20)
        .frame(width: 300)
        .background(Color.white, in: RoundedRectangle(cornerRadius: 12))
        .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(.quaternary))
    }
 
    private func label(for command: KeyCommand) -> String {
        switch command {
        case .newDocument: "新建文档"
        case .search: "搜索"
        case .closeWindow: "关闭窗口"
        case .delete: "删除"
        case .help: "帮助"
        }
    }
}
 
/// App 级菜单:命令与快捷键在 `Commands` 中声明。
public struct LibraryCommands: Commands {
    public init() {}
 
    public var body: some Commands {
        CommandGroup(after: .newItem) {
            Button("搜索") {}
                .keyboardShortcut("f", modifiers: .command)
        }
        CommandMenu("文档") {
            Button("新建") {}
                .keyboardShortcut("n", modifiers: .command)
            Divider()
            Button("删除") {}
                .keyboardShortcut(.delete, modifiers: [])
        }
    }
}