Skip to content

Commit 8271537

Browse files
Add ability to set default shortcut (#13)
Co-authored-by: Sindre Sorhus <[email protected]>
1 parent e33b6cb commit 8271537

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

Sources/KeyboardShortcuts/KeyboardShortcuts.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,10 +211,14 @@ public enum KeyboardShortcuts {
211211
return
212212
}
213213

214-
UserDefaults.standard.removeObject(forKey: userDefaultsKey(for: name))
214+
UserDefaults.standard.set(false, forKey: userDefaultsKey(for: name))
215215
unregister(shortcut)
216216
userDefaultsDidChange(name: name)
217217
}
218+
219+
static func userDefaultsContains(name: Name) -> Bool {
220+
UserDefaults.standard.object(forKey: userDefaultsKey(for: name)) != nil
221+
}
218222
}
219223

220224
extension Notification.Name {

Sources/KeyboardShortcuts/Name.swift

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,28 @@ extension KeyboardShortcuts {
1313
```
1414
*/
1515
public struct Name: Hashable {
16-
// This is to allow `extension KeyboardShortcuts.Name { static let x = Name("x") }`.
16+
// These make it possible to use the types without the namespace.
17+
// `extension KeyboardShortcuts.Name { static let x = Name("x") }`.
1718
/// :nodoc:
1819
public typealias Name = KeyboardShortcuts.Name
20+
/// :nodoc:
21+
public typealias Shortcut = KeyboardShortcuts.Shortcut
1922

2023
public let rawValue: String
2124

22-
public init(_ name: String) {
25+
/**
26+
- Parameter name: Name of the shortcut.
27+
- Parameter default: Optional default key combination for the shortcut. Do not set this unless it's essential. Users find it annoying when random apps steal their existing keyboard shortcuts. It's generally better to show a welcome screen on the first app launch that lets the user set the shortcut.
28+
*/
29+
public init(_ name: String, default defaultShortcut: Shortcut? = nil) {
2330
self.rawValue = name
31+
32+
if
33+
let defaultShortcut = defaultShortcut,
34+
!userDefaultsContains(name: self)
35+
{
36+
userDefaultsSet(name: self, shortcut: defaultShortcut)
37+
}
2438
}
2539
}
2640
}

0 commit comments

Comments
 (0)