Updated AsyncStream function

This commit is contained in:
Emilio Peláez 2022-04-16 16:17:49 +02:00
parent c417404da5
commit d6c12f9208
2 changed files with 33 additions and 16 deletions

View File

@ -396,7 +396,7 @@ extension KeyboardShortcuts {
var body: some View {
Text(isUnicornMode ? "🦄" : "🐴")
.task {
for await _ in KeyboardShortcuts.on(.keyUp, for: .toggleUnicornMode) {
for await event in KeyboardShortcuts.events(for: .toggleUnicornMode) where event == .keyUp {
isUnicornMode.toggle()
}
}
@ -407,6 +407,30 @@ extension KeyboardShortcuts {
- Note: This method is not affected by `.removeAllHandlers()`.
*/
@available(macOS 10.15, *)
public static func events(for name: Name) -> AsyncStream<KeyboardShortcuts.EventType> {
AsyncStream { continuation in
let id = UUID()
streamKeyDownHandlers[name, default: [:]][id] = {
continuation.yield(.keyDown)
}
streamKeyUpHandlers[name, default: [:]][id] = {
continuation.yield(.keyUp)
}
registerShortcutIfNeeded(for: name)
continuation.onTermination = { _ in
streamKeyDownHandlers[name]?[id] = nil
streamKeyUpHandlers[name]?[id] = nil
unregisterShortcutIfNeeded(for: name)
}
}
}
@available(macOS 10.15, *)
@available(*, deprecated, message: "Use events(for:) instead")
public static func on(_ type: EventType, for name: Name) -> AsyncStream<Void> {
AsyncStream { continuation in
let id = UUID()

View File

@ -3,25 +3,18 @@ import SwiftUI
@available(macOS 12, *)
extension View {
public func onKeyboardShortcut(_ shortcut: KeyboardShortcuts.Name, perform: @escaping (KeyboardShortcuts.EventType) -> Void) -> some View {
self
.task {
for await _ in KeyboardShortcuts.on(.keyDown, for: shortcut) {
perform(.keyDown)
}
}
.task {
for await _ in KeyboardShortcuts.on(.keyUp, for: shortcut) {
perform(.keyUp)
}
task {
for await event in KeyboardShortcuts.events(for: shortcut) {
perform(event)
}
}
}
public func onKeyboardShortcut(_ shortcut: KeyboardShortcuts.Name, event: KeyboardShortcuts.EventType, perform: @escaping () -> Void) -> some View {
self
.task {
for await _ in KeyboardShortcuts.on(event, for: shortcut) {
perform()
}
task {
for await shortcutEvent in KeyboardShortcuts.events(for: shortcut) where shortcutEvent == event {
perform()
}
}
}
}