diff --git a/Sources/KeyboardShortcuts/KeyboardShortcuts.swift b/Sources/KeyboardShortcuts/KeyboardShortcuts.swift index e1df750..b6a8b7e 100644 --- a/Sources/KeyboardShortcuts/KeyboardShortcuts.swift +++ b/Sources/KeyboardShortcuts/KeyboardShortcuts.swift @@ -429,6 +429,35 @@ extension KeyboardShortcuts { } } + /** + Listen to keyboard shortcut events with the given name and type. + + You can register multiple listeners. + + You can safely call this even if the user has not yet set a keyboard shortcut. It will just be inactive until they do. + + Ending the async sequence will stop the listener. For example, in the below example, the listener will stop when the view disappears. + + ```swift + import SwiftUI + import KeyboardShortcuts + + struct ContentView: View { + @State private var isUnicornMode = false + + var body: some View { + Text(isUnicornMode ? "🦄" : "🐴") + .task { + for await event in KeyboardShortcuts.events(for: .toggleUnicornMode) where event == .keyUp { + isUnicornMode.toggle() + } + } + } + } + ``` + + - Note: This method is not affected by `.removeAllHandlers()`. + */ @available(macOS 10.15, *) public static func events(_ type: EventType, for name: Name) -> AsyncFilterSequence> { events(for: name).filter { $0 == type } diff --git a/Sources/KeyboardShortcuts/ViewModifiers.swift b/Sources/KeyboardShortcuts/ViewModifiers.swift index ff00de3..95d2866 100644 --- a/Sources/KeyboardShortcuts/ViewModifiers.swift +++ b/Sources/KeyboardShortcuts/ViewModifiers.swift @@ -2,6 +2,15 @@ import SwiftUI @available(macOS 12, *) extension View { + /** + Register a listener for keyboard shortcut events with the given name. + + You can safely call this even if the user has not yet set a keyboard shortcut. It will just be inactive until they do. + + The listener will stop automatically when the view disappears. + + - Note: This method is not affected by `.removeAllHandlers()`. + */ public func onKeyboardShortcut(_ shortcut: KeyboardShortcuts.Name, perform: @escaping (KeyboardShortcuts.EventType) -> Void) -> some View { task { for await event in KeyboardShortcuts.events(for: shortcut) { @@ -10,6 +19,15 @@ extension View { } } + /** + Register a listener for keyboard shortcut events with the given name and type. + + You can safely call this even if the user has not yet set a keyboard shortcut. It will just be inactive until they do. + + The listener will stop automatically when the view disappears. + + - Note: This method is not affected by `.removeAllHandlers()`. + */ public func onKeyboardShortcut(_ shortcut: KeyboardShortcuts.Name, type: KeyboardShortcuts.EventType, perform: @escaping () -> Void) -> some View { task { for await _ in KeyboardShortcuts.events(type, for: shortcut) {