### Complete SwiftUI App Example with Keyboard Shortcuts Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt A full SwiftUI application demonstrating the integration of global keyboard shortcuts. This example includes defining shortcuts, managing their state with ObservableObjects, displaying shortcut information in the UI, and providing a settings view with shortcut recorders and reset functionality. ```swift import SwiftUI import KeyboardShortcuts extension KeyboardShortcuts.Name { static let toggleUnicornMode = Self("toggleUnicornMode") static let showSettings = Self("showSettings") } @main struct MyApp: App { @StateObject private var appState = AppState() var body: some Scene { WindowGroup { ContentView() .environmentObject(appState) } Settings { SettingsView() } } } @MainActor class AppState: ObservableObject { @Published var isUnicornMode = false init() { Task { for await event in KeyboardShortcuts.events(for: .toggleUnicornMode) where event == .keyUp { isUnicornMode.toggle() } } } } struct ContentView: View { @EnvironmentObject var appState: AppState var body: some View { VStack { Text(appState.isUnicornMode ? "Unicorn Mode Activated!" : "Normal Mode") .font(.largeTitle) if let shortcut = KeyboardShortcuts.getShortcut(for: .toggleUnicornMode) { Text("Press \(shortcut) to toggle") .foregroundStyle(.secondary) } else { Text("Set a shortcut in Settings") .foregroundStyle(.secondary) } } .padding() } } struct SettingsView: View { var body: some View { Form { Section("Keyboard Shortcuts") { KeyboardShortcuts.Recorder("Toggle Unicorn Mode:", name: .toggleUnicornMode) KeyboardShortcuts.Recorder("Open Settings:", name: .showSettings) } Section { Button("Reset All Shortcuts") { KeyboardShortcuts.reset(.toggleUnicornMode, .showSettings) } } } .padding() .frame(width: 400) } } ``` -------------------------------- ### Programmatically Getting and Setting Shortcuts Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Manage shortcuts programmatically for migration or custom storage scenarios. You can get, set, and clear shortcuts for specific names. ```swift import KeyboardShortcuts // Get the current shortcut for a name if let shortcut = KeyboardShortcuts.getShortcut(for: .toggleUnicornMode) { print("Current shortcut: \(shortcut)") print("Key: \(shortcut.key?.rawValue ?? -1)") print("Modifiers: \(shortcut.modifiers)") } // Set a shortcut programmatically let newShortcut = KeyboardShortcuts.Shortcut(.t, modifiers: [.command, .shift]) KeyboardShortcuts.setShortcut(newShortcut, for: .toggleUnicornMode) // Clear a shortcut KeyboardShortcuts.setShortcut(nil, for: .toggleUnicornMode) // Access via the Name's shortcut property let currentShortcut = KeyboardShortcuts.Name.toggleUnicornMode.shortcut KeyboardShortcuts.Name.toggleUnicornMode.shortcut = newShortcut ``` -------------------------------- ### Listen for KeyboardShortcut Events Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md Listen for keyboard shortcut events using `KeyboardShortcuts.events(for:)`. This must be done within a `Task` or `async` context. The example shows listening for a key-up event. ```swift import SwiftUI import KeyboardShortcuts // 3. Listen for events (must be inside a Task or async context) Task { for await eventType in KeyboardShortcuts.events(for: .toggleMainWindow) where eventType == .keyUp { toggleMainWindow() } } ``` -------------------------------- ### Programmatic Shortcut Management Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Methods to get, set, and clear shortcuts programmatically. ```APIDOC ## KeyboardShortcuts.getShortcut / setShortcut ### Description Allows manual retrieval and modification of shortcut assignments. ### Parameters - **name** (KeyboardShortcuts.Name) - Required - The shortcut name identifier. - **shortcut** (KeyboardShortcuts.Shortcut?) - Optional - The shortcut object to assign or nil to clear. ### Request Example KeyboardShortcuts.setShortcut(newShortcut, for: .toggleUnicornMode) ``` -------------------------------- ### Get Modifier Key Symbols Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Obtain symbolic string representations for modifier keys used in keyboard shortcuts. This is useful for displaying shortcuts in a user-friendly format. ```swift import AppKit import KeyboardShortcuts let modifiers = NSEvent.ModifierFlags([.command, .shift]) print(modifiers.ks_symbolicRepresentation) // Outputs: "⇧⌘" if let shortcut = KeyboardShortcuts.getShortcut(for: .toggleUnicornMode) { print(shortcut.modifiers.ks_symbolicRepresentation) // e.g., "⌘⌥" } ``` -------------------------------- ### Magnet Migration: Before Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md This snippet demonstrates the 'before' state when migrating from Magnet, showing how HotKeys were defined with identifiers, key combos, targets, and actions, and registered with the HotKeyCenter. ```swift import Magnet let hotKey = HotKey( identifier: "toggleMainWindow", keyCombo: KeyCombo(key: .j, cocoaModifiers: [.command, .shift]), target: self, action: #selector(toggleMainWindow) ) hotKey.keyDownHandler = { toggleMainWindow() } hotKey.keyUpHandler = { // Optional } HotKeyCenter.shared.register(with: hotKey) ``` -------------------------------- ### Listen to a hard-coded global shortcut Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/readme.md Use this to monitor specific key combinations globally. Requires an active Task to observe events. ```swift import KeyboardShortcuts let shortcut = KeyboardShortcuts.Shortcut(.a, modifiers: [.command]) Task { for await eventType in KeyboardShortcuts.events(for: shortcut) where eventType == .keyUp { // Do something. } } ``` -------------------------------- ### Legacy Callback-Based Listening with onKeyDown and onKeyUp Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Use `onKeyDown` and `onKeyUp` for traditional event handling. Prefer `events(for:)` for new code. ```swift import AppKit import KeyboardShortcuts @main final class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { KeyboardShortcuts.onKeyDown(for: .toggleUnicornMode) { print("Shortcut pressed down!") } KeyboardShortcuts.onKeyUp(for: .toggleUnicornMode) { print("Shortcut released!") toggleUnicornMode() } } private func toggleUnicornMode() { // Toggle your feature } } ``` -------------------------------- ### ShortcutRecorder Migration: Before Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md This snippet shows the 'before' state when migrating from ShortcutRecorder, illustrating how shortcut values were previously bound to UserDefaults using a specific key path and value transformer. ```swift import ShortcutRecorder recorderControl.bind( .objectValue, to: UserDefaultsController.shared, withKeyPath: "values.toggleMainWindow", options: [.valueTransformerName: NSValueTransformerName.keyedUnarchiveFromDataTransformerName] ) ``` -------------------------------- ### Implement SwiftUI Recorder View Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Use KeyboardShortcuts.Recorder to provide a UI for users to record shortcuts, which are automatically persisted to UserDefaults. ```swift import SwiftUI import KeyboardShortcuts struct SettingsScreen: View { var body: some View { Form { KeyboardShortcuts.Recorder("Toggle Unicorn Mode:", name: .toggleUnicornMode) KeyboardShortcuts.Recorder("Show Main Window:", name: .showMainWindow) KeyboardShortcuts.Recorder("Capture Screenshot:", name: .captureScreenshot) } } } ``` -------------------------------- ### KeyboardShortcuts Rollout Sequence: Write and Remove Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md This snippet demonstrates the recommended sequence for rolling out KeyboardShortcuts. It involves writing new shortcuts using `KeyboardShortcuts.setShortcut` and removing old dependencies only after successful conversion. ```swift // 2. Write with KeyboardShortcuts.setShortcut // 3. Remove the old stored value only after successful conversion. // 4. Remove the old dependency. ``` -------------------------------- ### MASShortcut Migration: Before Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md This snippet shows the 'before' state when migrating from MASShortcut, demonstrating how shortcuts were previously associated with UserDefaults keys and bound to actions. ```swift import MASShortcut shortcutView.associatedUserDefaultsKey = "toggleMainWindow" MASShortcutBinder.shared().bindShortcut(withDefaultsKey: "toggleMainWindow") { toggleMainWindow() } ``` -------------------------------- ### Implement SwiftUI Recorder with onChange Callback Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Use the onChange callback to execute custom logic or handle data migration when a shortcut is updated. ```swift import SwiftUI import KeyboardShortcuts struct SettingsScreen: View { var body: some View { Form { KeyboardShortcuts.Recorder("Toggle Mode:", name: .toggleUnicornMode) { shortcut in if let shortcut { print("User set shortcut: \(shortcut)") // Perform custom storage or migration } else { print("User cleared the shortcut") } } } } } ``` -------------------------------- ### Implement in-app customizable shortcuts Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/readme.md Uses a Recorder view to allow users to define shortcuts that trigger actions only when the app is focused. ```swift import SwiftUI import KeyboardShortcuts struct ContentView: View { @State private var shortcut: KeyboardShortcuts.Shortcut? var body: some View { VStack { KeyboardShortcuts.Recorder("Record shortcut", shortcut: $shortcut) Button("Perform Action") { performAction() } .keyboardShortcut(shortcut?.toSwiftUI) } } } ``` -------------------------------- ### Define Shortcut Names with Initial Values Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Provide default keyboard shortcuts during definition. Use sparingly to avoid overriding user preferences. ```swift import KeyboardShortcuts extension KeyboardShortcuts.Name { // Sets Command+Option+K as the initial shortcut static let toggleUnicornMode = Self( "toggleUnicornMode", initial: .init(.k, modifiers: [.command, .option]) ) // Sets Control+Shift+S as the initial shortcut static let saveDocument = Self( "saveDocument", initial: .init(.s, modifiers: [.control, .shift]) ) } ``` -------------------------------- ### Implement SwiftUI Recorder with Binding Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Use a binding to manage shortcut storage manually. Note that this mode does not automatically register the shortcut as a global hotkey. ```swift import SwiftUI import KeyboardShortcuts struct CustomStorageView: View { @State private var shortcut: KeyboardShortcuts.Shortcut? var body: some View { VStack { KeyboardShortcuts.Recorder("Record shortcut:", shortcut: $shortcut) Button("Perform Action") { performAction() } .keyboardShortcut(shortcut?.toSwiftUI) if let shortcut { Text("Current shortcut: \(shortcut.description)") } } } private func performAction() { print("Action performed!") } } ``` -------------------------------- ### Implement SwiftUI Recorder with Custom Label Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Customize the appearance of the recorder by providing a custom label view. ```swift import SwiftUI import KeyboardShortcuts struct SettingsScreen: View { var body: some View { Form { KeyboardShortcuts.Recorder(for: .toggleUnicornMode) { HStack { Image(systemName: "keyboard") Text("Toggle Unicorn Mode") Spacer() } } } } } ``` -------------------------------- ### Listen for shortcut events Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/readme.md Register a callback for a shortcut using onKeyUp or onKeyDown within an observable class. ```swift import SwiftUI import KeyboardShortcuts @main struct YourApp: App { @State private var appState = AppState() body: some Scene { WindowGroup { // … } Settings { SettingsScreen() } } } @MainActor @Observable final class AppState { init() { KeyboardShortcuts.onKeyUp(for: .toggleUnicornMode) { [self] in isUnicornMode.toggle() } } } ``` -------------------------------- ### AppKit Recorder View Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Integrate `KeyboardShortcuts.RecorderCocoa` into AppKit applications to provide a view for recording keyboard shortcuts. ```swift import AppKit import KeyboardShortcuts final class SettingsViewController: NSViewController { override func loadView() { view = NSView() view.frame = NSRect(x: 0, y: 0, width: 300, height: 100) let label = NSTextField(labelWithString: "Toggle Unicorn Mode:") label.frame = NSRect(x: 20, y: 50, width: 150, height: 20) let recorder = KeyboardShortcuts.RecorderCocoa(for: .toggleUnicornMode) recorder.frame = NSRect(x: 180, y: 45, width: 100, height: 30) view.addSubview(label) view.addSubview(recorder) } } ``` -------------------------------- ### Callback-Based Listening Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Legacy methods for handling key down and key up events using closures. ```APIDOC ## KeyboardShortcuts.onKeyDown / onKeyUp ### Description Registers a callback to be executed when a specific shortcut is pressed or released. ### Parameters - **name** (KeyboardShortcuts.Name) - Required - The shortcut name identifier. - **callback** (Closure) - Required - The function to execute on event. ### Request Example KeyboardShortcuts.onKeyDown(for: .toggleUnicornMode) { print("Shortcut pressed down!") } ``` -------------------------------- ### Iterate over all keyboard shortcuts Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/readme.md Conform to CaseIterable to manage and filter registered shortcut names. ```swift import KeyboardShortcuts extension KeyboardShortcuts.Name { static let foo = Self("foo") static let bar = Self("bar") } extension KeyboardShortcuts.Name: CaseIterable { public static let allCases: [Self] = [ .foo, .bar ] } // … print(KeyboardShortcuts.Name.allCases) ``` ```swift print(KeyboardShortcuts.Name.allCases.filter { $0.shortcut != nil }) ``` -------------------------------- ### Add a shortcut recorder in Cocoa Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/readme.md Use KeyboardShortcuts.RecorderCocoa to integrate shortcut recording into an NSViewController. ```swift import AppKit import KeyboardShortcuts final class SettingsViewController: NSViewController { override func loadView() { view = NSView() let recorder = KeyboardShortcuts.RecorderCocoa(for: .toggleUnicornMode) view.addSubview(recorder) } } ``` -------------------------------- ### Create Shortcuts from Key Events Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Create KeyboardShortcut objects from NSEvent instances for custom key handling scenarios. This allows you to interpret raw key press events into a structured shortcut representation. ```swift import AppKit import KeyboardShortcuts func handleKeyEvent(_ event: NSEvent) { if let shortcut = KeyboardShortcuts.Shortcut(event: event) { print("User pressed: \(shortcut)") print("Key code: \(shortcut.carbonKeyCode)") print("Modifiers: \(shortcut.carbonModifiers)") } } ``` -------------------------------- ### ShortcutRecorder Migration: After Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md This snippet shows the 'after' state for ShortcutRecorder migration, replacing the old recorder control with the `KeyboardShortcuts.Recorder` view. This is typically used within a SwiftUI `SettingsView`. ```swift import SwiftUI import KeyboardShortcuts struct SettingsView: View { var body: some View { KeyboardShortcuts.Recorder("Toggle Main Window:", name: .toggleMainWindow) } } ``` -------------------------------- ### Define an initial keyboard shortcut Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/readme.md Sets a default shortcut for a name. Avoid using this in publicly distributed apps to prevent overriding user preferences. ```swift import KeyboardShortcuts extension KeyboardShortcuts.Name { static let toggleUnicornMode = Self("toggleUnicornMode", initial: .init(.k, modifiers: [.command, .option])) } ``` -------------------------------- ### Configure Keyboard Shortcut Conflict Policies Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Control how the keyboard shortcut recorder handles conflicts with existing menu items, system shortcuts, or disallowed shortcuts. This allows for flexible conflict resolution strategies like warning or blocking. ```swift import SwiftUI import KeyboardShortcuts struct SettingsScreen: View { var body: some View { Form { // Warn instead of block on menu item conflicts KeyboardShortcuts.Recorder("Action 1:", name: .action1) .keyboardShortcutsConflictPolicy(.init(menuItem: .warn)) // Allow all conflicts (use with custom validation) KeyboardShortcuts.Recorder("Action 2:", name: .action2) .keyboardShortcutsConflictPolicy(.allowAll) // Custom policy KeyboardShortcuts.Recorder("Action 3:", name: .action3) .keyboardShortcutsConflictPolicy(.init( menuItem: .block, systemShortcut: .warn, disallowed: .block )) } } } ``` -------------------------------- ### Defining and Listening to Hard-Coded Shortcuts Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Listen to shortcuts defined directly in code without storing them in UserDefaults. Prefer user-customizable shortcuts when possible. ```swift import KeyboardShortcuts let emergencyShortcut = KeyboardShortcuts.Shortcut(.escape, modifiers: [.command, .option]) Task { for await eventType in KeyboardShortcuts.events(for: emergencyShortcut) where eventType == .keyUp { handleEmergencyAction() } } // With repeating key down (macOS 13+) let volumeUp = KeyboardShortcuts.Shortcut(.upArrow, modifiers: [.option]) Task { for await _ in KeyboardShortcuts.repeatingKeyDownEvents(for: volumeUp) { increaseVolume() } } ``` -------------------------------- ### MASShortcut Migration: After (Key Up Event) Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md This snippet shows the 'after' state for MASShortcut migration, matching MASShortcut's key-up event behavior with KeyboardShortcuts. Ensure this code is within a Task or async context. ```swift import KeyboardShortcuts // Inside a Task or async context for await eventType in KeyboardShortcuts.events(for: .toggleMainWindow) where eventType == .keyUp { toggleMainWindow() } ``` -------------------------------- ### Add KeyboardShortcuts Recorder to Settings View Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md Integrate the `KeyboardShortcuts.Recorder` into your settings UI to allow users to define their preferred shortcuts. This view requires a title and the associated `KeyboardShortcuts.Name`. ```swift import SwiftUI import KeyboardShortcuts // 2. Add a recorder to your settings view struct SettingsView: View { var body: some View { KeyboardShortcuts.Recorder("Toggle Main Window:", name: .toggleMainWindow) } } ``` -------------------------------- ### Magnet Value Migration Helper Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md A helper function to migrate legacy shortcut values to KeyboardShortcuts. It takes a new shortcut name and a closure to read the legacy carbon key code and modifiers. It only sets the shortcut if one doesn't already exist for the new name. ```swift import KeyboardShortcuts func migrateLegacyShortcut( newName: KeyboardShortcuts.Name, readLegacyCarbonValue: () -> (Int, Int)? ) { guard KeyboardShortcuts.getShortcut(for: newName) == nil else { return } guard let (carbonKeyCode, carbonModifiers) = readLegacyCarbonValue() else { return } KeyboardShortcuts.setShortcut(.init(carbonKeyCode: carbonKeyCode, carbonModifiers: carbonModifiers), for: newName) } ``` -------------------------------- ### Magnet Migration: After (Key Down Event) Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md This snippet shows the 'after' state for Magnet migration, matching Magnet's default key-down event behavior with KeyboardShortcuts. Ensure this code is within a Task or async context. ```swift import KeyboardShortcuts // Inside a Task or async context for await eventType in KeyboardShortcuts.events(for: .toggleMainWindow) where eventType == .keyDown { toggleMainWindow() } ``` -------------------------------- ### Listening with AsyncStream Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Listen for keyboard shortcut events using Swift's async/await pattern with `KeyboardShortcuts.events(for:)`. The listener automatically stops when the async sequence ends. ```swift import SwiftUI import KeyboardShortcuts struct ContentView: View { @State private var isUnicornMode = false var body: some View { Text(isUnicornMode ? "Unicorn Mode" : "Normal Mode") .task { for await event in KeyboardShortcuts.events(for: .toggleUnicornMode) { switch event { case .keyDown: print("Key pressed down") case .keyUp: isUnicornMode.toggle() } } } } } ``` -------------------------------- ### Resetting Shortcuts Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Methods to reset shortcuts to initial values or clear all stored configurations. ```APIDOC ## KeyboardShortcuts.reset / resetAll ### Description Resets specific shortcuts to their initial values or clears all stored shortcuts globally. ### Parameters - **names** (KeyboardShortcuts.Name...) - Optional - List of names to reset. ### Request Example KeyboardShortcuts.reset(.toggleUnicornMode) KeyboardShortcuts.resetAll() ``` -------------------------------- ### Listening for Repeating Key Down Events Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Listen for repeating key events while a shortcut is held down, respecting system key repeat settings. Available on macOS 13+. ```swift import SwiftUI import KeyboardShortcuts struct ScrollView: View { @State private var scrollPosition = 0 var body: some View { Text("Position: \(scrollPosition)") .task { for await _ in KeyboardShortcuts.repeatingKeyDownEvents(for: .moveSelectionDown) { scrollPosition += 1 } } } } ``` -------------------------------- ### KeyboardShortcuts Rollout Sequence: Migration Condition Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md This snippet shows the condition to use when migrating to KeyboardShortcuts, ensuring that new shortcuts are only migrated when no existing shortcut is found for the given name, thus avoiding overwriting user preferences. ```swift // 1. Migrate only when KeyboardShortcuts.getShortcut(for:) == nil to avoid overwriting user preferences. ``` -------------------------------- ### Register a keyboard shortcut name Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/readme.md Define a strongly-typed name for a shortcut by extending KeyboardShortcuts.Name. ```swift import KeyboardShortcuts extension KeyboardShortcuts.Name { static let toggleUnicornMode = Self("toggleUnicornMode") } ``` -------------------------------- ### Enabling and Disabling Shortcuts Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Control the active state of shortcuts globally or individually. ```APIDOC ## KeyboardShortcuts.enable / disable ### Description Temporarily toggle the functionality of specific shortcuts or the entire system. ### Parameters - **names** (KeyboardShortcuts.Name...) - Required - The shortcuts to enable or disable. ### Request Example KeyboardShortcuts.disable(.toggleUnicornMode) KeyboardShortcuts.isEnabled = false ``` -------------------------------- ### Add a shortcut recorder in SwiftUI Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/readme.md Use the KeyboardShortcuts.Recorder view within a SwiftUI Form to allow users to set their preferred shortcut. ```swift import SwiftUI import KeyboardShortcuts struct SettingsScreen: View { var body: some View { Form { KeyboardShortcuts.Recorder("Toggle Unicorn Mode:", name: .toggleUnicornMode) } } } ``` -------------------------------- ### Handle repeating key down events Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/readme.md Emits events based on system key repeat settings. Requires macOS 13 or later. ```swift import KeyboardShortcuts Task { for await _ in KeyboardShortcuts.repeatingKeyDownEvents(for: .moveSelectionDown) { // Move to the next item. } } ``` -------------------------------- ### Repeating Key Down Events Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Listen for repeating key events while a shortcut is held down, available on macOS 13+. ```APIDOC ## KeyboardShortcuts.repeatingKeyDownEvents ### Description Returns an AsyncSequence that emits events while the shortcut is held down, respecting system repeat settings. ### Parameters - **name** (KeyboardShortcuts.Name) - Required - The shortcut name identifier. ### Request Example for await _ in KeyboardShortcuts.repeatingKeyDownEvents(for: .moveSelectionDown) { scrollPosition += 1 } ``` -------------------------------- ### Migrate MASShortcut to KeyboardShortcuts Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Use this function to migrate existing shortcuts stored using MASShortcut to the KeyboardShortcuts format. It checks if a shortcut is already set for the new name and only proceeds if the legacy shortcut exists and the new one is not yet configured. The old shortcut is removed from UserDefaults after migration. ```swift import MASShortcut import KeyboardShortcuts func migrateMASShortcutValue(oldDefaultsKey: String, newName: KeyboardShortcuts.Name) { guard KeyboardShortcuts.getShortcut(for: newName) == nil, let legacyShortcut = UserDefaults.standard.object(forKey: oldDefaultsKey) as? MASShortcut else { return } KeyboardShortcuts.setShortcut( .init( carbonKeyCode: Int(legacyShortcut.keyCode), carbonModifiers: Int(legacyShortcut.modifierFlags) ), for: newName ) UserDefaults.standard.removeObject(forKey: oldDefaultsKey) } // Usage migrateMASShortcutValue(oldDefaultsKey: "toggleMainWindow", newName: .toggleUnicornMode) ``` -------------------------------- ### Define KeyboardShortcuts Name Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md Define a custom name for your keyboard shortcut using `KeyboardShortcuts.Name`. This is the first step in integrating KeyboardShortcuts into your application. ```swift import SwiftUI import KeyboardShortcuts // 1. Define a name extension KeyboardShortcuts.Name { static let toggleMainWindow = Self("toggleMainWindow") } ``` -------------------------------- ### Convert Shortcuts to SwiftUI KeyboardShortcut Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Convert a recorded KeyboardShortcuts.Shortcut to SwiftUI's native KeyboardShortcut type. This is useful for applying shortcuts using standard SwiftUI modifiers like .keyboardShortcut. ```swift import SwiftUI import KeyboardShortcuts struct ActionButton: View { let shortcut: KeyboardShortcuts.Shortcut? var body: some View { Button("Perform Action") { performAction() } .keyboardShortcut(shortcut?.toSwiftUI) } } ``` -------------------------------- ### Listening for Specific Event Types Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Filter keyboard shortcut events to listen only for `keyDown` or `keyUp` using `events(_:for:)`. This allows precise control over event handling. ```swift import SwiftUI import KeyboardShortcuts struct ContentView: View { @State private var isUnicornMode = false var body: some View { Text(isUnicornMode ? "Unicorn Mode" : "Normal Mode") .task { // Only fires on key up for await _ in KeyboardShortcuts.events(.keyUp, for: .toggleUnicornMode) { isUnicornMode.toggle() } } } } ``` -------------------------------- ### AppKit Recorder with Custom Validation Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Implement custom shortcut validation for AppKit recorders using the `validateShortcut` property. This allows defining rules to disallow specific shortcuts. ```swift import AppKit import KeyboardShortcuts let recorder = KeyboardShortcuts.RecorderCocoa(for: .action1) recorder.validateShortcut = { let otherActions: [KeyboardShortcuts.Name] = [.action2, .action3] if let conflict = otherActions.first(where: { $0.shortcut == shortcut }) { return .disallow(reason: "This shortcut is already used by \"\(.rawValue)\".") } return .allow } ``` -------------------------------- ### Iterate All Keyboard Shortcut Names Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Define custom shortcut names by extending KeyboardShortcuts.Name and conforming to CaseIterable. This allows you to retrieve all defined shortcut names, filter for those with assigned shortcuts, or access all stored names from UserDefaults. ```swift import KeyboardShortcuts extension KeyboardShortcuts.Name { static let action1 = Self("action1") static let action2 = Self("action2") static let action3 = Self("action3") } extension KeyboardShortcuts.Name: CaseIterable { public static let allCases: [Self] = [ .action1, .action2, .action3 ] } // Get all names print(KeyboardShortcuts.Name.allCases) // Get only names with assigned shortcuts let assignedShortcuts = KeyboardShortcuts.Name.allCases.filter { $0.shortcut != nil } print(assignedShortcuts) // Get all stored names (from UserDefaults) let storedNames = KeyboardShortcuts.storedNames ``` -------------------------------- ### Display Shortcuts in NSMenuItem Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Integrate keyboard shortcuts into NSMenuItems and ensure they stay synchronized with user changes. This involves setting the shortcut on the NSMenuItem and managing shortcut enablement/disablement when the menu is open or closed. ```swift import AppKit import KeyboardShortcuts extension KeyboardShortcuts.Name { static let toggleUnicornMode = Self("toggleUnicornMode") } class MenuManager: NSObject, NSMenuDelegate { let menu = NSMenu() var toggleMenuItem: NSMenuItem! func setupMenu() { toggleMenuItem = NSMenuItem( title: "Toggle Unicorn Mode", action: #selector(toggleAction), keyEquivalent: "" ) toggleMenuItem.target = self // Automatically shows and updates the shortcut toggleMenuItem.setShortcut(for: .toggleUnicornMode) menu.addItem(toggleMenuItem) menu.delegate = self } @objc func toggleAction() { print("Menu action triggered!") } // IMPORTANT: Disable global shortcuts while menu is open func menuWillOpen(_ menu: NSMenu) { KeyboardShortcuts.disable(.toggleUnicornMode) } func menuDidClose(_ menu: NSMenu) { KeyboardShortcuts.enable(.toggleUnicornMode) } } ``` -------------------------------- ### Enabling and Disabling Shortcuts Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Temporarily disable shortcuts without removing them. You can disable specific shortcuts or all shortcuts globally. ```swift import KeyboardShortcuts // Disable specific shortcuts KeyboardShortcuts.disable(.toggleUnicornMode, .showMainWindow) // Re-enable them KeyboardShortcuts.enable(.toggleUnicornMode, .showMainWindow) // Check if a shortcut is currently enabled let isEnabled = KeyboardShortcuts.isEnabled(for: .toggleUnicornMode) print("Shortcut enabled: \(isEnabled)") // Disable all shortcuts globally KeyboardShortcuts.isEnabled = false // Re-enable all shortcuts globally KeyboardShortcuts.isEnabled = true ``` -------------------------------- ### MASShortcut Value Migration Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/Sources/KeyboardShortcuts/KeyboardShortcuts.docc/Migration.md Migrates a MASShortcut value from UserDefaults to KeyboardShortcuts. It checks if a shortcut already exists for the new name, retrieves the legacy shortcut, converts it, and then removes the old UserDefaults entry. This function should be called once. ```swift import MASShortcut import KeyboardShortcuts func migrateMASShortcutValue(oldDefaultsKey: String, newName: KeyboardShortcuts.Name) { guard KeyboardShortcuts.getShortcut(for: newName) == nil, let legacyShortcut = UserDefaults.standard.object(forKey: oldDefaultsKey) as? MASShortcut else { return } KeyboardShortcuts.setShortcut( .init( carbonKeyCode: Int(legacyShortcut.keyCode), carbonModifiers: Int(legacyShortcut.modifierFlags) ), for: newName ) UserDefaults.standard.removeObject(forKey: oldDefaultsKey) } ``` -------------------------------- ### Convert modifier flags to symbols Source: https://github.com/sindresorhus/keyboardshortcuts/blob/main/readme.md Retrieves symbolic representations for modifier keys or existing shortcuts. ```swift import KeyboardShortcuts let modifiers = NSEvent.ModifierFlags([.command, .shift]) print(modifiers.ks_symbolicRepresentation) //=> "⇧⌘" // Also works with shortcuts: if let shortcut = KeyboardShortcuts.getShortcut(for: .toggleUnicornMode) { print(shortcut.modifiers.ks_symbolicRepresentation) //=> "⌘⌥" } ``` -------------------------------- ### Resetting Keyboard Shortcuts Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Reset shortcuts to their initial values or clear all stored shortcuts. This can be done for individual shortcuts, multiple shortcuts, or all shortcuts. ```swift import SwiftUI import KeyboardShortcuts struct SettingsScreen: View { var body: some View { Form { KeyboardShortcuts.Recorder("Toggle Mode:", name: .toggleUnicornMode) HStack { Button("Reset This") { // Reset to initial value (if defined) or nil KeyboardShortcuts.reset(.toggleUnicornMode) } Button("Reset Multiple") { KeyboardShortcuts.reset(.toggleUnicornMode, .showMainWindow) } Button("Reset All") { // Clears all stored shortcuts (ignores initial values) KeyboardShortcuts.resetAll() } } } } } ``` -------------------------------- ### SwiftUI View Modifier for Shortcuts Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Use the `onGlobalKeyboardShortcut` view modifier for a streamlined SwiftUI integration. The listener automatically stops when the view disappears. ```swift import SwiftUI import KeyboardShortcuts struct ContentView: View { @State private var isPressed = false @State private var toggleCount = 0 var body: some View { VStack { Text(isPressed ? "Pressed!" : "Released") Text("Toggle count: \(toggleCount)") } .onGlobalKeyboardShortcut(.toggleUnicornMode) { isPressed = eventType == .keyDown } .onGlobalKeyboardShortcut(.showMainWindow, type: .keyUp) { toggleCount += 1 } } } ``` -------------------------------- ### SwiftUI Global Keyboard Shortcut Display Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Associate global keyboard shortcuts with SwiftUI controls, allowing them to be displayed in menus. This modifier is used within SwiftUI views to link a button or menu item to a specific keyboard shortcut. ```swift import SwiftUI import KeyboardShortcuts struct MyMenuBarExtra: View { var body: some View { Menu("Actions") { Button("Toggle Unicorn Mode") { toggleUnicornMode() } .globalKeyboardShortcut(.toggleUnicornMode) Button("Show Window") { showWindow() } .globalKeyboardShortcut(.showMainWindow) } } } ``` -------------------------------- ### SwiftUI Recorder with Custom Validation Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Use the `shortcutValidation` modifier to validate shortcuts before saving in SwiftUI. It allows disallowing shortcuts based on conflicts or specific reserved combinations. ```swift import SwiftUI import KeyboardShortcuts struct SettingsScreen: View { var body: some View { Form { KeyboardShortcuts.Recorder(for: .action1) .shortcutValidation { let otherActions: [KeyboardShortcuts.Name] = [.action2, .action3] if let conflict = otherActions.first(where: { $0.shortcut == shortcut }) { return .disallow(reason: "This shortcut is already used by \"\(.rawValue)\".") } // Block a specific shortcut if shortcut == .init(.k, modifiers: .command) { return .disallow(reason: "Command+K is reserved for system use.") } return .allow } } } } ``` -------------------------------- ### Remove Keyboard Shortcut Handlers Source: https://context7.com/sindresorhus/keyboardshortcuts/llms.txt Clean up keyboard shortcut handlers when they are no longer needed to prevent memory leaks or unintended behavior. This can be done for specific shortcuts or for all registered handlers. ```swift import KeyboardShortcuts // Remove handlers for a specific shortcut KeyboardShortcuts.removeHandler(for: .toggleUnicornMode) // Remove all handlers (doesn't affect AsyncStream listeners) KeyboardShortcuts.removeAllHandlers() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.