Convenience helpers for working with keyboard inputs.
Using Keyboard.Extra this way, you get all the help it can provide. Use either this approach, or the plain subscriptions and handle the state yourself.
The subscriptions needed for the "Msg and Update" way.
Use this (or updateWithKeyChange) to have the list of keys update.
If you need to know exactly what changed just now, have a look
at updateWithKeyChange.
This alternate update function answers the question: "Did the pressed down keys in fact change just now?"
You might be wondering why this is a Maybe KeyChange – it's because
keydown events happen many times per second when you hold down a key. Thus,
not all incoming messages actually cause a change in the model.
Note This is provided for convenience, and may not perform well in real
programs. If you are experiencing slowness or jittering when using
updateWithKeyChange, see if the regular update makes it go away.
The second value updateWithKeyChange may return, representing the actual
change that happened during the update.
Note: To find out if a key is being pressed, simply use
List.member key keyList.
Record type used for arrows and wasd.
Both x and y can range from -1 to 1, and are 0 if no keys are pressed.
Gives the arrow keys' pressed down state as follows:
arrows [] --> { x = 0, y = 0 }
arrows [ ArrowLeft ] --> { x = -1, y = 0 }
arrows [ ArrowUp, ArrowRight ] --> { x = 1, y = 1 }
arrows [ ArrowDown, ArrowLeft, ArrowRight ] --> { x = 0, y = -1 }Similar to arrows, gives the W, A, S and D keys' pressed down state.
wasd [] --> { x = 0, y = 0 }
wasd [ CharA ] --> { x = -1, y = 0 }
wasd [ CharW, CharD ] --> { x = 1, y = 1 }
wasd [ CharA, CharS, CharD ] --> { x = 0, y = -1 }Type representation of the arrows.
Gives the arrow keys' pressed down state as follows:
arrowsDirection [] --> NoDirection
arrowsDirection [ ArrowLeft ] --> West
arrowsDirection [ ArrowUp, ArrowRight ] --> NorthEast
arrowsDirection [ ArrowDown, ArrowLeft, ArrowRight ] --> South
-- (left and right cancel out)Similar to arrows, gives the W, A, S and D keys' pressed down state.
wasdDirection [] --> NoDirection
wasdDirection [ CharA ] --> West
wasdDirection [ CharW, CharD ] --> NorthEast
wasdDirection [ CharA, CharS, CharD ] --> SouthIf you prefer to only get "the facts" and do your own handling, use these subscriptions. Otherwise, you may be more comfortable with the Msg and Update.
Subscription for key down events.
Note When the user presses and holds a key, there may or may not be many of these messages before the corresponding key up message.
Subscription for key up events.
A Json.Decoder for grabbing event.keyCode and turning it into a Key
import Json.Decode as Json
onKey : (Key -> msg) -> Attribute msg
onKey tagger =
on "keydown" (Json.map tagger targetKey)Convert a key code into a Key.
fromCode 13 --> EnterConvert a Key into a key code.
toCode Enter --> 13These are all the keys that have names in Keyboard.Extra.
Keyboard.Extra's internal message type.