sindresorhus / KeyboardShortcuts

⌨️ Add user-customizable global keyboard shortcuts (hotkeys) to your macOS app in minutes
https://swiftpackageindex.com/sindresorhus/KeyboardShortcuts/documentation/keyboardshortcuts/keyboardshortcuts
MIT License
1.99k stars 184 forks source link

How to delete keyboard shortcut of a dynamic item in the list? #168

Closed pradeepb28 closed 5 months ago

pradeepb28 commented 5 months ago

I am trying to understand how can we set keyboard shortcut item for a dynamic list item here https://github.com/sindresorhus/KeyboardShortcuts/blob/main/Example/KeyboardShortcutsExample/MainScreen.swift#L31

Is it possible to delete the keyboard shortcut when an item in dynamic list is deleted? If so, it would really helpful if you have an example for that.

sindresorhus commented 5 months ago

You would have to do this yourself. You could add a onChange listener for the source of the list, and whenever it changes, check if any keyboard names were removed, and then call KeyboardShortcuts.reset().

pradeepb28 commented 5 months ago

I feel like I understand and didn't understand at the same time :)

Probably I will give a detailed example, how I want to use in my app.

  1. Dynamic list is saved as Coredata entites. Each entity also includes the keyboard name and keyboard shortcut code.
  2. When a user delete the entity, the corresponding name and shortcut code will also be deleted from Coredata.
  3. At the same time, it should also delete from KeyboardShortcuts storage of that corresponding name and the code.

How would I approach this? Does my flow actually works or do you have any recommendations to approach it differently?

Thank you :) @sindresorhus

sindresorhus commented 5 months ago

Listen to Core Data entities being deleted and then delete the KeyboardShortcuts storage.

This is what I do in one of my apps:

struct Folder: Defaults.Serializable {
    let id: UUID
    var title: String?
}

extension Folder {
    var toggleMenuShortcutName: KeyboardShortcuts.Name { .init(id.uuidString) }
}

extension Folder {
    func remove() {
        KeyboardShortcuts.reset(toggleMenuShortcutName)
        Defaults[.folders] = Defaults[.folders].identifiableRemovingAll(self)
    }
}