sindresorhus / KeyboardShortcuts

⌨️ Add user-customizable global keyboard shortcuts (hotkeys) to your macOS app in minutes
https://swiftpackageindex.com/sindresorhus/KeyboardShortcuts/documentation/keyboardshortcuts/keyboardshortcuts
MIT License
1.94k stars 181 forks source link

What's the best way to achive in app shortcuts with the package #182

Open gavin1818 opened 1 month ago

gavin1818 commented 1 month ago

Description

First of all, thank you for this amazing package! It has been incredibly useful in my project. However, I have a requirement that I am hoping to get some guidance on.

I need to create keyboard shortcuts that are only active when my app is in use. I want to avoid having these shortcuts override global shortcuts or interfere with other applications. I noticed that there is a brief explanation in the readme about this, but it does not provide much detail. Could you please provide more detailed guidance or examples on how to achieve in-app specific shortcuts using this package?

Here's a summary of what I have so far:

import KeyboardShortcuts

extension KeyboardShortcuts.Name {
    static let textSearch = Self("textSearch", default: .init(.f, modifiers: [.command]))
    // ... other shortcuts
}
struct TextEditorSearchBar: View {
    @EnvironmentObject var searchState: TextEditorSearchBarState
    @FocusState private var isSearchFieldFocused: Bool

    var body: some View {
        HStack(spacing: 0) { // Set spacing to 0 to remove padding between elements
            TextField("Search...", text: $searchState.searchText)
                .focused($isSearchFieldFocused)
        }
        .onAppear {
            // Register the keyboard shortcut
            KeyboardShortcuts.onKeyUp(for: .textSearch) {
                isSearchFieldFocused = true
            }
        }
    }
}

Goal

I want to ensure that these shortcuts are only active when my app is in use and do not interfere with global shortcuts or other applications.

Questions

  1. What is the best practice to achieve in-app specific shortcuts using this package?
  2. Can you provide a detailed example or guidance on implementing this?

Thank you in advance for your assistance!

sindresorhus commented 1 month ago

The tagline for the project is:

Custom global keyboard shortcuts for your macOS app

Handling local shortcuts is a non-goal.

However, when https://github.com/sindresorhus/KeyboardShortcuts/issues/164 is done, you could use the recorder from this package, store the keyboard shortcut yourself in UserDefaults, and then use the SwiftUI .keyboardShortcut() method.

longseespace commented 1 month ago

This is a terrible, terrible hack, but it works for me.

  1. Disable the shortcut immediately after change, and on startup:
  2. Use .keyboardShortcut() helper here: https://github.com/sindresorhus/KeyboardShortcuts/issues/101#issuecomment-1325196892