Nice keyboard inputs in Elm.
It is quite tedious to find out the currently pressed down keys with just the Keyboard module, so this package aims to make it easier.
You can use Keyboard.Extra in two ways:
North, NorthEast, etc. directions workupdateWithKeyChange to show when a key is pressed down and when it is releasedAll of the examples are also in the example directory in the repository.
If you use the "Intelligent Helper" way, you will get the most help, such as:
Key type, such as ArrowUp, CharA and EnterShift is pressed down when any kind of a Msg happens in your program{ x : Int, y : Int } or as a union type (e.g. South, NorthEast)When using Keyboard.Extra like this, it follows The Elm Architecture. Its model is a list of keys, and it has an update function and some subscriptions. Below are the necessary parts to wire things up. Once that is done, you can get useful information using the numerous helper functions such as isPressed, arrows and arrowsDirection.
Include the list of keys in your program's model
import Keyboard.Extra exposing (Key)
type alias Model =
{ pressedKeys : List Key
-- ...
}
init : ( Model, Cmd Msg )
init =
( { pressedKeys = []
-- ...
}
, Cmd.none
)Add the message type in your messages
type Msg
= KeyMsg Keyboard.Extra.Msg
-- ...Include the subscriptions for the events to come through (remember to add them in your main too)
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ Sub.map KeyMsg Keyboard.Extra.subscriptions
-- ...
]And finally, you can use update to have the list of keys be up to date
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
KeyMsg keyMsg ->
( { model | pressedKeys = Keyboard.Extra.update keyMsg model.pressedKeys }
, Cmd.none
)
-- ...Now you can get all the information anywhere where you have access to the model, for example like so:
calculateSpeed : Model -> Float
calculateSpeed model =
let
arrows =
Keyboard.Extra.arrows model.pressedKeys
in
model.currentSpeed + arrows.x
isShooting : Model -> Bool
isShooting model =
List.member Space model.pressedKeysHave fun! :)
PS. The Tracking Key Changes example example shows how to use updateWithKeyChange to find out exactly which key was pressed down / released on that update cycle.
With the "plain subscriptions" way, you get the bare minimum:
Key type, such as ArrowUp, CharA and EnterSetting up is very straight-forward:
type Msg
= KeyDown Key
| KeyUp Key
-- ...
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ Keyboard.Extra.downs KeyDown
, Keyboard.Extra.ups KeyUp
-- ...
]There's an example for this, too: Plain Subscriptions