Skip to content
Source
Sign inSign up
TanStack/hotkeys

feat: allow `enabled` to accept a callback for lazy evaluation #105

Closedp7gg(GitHub profile, opens in a new tab) opened this issue 3 comments

Feature Request

Summary

Currently, the enabled option in HotkeyOptions only accepts a boolean. It would be useful to also accept a callback (i.e. () => boolean) to support lazy evaluation.

Motivation

There are cases where the enabled state depends on values that are re-evaluated at hotkey trigger time, not at registration time. Having to re-register the hotkey every time that condition changes is cumbersome.

A callback form would allow users to defer the check to when the hotkey is actually fired:

useHotkeys('mod+s', save, {
  enabled: () => !isReadOnly,
})

Proposed API change

// Current
enabled?: boolean

// Proposed
enabled?: boolean | (() => boolean)

The implementation would just call enabled() instead of reading it directly when it's a function.

Alternatives considered

Passing a reactive enabled value that changes over time works, but requires the caller to manage that reactivity and causes unnecessary re-registrations.

  1. p7gg(GitHub profile, opens in a new tab) changed the title

  2. Hey @p7gg are you working on this issue? If not @KevinVandy can I work on this?

  3. @MdSadiqMd I'm not... Posted this just to gather the maintainer's thoughts before putting in any work.

  4. Every framework adapter now updates enabled on the existing registration instead of registering the hotkey again, so passing a reactive value already covers this.

    // React
    useHotkey('Mod+S', save, { enabled: !isReadOnly })
    
    // Solid
    createHotkey('Mod+S', save, () => ({ enabled: !isReadOnly() }))
  5. KevinVandy closed this

Sign in to join this conversation.