Search code examples
keyboardshortcutelm

Elm keyboard combination shortcut


In my Elm program I would like to have some keyboard shortcuts.

I have a shortcut d which does what I want, however, I want the key combination to be alt+d.

StartApp.start { 
    init = (emptyModel, Effects.none),
    view   = view, 
    update = update,
    inputs = [ Signal.map forwardKey Keyboard.presses]
    }

forwardKey : Int -> Action    
forwardKey keyCode =
  case (Char.fromCode keyCode) of
    'd' -> Add
    _ -> NoOp

I noticed that there is a keyboard.alt signal that returns Signal Bool to check if alt is pressed or not.

How can I apply change the shortcut from d to alt+d by using this signal?


Solution

  • See this answer to the same underlying question.

    Note that it's going to be difficult to impossible to capture Alt-D since that's a common key combination used by browsers. For example, Chrome shifts focus to the address bar when you press Alt-D. For this reason, I'll revert to the example above and use Alt-0 as the chord here:

    You can use map2 to create a new Boolean signal that tells if your key combination is pressed. We'll create a new signal called chordPressed like so:

    chordPressed : Signal Bool
    chordPressed =
      Signal.map2 (&&) Keyboard.alt (Keyboard.isDown <| Char.toCode '0')
    

    Now, we need to convert that signal to an Action before we can pass it into the inputs list.

    chordToAction : Signal Action
    chordToAction =
      let
        toAction b =
          case b of
            True -> Add
            False -> NoOp
      in
        Signal.dropRepeats
          <| Signal.map toAction chordPressed
    

    Now, you can pass chordToAction into the inputs list. Again, you might want to choose a key-chord that isn't going to be first caught by the browser, like Alt-D will.

    inputs = [ chordToAction ]