2
votes

In my Elm program I would like to have some keyboard shortcuts. Now I have a shortcut 'd' who does what I want but 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 their is a keyboard.alt signal that return Signal Bool to check if alt is pressed or not.

I have not succeeded to let the combination work.

I'm new at Elm so any explanation is welcome.. Thanks a lot!

1

1 Answers

3
votes

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 ]