This commit is contained in:
Emilio Peláez 2022-04-19 12:50:06 +02:00
parent 10b0f7f07a
commit 112cd63917
2 changed files with 47 additions and 0 deletions

View File

@ -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<AsyncStream<EventType>> {
events(for: name).filter { $0 == type }

View File

@ -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) {